ai-renamer 项目介绍
ai-renamer 是一个智能文件重命名工具,它利用人工智能技术来分析文件内容并为其生成合适的新名称。这个项目是一个基于 Node.js 的命令行界面(CLI)工具,可以与多种大型语言模型(如 Llava、Gemma、Llama 等)配合使用,以实现智能化的文件重命名功能。
主要特点
-
多模型支持:ai-renamer 可以与 Ollama 和 LM Studio 提供的多种语言模型兼容,为用户提供了灵活的选择。
-
多文件类型支持:该工具不仅可以重命名图片文件,还支持视频和其他类型的文件重命名。
-
自定义选项:用户可以通过各种参数来自定义重命名过程,如指定模型、设置输出语言、定义文件名长度等。
-
多提供商支持:除了默认的 Ollama,ai-renamer 还支持 LM Studio 和 OpenAI 作为 AI 提供商。
-
配置持久化:用户的设置会被保存到本地配置文件中,方便后续使用。
使用方法
ai-renamer 的使用非常简单。用户可以通过 NPX 直接运行,也可以通过 NPM 全局安装后使用。基本的使用命令如下:
npx ai-renamer /path
或者全局安装后:
ai-renamer /path
高级配置
用户可以通过命令行参数来细化重命名过程:
- 选择提供商:可以选择 Ollama、LM Studio 或 OpenAI 作为 AI 提供商。
- 指定模型:用户可以指定使用的具体语言模型。
- 自定义输出:支持设置输出语言、文件名长度、命名风格等。
- 视频处理:可以设置从视频中提取的最大帧数。
- 自定义提示:允许用户添加自定义提示来引导 AI 的重命名过程。
技术亮点
- AI 驱动:利用先进的语言模型来理解文件内容并生成相应的文件名。
- 跨平台兼容:作为 Node.js 应用,可以在多种操作系统上运行。
- 可扩展性:支持多种 AI 提供商和模型,为未来的扩展提供了可能性。
- 用户友好:提供了直观的命令行界面和丰富的自定义选项。
总结
ai-renamer 是一个创新的文件管理工具,它巧妙地结合了人工智能和文件系统操作。无论是个人用户还是专业人士,都可以利用这个工具来提高文件组织的效率和准确性。随着 AI 技术的不断发展,ai-renamer 也有望在未来得到更多的功能扩展和性能提升。
ai-renamer
#!/usr/bin/env node
import path from 'node:path' import os from 'node:os' import fs from 'node:fs' import crypto from 'node:crypto' import { exec } from 'node:child_process' import { promisify } from 'node:util'
import yargs from 'yargs' import { hideBin } from 'yargs/helpers' import axios from 'axios' import ora from 'ora' import chalk from 'chalk' import sharp from 'sharp' import imageSize from 'image-size' import mimeTypes from 'mime-types' import changeCase from 'change-case' import { fileTypeFromFile } from 'file-type' import ffmpeg from 'fluent-ffmpeg' import { encode } from 'gpt-3-encoder' import { readdir } from 'node:fs/promises' // import { OpenAI } from 'openai';
const execAsync = promisify(exec)
const argv = yargs(hideBin(process.argv)) .option('provider', { alias: 'p', describe: 'Set the provider (e.g. ollama, openai, lm-studio)', type: 'string' }) .option('api-key', { alias: 'a', describe: 'Set the API key if you're using openai as provider', type: 'string' }) .option('base-url', { alias: 'u', describe: 'Set the API base URL (e.g. http://127.0.0.1:11434 for ollama)', type: 'string' }) .option('model', { alias: 'm', describe: 'Set the model to use (e.g. gemma2, llama3, gpt-4o)', type: 'string' }) .option('frames', { alias: 'f', describe: 'Set the maximum number of frames to extract from videos (e.g. 3, 5, 10)', type: 'number' }) .option('case', { alias: 'c', describe: 'Set the case style (e.g. camelCase, pascalCase, snakeCase, kebabCase)', type: 'string' }) .option('chars', { alias: 'x', describe: 'Set the maximum number of characters in the new filename (e.g. 25)', type: 'number' }) .option('language', { alias: 'l', describe: 'Set the output language (e.g. English, Turkish)', type: 'string' }) .option('include-subdirectories', { alias: 's', describe: 'Include files in subdirectories when processing (e.g: true, false)', type: 'string' }) .option('custom-prompt', { alias: 'r', describe: 'Add a custom prompt to the LLM (e.g. "Only describe the background")', type: 'string' }) .argv
const getConfig = () => { const homeDir = os.homedir() const configPath = path.join(homeDir, 'ai-renamer.json') let config = {} if (fs.existsSync(configPath)) { const configFile = fs.readFileSync(configPath, 'utf-8') config = JSON.parse(configFile) } return config }
const saveConfig = (config) => { const homeDir = os.homedir() const configPath = path.join(homeDir, 'ai-renamer.json') fs.writeFileSync(configPath, JSON.stringify(config, null, 2)) }
const updateConfig = (newConfig) => { const currentConfig = getConfig() const updatedConfig = { ...currentConfig, ...newConfig } saveConfig(updatedConfig) }
const config = getConfig()
const provider = argv.provider || config.provider || 'ollama' const apiKey = argv['api-key'] || config.apiKey || '' const baseUrl = argv['base-url'] || config.baseUrl || '' const model = argv.model || config.model || '' const frames = argv.frames || config.frames || 3 const caseStyle = argv.case || config.case || 'kebabCase' const chars = argv.chars || config.chars || 60 const language = argv.language || config.language || 'English' const includeSubdirectories = argv['include-subdirectories'] || config.includeSubdirectories || false const customPrompt = argv['custom-prompt'] || config.customPrompt || ''
updateConfig({ provider, apiKey, baseUrl, model, frames, case: caseStyle, chars, language, includeSubdirectories, customPrompt })
let OpenAI if (provider === 'openai') { const { OpenAI: OpenAIModule } = await import('openai') OpenAI = OpenAIModule }
const supportedImageFormats = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'avif'] const supportedVideoFormats = ['mp4', 'avi', 'mov', 'mkv', 'webm']
const getModelName = async () => {
if (provider === 'ollama') {
try {
const response = await axios.get(${baseUrl || 'http://localhost:11434'}/api/tags
)
const tags = response.data.models
const llavaModel = tags.find(tag => tag.toLowerCase().includes('llava'))
if (llavaModel) {
return llavaModel
} else {
console.log(chalk.yellow('No Llava model found. Please specify a model with --model flag.'))
process.exit(1)
}
} catch (error) {
console.error(chalk.red('Error fetching models from Ollama:', error.message))
process.exit(1)
}
} else if (provider === 'lm-studio') {
return 'default'
} else if (provider === 'openai') {
return model || 'gpt-4-vision-preview'
}
}
const transformCase = (str, caseStyle) => { if (changeCase[caseStyle]) { return changeCasecaseStyle } return str }
const getDirectoryFiles = async (dirPath, includeSubdirectories) => { const entries = await readdir(dirPath, { withFileTypes: true }) const files = []
for (const entry of entries) { const fullPath = path.join(dirPath, entry.name) if (entry.isFile()) { files.push(fullPath) } else if (entry.isDirectory() && includeSubdirectories === 'true') { files.push(...(await getDirectoryFiles(fullPath, includeSubdirectories))) } }
return files }
const extractFramesFromVideo = async (videoPath, outputDir, numFrames) => {
const videoName = path.basename(videoPath, path.extname(videoPath))
const outputPattern = path.join(outputDir, ${videoName}-%d.png
)
await new Promise((resolve, reject) => {
ffmpeg(videoPath)
.on('end', resolve)
.on('error', reject)
.screenshots({
count: numFrames,
folder: outputDir,
filename: ${videoName}-%i.png
})
})
const frames = []
for (let i = 1; i <= numFrames; i++) {
const framePath = path.join(outputDir, ${videoName}-${i}.png
)
if (fs.existsSync(framePath)) {
frames.push(framePath)
}
}
return frames }
const resizeImage = async (imagePath, maxWidth = 512, maxHeight = 512) => { const { width, height } = imageSize(imagePath) const aspectRatio = width / height
let newWidth, newHeight if (width > height) { newWidth = Math.min(width, maxWidth) newHeight = Math.round(newWidth / aspectRatio) } else { newHeight = Math.min(height, maxHeight) newWidth = Math.round(newHeight * aspectRatio) }
const resizedImageBuffer = await sharp(imagePath) .resize(newWidth, newHeight, { fit: 'inside' }) .toBuffer()
return resizedImageBuffer.toString('base64') }
const generateDescription = async (imageBase64, modelName) => { let response const systemPrompt = 'You are an expert in giving brief but rich descriptions of images and summarizing video content.' const maxTokens = 200 const maxRetries = 3 const retryDelay = 1000 // 1 second
const userPrompt = Generate a concise description of the image and suggest a file name based on its content. The response should be short, within ${maxTokens} tokens, in ${language}. ${customPrompt}
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
if (provider === 'ollama') {
response = await axios.post(${baseUrl || 'http://localhost:11434'}/api/generate
, {
model: modelName,
prompt: ${systemPrompt}\n\nImage: data:image/jpeg;base64,${imageBase64}\n\nHuman: ${userPrompt}\n\nAssistant:
,
stream: false
})
} else if (provider === 'lm-studio') {
response = await axios.post(${baseUrl || 'http://localhost:1234'}/v1/chat/completions
, {
messages: [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: [{ type: 'image_url', image_url: { url: data:image/jpeg;base64,${imageBase64}
} }, { type: 'text', text: userPrompt }] }
],
max_tokens: maxTokens,
stream: false
})
} else if (provider === 'openai') {
const openai = new OpenAI({
apiKey,
baseURL: baseUrl || 'https://api.openai.com/v1'
})
response = await openai.chat.completions.create({
model: modelName,
messages: [
{ role: 'system', content: systemPrompt },
{
role: 'user',
content: [
{ type: 'text', text: userPrompt },
{ type: 'image_url', image_url: { url: `data:image/jpeg;base64,${imageBase64}` } }
]
}
],
max_tokens: maxTokens
})
}
// If successful, break out of the retry loop
break
} catch (error) {
console.error(`Attempt ${attempt} failed:`, error.message)
if (attempt === maxRetries) {
throw error // If all retries failed, throw the last error
}
// Wait before the next retry
await new Promise(resolve => setTimeout(resolve, retryDelay))
}
}
let description if (provider === 'ollama') { description = response.data.response } else if (provider === 'lm-studio') { description = response.data.choices[0].message.content } else if (provider === 'openai') { description = response.choices[0].message.content }
return description.trim() }
const generateVideoDescription = async (framePaths, modelName) => { const frameDescriptions = await Promise.all(framePaths.map(async (framePath) => { const imageBase64 = await resizeImage(framePath) return generateDescription(imageBase64, modelName) }))
const combinedDescription = frameDescriptions.join(' ')
let summaryResponse const systemPrompt = 'You are an expert in summarizing video content based on frame descriptions.'