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
用户可以通过命令行参数来细化重命名过程:
ai-renamer 是一个创新的文件管理工具,它巧妙地结合了人工智能和文件系统操作。无论是个人用户还是专业人士,都可以利用这个工具来提高文件组织的效率和准确性。随着 AI 技术的不断发展,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.'
最强AI数据分析助手
小浣熊家族Raccoon,您的AI智能助手,致力于通过先进的人工智能技术,为用户提供高效、便捷的智能服务。无论是日常咨询还是专业问题解答,小浣熊都能以快速、准确的响应满足您的需求,让您的生活更加智能便捷。
像人一样思考的AI智能体
imini 是一款超级AI智能体,能根据人类指令,自主思考、自主完成、并且交付结果的AI智能体。
AI数字人视频创作平台
Keevx 一款开箱即用的AI数字人视频创作平台,广泛适用于电商广告、企业培训与社媒宣传,让全球企业与个人创作者无需拍摄剪辑,就能快速生成多语言、高质量的专业视频。
一站式AI创作平台
提供 AI 驱动的图片、视频生成及数字人等功能,助力创意创作
AI办公助手,复杂任务高效处理
AI办公助手,复杂任务高效处理。办公效率低?扣子空间AI助手支持播客生成、PPT制作、网页开发及报告写作,覆盖科研、商业、舆情等领域的专家Agent 7x24小时响应,生活工作无缝切换,提升50%效率!
AI辅助编程,代码自动修复
Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。
AI小说写作助手,一站式润色、改写、扩写
蛙蛙写作—国内先进的AI写作平台,涵盖小说、学术、社交媒体等多场景。提供续写、改写、润色等功能,助力创作者高效优化写作流程。界面简洁,功能全面,适合各类写作者提升内容品质和工作效率。
全能AI智能助手,随时解答生活与工作的多样问题
问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。
实时语音翻译/同声传译工具
Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。
一键生成PPT和Word,让学习生活更轻松
讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。