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自动化工作流平台
无需编码,轻松生成可复用、可变现的AI自动化工作流

大模型驱动的Excel数据处理工具
基于大模型交互的表格处理系统,允许用户通过对话方式完成数据整理和可视化分析。系统采用机器学习算法解析用户指令,自动执行排序、公式计算和数据透视等操作,支持多种文件格式导入导出。数据处理响应速度保持在0.8秒以内,支持超过100万行数据的即时分析。


AI辅助编程,代码自动修复
Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。


AI论文写作指导平台
AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。


AI一键生成PPT,就用博思AIPPT!
博思AIPPT,新一代的AI生成PPT平台,支持智能生成PPT、AI美化PPT、文本&链接生成PPT、导入Word/PDF/Markdown文档生成PPT等,内置海量精美PPT模板,涵盖商务、教育、科技等不同风格,同时针对每个页面提供多种版式,一键自适应切换,完美适配各种办公场景。


AI赋能电商视觉革命,一站式智能商拍平台
潮际好麦深耕服装行业,是国内AI试衣效果最好的软件。使用先进AIGC能力为电商卖家批量提供优质的、低成本的商拍图。合作品牌有Shein、Lazada、安踏、百丽等65个国内外头部品牌,以及国内10万+淘宝、天猫、京东等主流平台的品牌商家,为卖家节省将近85%的出图成本,提升约3倍出图效率,让品牌能够快速上架。


企业专属的AI法律顾问
iTerms是法大大集团旗下法律子品牌,基于最先进的大语言模型(LLM)、专业的法律知识库和强大的智能体架构,帮助企业扫清合规障碍,筑牢风控防线,成为您企业专属的AI法律顾问。


稳定高效的流量提升解决方案,助力品牌曝光
稳定高效的流量提升解决方案,助力品牌曝光


最新版Sora2模型免费使用,一键生成无水印视频
最新版Sora2模型免费使用,一键生成无水印视频


实时语音翻译/同声传译工具
Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。
最新AI工具、AI资讯
独家AI资源、AI项目落地

微信扫一扫关注公众号