ai-renamer

ai-renamer

智能文件重命名CLI工具,兼容多种语言模型

基于Node.js的CLI工具,利用Ollama和LM Studio模型(如Llava、Gemma、Llama等)智能识别并重命名文件。支持重命名视频、图片及其他文件,适用于Ollama或LM Studio用户,并可配置OpenAI及自定义端口。通过简单的命令行操作,提供灵活的文件命名方式和多种参数设置,满足用户需求。

ai-renamerOllamaLM Studio文件重命名CLI工具Github开源项目

ai-renamer 项目介绍

ai-renamer 是一个智能文件重命名工具,它利用人工智能技术来分析文件内容并为其生成合适的新名称。这个项目是一个基于 Node.js 的命令行界面(CLI)工具,可以与多种大型语言模型(如 Llava、Gemma、Llama 等)配合使用,以实现智能化的文件重命名功能。

主要特点

  1. 多模型支持:ai-renamer 可以与 Ollama 和 LM Studio 提供的多种语言模型兼容,为用户提供了灵活的选择。

  2. 多文件类型支持:该工具不仅可以重命名图片文件,还支持视频和其他类型的文件重命名。

  3. 自定义选项:用户可以通过各种参数来自定义重命名过程,如指定模型、设置输出语言、定义文件名长度等。

  4. 多提供商支持:除了默认的 Ollama,ai-renamer 还支持 LM Studio 和 OpenAI 作为 AI 提供商。

  5. 配置持久化:用户的设置会被保存到本地配置文件中,方便后续使用。

使用方法

ai-renamer 的使用非常简单。用户可以通过 NPX 直接运行,也可以通过 NPM 全局安装后使用。基本的使用命令如下:

npx ai-renamer /path

或者全局安装后:

ai-renamer /path

高级配置

用户可以通过命令行参数来细化重命名过程:

  1. 选择提供商:可以选择 Ollama、LM Studio 或 OpenAI 作为 AI 提供商。
  2. 指定模型:用户可以指定使用的具体语言模型。
  3. 自定义输出:支持设置输出语言、文件名长度、命名风格等。
  4. 视频处理:可以设置从视频中提取的最大帧数。
  5. 自定义提示:允许用户添加自定义提示来引导 AI 的重命名过程。

技术亮点

  1. AI 驱动:利用先进的语言模型来理解文件内容并生成相应的文件名。
  2. 跨平台兼容:作为 Node.js 应用,可以在多种操作系统上运行。
  3. 可扩展性:支持多种 AI 提供商和模型,为未来的扩展提供了可能性。
  4. 用户友好:提供了直观的命令行界面和丰富的自定义选项。

总结

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.'

编辑推荐精选

Trae

Trae

字节跳动发布的AI编程神器IDE

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

热门AI工具生产力协作转型TraeAI IDE
问小白

问小白

全能AI智能助手,随时解答生活与工作的多样问题

问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。

聊天机器人AI助手热门AI工具AI对话
Transly

Transly

实时语音翻译/同声传译工具

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

讯飞智文

讯飞智文

一键生成PPT和Word,让学习生活更轻松

讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。

热门AI工具AI办公办公工具讯飞智文AI在线生成PPTAI撰写助手多语种文档生成AI自动配图
讯飞星火

讯飞星火

深度推理能力全新升级,全面对标OpenAI o1

科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。

模型训练热门AI工具内容创作智能问答AI开发讯飞星火大模型多语种支持智慧生活
Spark-TTS

Spark-TTS

一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型

Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。

咔片PPT

咔片PPT

AI助力,做PPT更简单!

咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。

讯飞绘文

讯飞绘文

选题、配图、成文,一站式创作,让内容运营更高效

讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。

AI助手热门AI工具AI创作AI辅助写作讯飞绘文内容运营个性化文章多平台分发
材料星

材料星

专业的AI公文写作平台,公文写作神器

AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。

openai-agents-python

openai-agents-python

OpenAI Agents SDK,助力开发者便捷使用 OpenAI 相关功能。

openai-agents-python 是 OpenAI 推出的一款强大 Python SDK,它为开发者提供了与 OpenAI 模型交互的高效工具,支持工具调用、结果处理、追踪等功能,涵盖多种应用场景,如研究助手、财务研究等,能显著提升开发效率,让开发者更轻松地利用 OpenAI 的技术优势。

下拉加载更多