Batch File Renaming
已吸收子管线(curator 合并 2026-10-16):AI 名词卡片批量重命名的 3 阶段智能识别管线(OCR 直读 → 感知哈希分组 → 知识库匹配,85-100% 识别率)原独立 skill
ai-flashcard-batch-rename已并入本 skill——管线 SOP 见references/ai-flashcard-3stage-pipeline.md,可复用脚本scripts/rename_flashcards.py,术语知识库references/terminology_knowledge_base.md。触发词:图片重命名 / AI名词卡片 / tXXX 编号 / 乱码文件名 / 豆包生成图。
Description
Renaming multiple files systematically, especially when files contain embedded identifiers (knowledge cards, labeled images, sequentially generated content). Use this skill whenever you need to rename a batch of files based on their content rather than just their filenames or timestamps.
When to Use
- Files generated sequentially (e.g., AI image generation with numbered filenames)
- Files contain visible identifiers (IDs, labels, titles) embedded in their content
- Need to standardize naming across a large set of files
- User provides a batch of files to organize/rename
Core Principles
✅ ZERO GUESSING RULE — User Mandate, NON-NEGOTIABLE
User corrections in Session 2026-07-13 elevated this from guideline to LAW:
"必须你自己识别再编号。不能猜。" "You must identify content yourself before renaming. No guessing."
"必须每一张都识别一次再编号。" "Must identify EVERY SINGLE file before numbering."
"必须解图片内容,提取编号信息,再重命名。" "Must read image content, extract number info, then rename."
"不能套用其它数据,也是只能识别。" "Cannot use preset data/lookup tables, can only recognize."
ABSOLUTE RULES — these override ALL shortcuts, ALL fallback patterns, ALL domain knowledge:
- Perform actual content recognition via OCR for EVERY FILE before renaming — NO EXCEPTIONS
- No lookup tables (
TERM_MAP), no preset term tables, no filename pattern matching - Do NOT sample "the first few" then assume a pattern holds
- Do NOT trust manifest files alone — they can be wrong
- The ONLY source of truth is the actual content of the file itself
If you cannot reliably identify files due to tool limitations:
- STOP and inform the user
- Ask for their help verifying a sample
- Propose a verification plan they can confirm before bulk processing
✅ ALWAYS Verify Content First
Never assume sequential order based on:
- Filename numbering (e.g.,
file (1).png,file (2).pngmay not correspond to actual content order) - File timestamps (generation order may not match logical order)
- File size patterns
✅ Use macOS Vision for Image Content (PRIMARY METHOD)
When files are images containing text labels:
- Use
scripts/ocr_macos_vision.swiftviaxcrun swift— this is the fastest, most reliable method - Crops automatically to top 15% where titles live, avoids noisy body content
- Extract ID numbers (T001, T002...), titles, or category labels from each image
- Use voting/consensus across multiple variations of the same term
- Verify mapping with user before bulk renaming
Example:
xcrun swift ~/.hermes/skills/batch-file-renaming/scripts/ocr_macos_vision.swift /path/to/image.png
Fallback options (use ONLY if macOS Vision fails):
browser_visionviabrowser_navigateto file:// URLtesseractcommand-line OCR (brew install tesseract)
✅ Work Safely
- Backup first - copy original files to a backup directory before any renaming
- Dry run - print proposed renames first for verification
- Incremental - rename one batch/term first and ask for confirmation before proceeding
- Document - keep a mapping file that records original → new filename for traceability
Step-by-Step Workflow
1. Inventory Files and Check for Manifest
ls -ltr /path/to/files/*.png | head -50 # sort by time, oldest first
Count files, identify naming patterns.
CRITICAL: Look for a manifest file first! Check for files like 00_总览.md, manifest.md, README.md that often contain:
- Exact term IDs and names
- Number of images per term
- Target naming conventions
- Project-specific metadata
This eliminates 90% of guesswork. Use the manifest as your source of truth, not assumptions.
2. Verify Content Identification
For the first few files, manually verify the content:
- Open first 4-8 files
- Identify what ID/label each file contains
- Confirm the pattern (e.g., 4 images per term, sequential IDs)
3. Create Mapping
Build a mapping table:
| Original File | Term ID | Variation | Target Name |
|---|---|---|---|
| image (1).png | T001 | v1 | T001-AI(人工智能)_v1.png |
| image (2).png | T001 | v2 | T001-AI(人工智能)_v2.png |
4. Execute Renaming
- Start with one batch (one term, 4 images)
- Verify results look correct
- Continue with remaining batches
Common Pitfalls
❌ Pitfall: Assuming Filename Numbers Match Content IDs
Problem: image (35).png may NOT contain T035 - it could be T009 or any other ID depending on generation order.
Fix: Always OCR or manually verify the actual ID on each card/image.
❌ Pitfall: Timestamps Are Not Trustworthy
Problem: Files with similar timestamps may be out of order due to parallel processing, network delays, or bulk saves.
Fix: Don't trust time ordering alone - verify content.
❌ Pitfall: Vision Tools Can Hallucinate
Problem: AI vision tools (especially browser_vision and vision_analyze) are unreliable. They may:
- Hallucinate completely unrelated content (e.g., medical terminology instead of AI knowledge cards)
- Report "cannot see the image" even when the page loaded
- Misread digits or labels
- Return cached results from previous images
Fix:
- Always spot-check — if the first identification looks wrong, stop
- Cross-verify with multiple tools or approaches
- When in doubt: ask the user to verify a sample
- Never assume "the tool worked" — validate the output makes contextual sense for the project
❌ Pitfall: Not Handling Missing/Extra Files
Problem: Some terms may have 3 images instead of 4, or duplicates may exist.
Fix: Count files per ID first, flag anomalies for user review before renaming.
❌ Pitfall: Domain Knowledge Fallback is FORBIDDEN by User Mandate
USER EXPLICITLY REJECTED preset term tables (Session 2026-07-13):
"必须解图片内容,提取编号信息,再重命名。" "Must read image content, extract number info, then rename."
"不能套用其它数据,也是只能识别。" "Cannot use preset data, can only recognize."
CONSEQUENCE: The TERM_MAP fallback pattern is DEPRECATED. You MUST NOT use filename patterns or preset lookup tables to skip actual content recognition. Even if you "know" the mapping, OCR EVERY FILE. The user corrected this explicitly after mislabeling occurred.
✅ macOS Vision Framework — Primary OCR Method (Reliable, Local, Fast)
Discovered in Session 2026-07-13: macOS has a built-in Vision framework accessible via Swift. This is the most reliable OCR method — no network, no hallucinations, no model downloads.
How to use:
- Create a Swift script (
ocr_top.swift):
import Vision
import AppKit
// Crop to TOP 15% where titles live — avoids distracting content
let img = NSImage(contentsOfFile: CommandLine.arguments[1])!
let cropRect = NSRect(x: 0, y: img.size.height * 0.85,
width: img.size.width, height: img.size.height * 0.15)
let request = VNRecognizeTextRequest()
request.recognitionLevel = .accurate
request.usesLanguageCorrection = false
try VNImageRequestHandler(cgImage: img.cgImage(forProposedRect: nil, context: nil, hints: nil)!,
options: [:]).perform([request])
for result in request.results ?? [] {
print(result.topCandidates(1)[0].string)
}
- Run and parse:
xcrun swift ocr_top.swift /path/to/image.png
Key Techniques:
- Crop to top region only (120px or ~15% of image height) — this is where titles/IDs live, eliminates noise from card body content
- Language correction OFF — preserves numbers and technical terminology
- Accurate level — better for small font and dense text
OCR Error Correction Patterns:
# Common OCR mistakes
corrections = {
'O': '0', 'o': '0', # Letter O -> zero
'I': '1', 'l': '1', # Uppercase i / lowercase L -> one
'S': '5', 'Z': '2', # Shape similarities
'B': '8', 'G': '6',
}
✅ Voting/Consensus Pattern for Term Names
When multiple images share the same number (e.g., 4 variations of t001):
- OCR all 4 images
- Count frequency of each extracted term name
- Use the most frequent name as the canonical name for that number
- Flag files that don't match for user review
# Example: 4 images for number 001
# Image 1: "人工智" (partial OCR)
# Image 2: "人工智能" ✓
# Image 3: "人工智能" ✓
# Image 4: "人工智" (partial OCR)
# Winner: "人工智能" (2 votes)
This corrects for partial OCR reads and ensures consistency across variations of the same term.
Tools
- ✅ PRIMARY: macOS Vision Framework - Use
scripts/ocr_macos_vision.swiftviaxcrun swift. Fast, local, reliable, no network, no hallucinations. Crops to top 15% where titles live. - ⚠️ Vision Tool Reliability Warning:
browser_visionandvision_analyzeare NOT 100% reliable. Known issues:- Local file paths often fail with "cannot see image" errors
- Hallucinations are common (returns unrelated content)
- Cached results from previous requests may be returned
- Use with extreme skepticism — verify every output makes sense
- OCR:
tesseract(install viabrew install tesseract) — backup option, but macOS Vision is preferred - File operations: Use
cpinstead ofmvfor safety (copy first, delete originals after verification) - Verification:
ls -lto confirm file counts after each batch - Batch processing: When
execute_codeis blocked, write a shell script and run it viaterminal
Example Pattern: AI Knowledge Cards
For AI knowledge card projects (each term has 4 variations):
- OCR first card using
scripts/ocr_macos_vision.swiftto confirm the workflow works - OCR 5th card to confirm it's the next term and verify pattern
- If pattern holds, proceed with batch processing using macOS Vision exclusively
- Use voting/consensus across the 4 variations of each term to get the canonical name
- Periodically spot-check throughout the process
References
- See
ai-vision/image-intelligence-platform/references/***SECRET***.mdfor session details on user's explicit mandate to use OCR exclusively (no preset tables) — moved 2026-10-23 to the image-intelligence-platform umbrella - See
ai-vision/image-intelligence-platform/references/flashcard-session-2026-07-13.mdfor detailed session notes on AI training platform knowledge card projects — moved 2026-10-23 to the image-intelligence-platform umbrella - See
scripts/ocr_macos_vision.swiftfor the macOS Vision Swift OCR script - See
references/***SECRET***.mdfor token-saving strategies - See
scripts/smart_rename_ai_cards.py— DEPRECATED by user mandate (2026-07-13), use macOS Vision OCR instead