惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Simon Willison's Weblog
Simon Willison's Weblog
Vercel News
Vercel News
博客园_首页
酷 壳 – CoolShell
酷 壳 – CoolShell
M
MIT News - Artificial intelligence
The Cloudflare Blog
N
Netflix TechBlog - Medium
GbyAI
GbyAI
Help Net Security
Help Net Security
Hugging Face - Blog
Hugging Face - Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
月光博客
月光博客
阮一峰的网络日志
阮一峰的网络日志
I
Intezer
Martin Fowler
Martin Fowler
量子位
P
Palo Alto Networks Blog
Security Latest
Security Latest
Attack and Defense Labs
Attack and Defense Labs
WordPress大学
WordPress大学
H
Help Net Security
C
Check Point Blog
T
Troy Hunt's Blog
C
CERT Recently Published Vulnerability Notes
Y
Y Combinator Blog
NISL@THU
NISL@THU
L
LINUX DO - 最新话题
V
Visual Studio Blog
C
Cisco Blogs
C
CXSECURITY Database RSS Feed - CXSecurity.com
S
Securelist
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
T
The Exploit Database - CXSecurity.com
人人都是产品经理
人人都是产品经理
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Recent Announcements
Recent Announcements
Forbes - Security
Forbes - Security
IT之家
IT之家
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Application and Cybersecurity Blog
Application and Cybersecurity Blog
L
LangChain Blog
AWS News Blog
AWS News Blog
N
News and Events Feed by Topic
Stack Overflow Blog
Stack Overflow Blog
H
Hacker News: Front Page
B
Blog
W
WeLiveSecurity
罗磊的独立博客
Jina AI
Jina AI
博客园 - 【当耐特】

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
How to Automate File Renaming with AI and OCR
Tighnari · 2026-05-27 · via DEV Community

Give your files names that actually describe what is inside them.


TL;DR

  • OCR reads text from PDFs and scanned documents; vision models describe photo content
  • A structured LLM prompt turns raw OCR output into reliable filename fields
  • Four Python functions cover the full pipeline in roughly 130 lines
  • Works on invoices, contracts, receipts, and mixed photo batches
  • Ends with a short note on when to build this yourself vs. reach for an existing tool

The Problem

Open a folder of scanned documents and you will almost certainly find the same pattern: scan_001.pdf, document_final_v3.docx, IMG_4382.jpg. The names tell you nothing. Search is broken. Downstream scripts that pattern-match on filenames fail silently. Someone on the team ends up doing the renaming manually, which works fine at ten files a week and falls apart at a hundred.

A naming convention helps, but only if everyone follows it. Getting a team to consistently name files {type}_{vendor}_{date}_{id} requires discipline that degrades under deadline pressure.

The better approach is to read what is inside each file and generate the name from that content. This tutorial walks you through building that pipeline.


What Content-Aware Renaming Actually Means

Content-aware renaming is not about reading file metadata. Metadata fields like creation date or the author field in an EXIF block are often wrong, empty, or filled with camera defaults that tell you nothing useful.

Reading the document's actual content requires two different approaches depending on what you are working with:

Text documents (PDFs, scanned invoices, contracts): OCR converts the rendered pixels or embedded text into a raw string. An LLM then pulls structured fields out of that string: document type, vendor name, date, reference number.

Photos and general images (receipts photographed on a phone, ID cards, site photos): OCR returns sparse or useless text on these. A vision model describes what is actually in the frame. The same LLM extraction step then processes that description.

Both paths produce the same output: a small dictionary of fields you feed into a filename template.


Pipeline Architecture

Here is the full flow in plain text:

Input file
    │
    ├─ PDF or text-heavy image
    │       └─ extract_text()    OCR or embedded text extraction
    │               └─ extract_fields()    LLM structured prompt
    │
    └─ Photo / general image
            └─ describe_image()    vision model
                    └─ extract_fields()    same LLM step
    │
    └─ build_filename()    template + sanitize
            └─ rename file on disk

Enter fullscreen mode Exit fullscreen mode

The two content paths share the field extraction and naming steps. Only the ingestion step differs based on what kind of file you are processing.


Step 1: Extract Text from the Document

For PDFs with embedded text, pdfplumber is faster and more accurate than rendering pages to images and running OCR on them. For scanned PDFs and standalone image files, pytesseract wraps Tesseract and handles most common formats.

import pdfplumber
import pytesseract
from PIL import Image
from pathlib import Path


def extract_text(file_path: str) -> str:
    """
    Extract text from a PDF (embedded or scanned) or image file.
    Returns raw text string. Returns empty string on failure.
    """
    path = Path(file_path)
    suffix = path.suffix.lower()

    if suffix == ".pdf":
        # Try embedded text first: faster and more accurate
        try:
            with pdfplumber.open(file_path) as pdf:
                pages = [page.extract_text() or "" for page in pdf.pages]
                combined = "\n".join(pages).strip()
                if len(combined) > 50:
                    return combined
        except Exception:
            pass

        # Fall back to OCR on the first page
        try:
            import pdf2image
            images = pdf2image.convert_from_path(
                file_path, first_page=1, last_page=1
            )
            if images:
                return pytesseract.image_to_string(images[0])
        except Exception:
            return ""

    elif suffix in {".jpg", ".jpeg", ".png", ".tiff", ".bmp"}:
        try:
            img = Image.open(file_path)
            return pytesseract.image_to_string(img)
        except Exception:
            return ""

    return ""

Enter fullscreen mode Exit fullscreen mode

Install: pip install pdfplumber pytesseract pdf2image Pillow

Tesseract itself requires a system install. On macOS: brew install tesseract. On Ubuntu or Debian: apt install tesseract-ocr.


Step 2: Extract Structured Fields with an LLM

Raw OCR output is noisy. Whitespace errors, page headers, footer fragments, and encoding artifacts all land in the string. An LLM handles this noise well if your prompt is tight and returns structured JSON.

import json
import openai

client = openai.OpenAI()  # reads OPENAI_API_KEY from environment


EXTRACTION_PROMPT = """
You are a document classifier. Given raw OCR text, extract exactly these fields as JSON:

- "doc_type": one of: invoice, contract, receipt, report, id_card, other
- "vendor_or_party": the main company or person name. Use "unknown" if not found.
- "date": the primary date in YYYY-MM-DD format. Use "unknown" if not found.
- "identifier": invoice number, contract ID, or reference number. Use "unknown" if not found.

Return ONLY valid JSON with these four keys. No explanation. No markdown fences.

OCR text:
{text}
"""


def extract_fields(raw_text: str) -> dict:
    """
    Send OCR text to GPT and return structured filename fields.
    Falls back to a safe default dict on any parse failure.
    """
    fallback = {
        "doc_type": "file",
        "vendor_or_party": "unknown",
        "date": "unknown",
        "identifier": "unknown",
    }

    if not raw_text.strip():
        return fallback

    prompt = EXTRACTION_PROMPT.format(text=raw_text[:3000])

    try:
        response = client.chat.completions.create(
            model="gpt-4o-mini",
            messages=[{"role": "user", "content": prompt}],
            temperature=0,
        )
        content = response.choices[0].message.content.strip()
        result = json.loads(content)
        for key in fallback:
            if key not in result:
                result[key] = "unknown"
        return result
    except Exception:
        return fallback

Enter fullscreen mode Exit fullscreen mode

temperature=0 keeps output deterministic across repeated runs on the same document. The 3,000-character cap limits token spend. For most invoices and contracts, the fields you need appear in the first page, well within that cap.

If you prefer Anthropic's API, the swap is straightforward. Replace openai.OpenAI() with anthropic.Anthropic() and use client.messages.create(model="claude-3-haiku-20240307", ...). The prompt itself works without changes.


Step 3: Build and Apply the Filename

With structured fields in hand, building the filename is a sanitize-and-join operation. The two things that will trip you up are illegal filesystem characters and name collisions.

import re
import hashlib


def sanitize(value: str) -> str:
    """Strip illegal filesystem characters and collapse whitespace."""
    value = value.strip()
    value = re.sub(r'[<>:"/\\|?*\x00-\x1f]', "", value)
    value = re.sub(r"\s+", "_", value)
    return value[:50]


def build_filename(fields: dict, original_path: str) -> str:
    """
    Assemble a descriptive filename from extracted fields.
    Format: {doc_type}_{vendor}_{date}_{identifier}{ext}
    Example: invoice_Acme_Corp_2024-03-15_INV-0042.pdf
    Unknown fields are dropped. Falls back to original stem + hash on total failure.
    """
    ext = Path(original_path).suffix.lower()

    parts = [
        sanitize(fields.get("doc_type", "file")),
        sanitize(fields.get("vendor_or_party", "")),
        sanitize(fields.get("date", "")),
    ]

    identifier = sanitize(fields.get("identifier", ""))
    if identifier and identifier.lower() != "unknown":
        parts.append(identifier)

    clean = [p for p in parts if p and p.lower() != "unknown"]

    if not clean:
        stem = Path(original_path).stem
        h = hashlib.md5(stem.encode()).hexdigest()[:6]
        clean = [sanitize(stem), h]

    return "_".join(clean) + ext


def rename_file(original_path: str, dry_run: bool = True) -> str:
    """
    Full text-document pipeline. Set dry_run=False to rename on disk.
    """
    raw_text = extract_text(original_path)
    fields = extract_fields(raw_text)
    new_name = build_filename(fields, original_path)

    original = Path(original_path)
    new_path = original.parent / new_name

    if dry_run:
        print(f"  [dry run] {original.name} -> {new_name}")
    else:
        original.rename(new_path)
        print(f"  renamed:  {original.name} -> {new_name}")

    return str(new_path)

Enter fullscreen mode Exit fullscreen mode

Run with dry_run=True first. Print the full preview list, spot-check a few filenames against the actual documents, then re-run with dry_run=False once you are satisfied.


Step 4: Handle Photos with a Vision Model

For photos, OCR returns little or nothing useful. A vision model can describe scene content and read visible text in context, which is exactly what you need for a photograph of a receipt or a scanned ID card.

import base64


def describe_image(file_path: str) -> str:
    """
    Use GPT-4o vision to describe an image for filename generation.
    Returns a plain-text description that extract_fields() can process.
    """
    path = Path(file_path)
    with open(file_path, "rb") as f:
        image_data = base64.b64encode(f.read()).decode("utf-8")

    ext = path.suffix.lower().lstrip(".")
    mime = "image/jpeg" if ext in ("jpg", "jpeg") else f"image/{ext}"

    try:
        response = client.chat.completions.create(
            model="gpt-4o",
            messages=[
                {
                    "role": "user",
                    "content": [
                        {
                            "type": "text",
                            "text": (
                                "Describe this image in 2-3 sentences for the purpose of "
                                "generating a descriptive filename. Include: the document "
                                "or scene type, any visible names, dates, or reference "
                                "numbers, and the primary subject. Be specific."
                            ),
                        },
                        {
                            "type": "image_url",
                            "image_url": {
                                "url": f"data:{mime};base64,{image_data}",
                                "detail": "low",
                            },
                        },
                    ],
                }
            ],
            max_tokens=200,
        )
        return response.choices[0].message.content.strip()
    except Exception:
        return ""


def rename_photo(file_path: str, dry_run: bool = True) -> str:
    """Photo pipeline: vision description -> field extraction -> rename."""
    description = describe_image(file_path)
    fields = extract_fields(description)
    new_name = build_filename(fields, file_path)

    original = Path(file_path)
    new_path = original.parent / new_name

    if dry_run:
        print(f"  [dry run] {original.name} -> {new_name}")
    else:
        original.rename(new_path)
        print(f"  renamed:  {original.name} -> {new_name}")

    return str(new_path)

Enter fullscreen mode Exit fullscreen mode

The "detail": "low" setting on the image URL cuts vision API costs by roughly 75% compared to the default. You do not need high-resolution analysis to figure out that a photo contains an Office Depot receipt dated February 28.


Edge Cases That Will Break Your Pipeline

Low-quality scans. Tesseract accuracy drops quickly below 150 DPI. Before passing a scanned image to pytesseract, convert it to grayscale with img.convert("L"), apply ImageFilter.SHARPEN, and scale up to 300 DPI if the image is smaller. Even basic preprocessing recovers meaningful accuracy on borderline scans.

Multi-language documents. Tesseract defaults to English. If your pipeline processes documents in French, German, or Japanese, pass the language code explicitly: pytesseract.image_to_string(img, lang="fra"). Documents that mix languages are harder to handle reliably and often need a detection step first. The langdetect library covers this well.

Handwriting. Tesseract handles printed text reliably. Cursive or informal handwriting produces garbage output. For those files, skip OCR entirely and route directly to the vision path, which handles handwriting considerably better (though with some inconsistency on complex script).

All-unknown extractions. When OCR returns junk and the LLM cannot extract any real fields, your pipeline produces a useless name. Track these cases: write them to a review list instead of renaming, so a human can handle the outliers without the rest of the batch stalling.

Name collisions. Two invoices from the same vendor on the same date will produce identical filenames. The build_filename function above uses a hash fallback on empty fields. You can extend it to also check whether the target path already exists and append a counter when it does.


Build It Yourself vs. Reach for a Tool

The pipeline above is around 130 lines. API costs are low: gpt-4o-mini extraction runs under $0.01 per document at typical invoice length. Vision calls for photos run a bit higher (around $0.01 to $0.03 each with detail: low), but that is manageable at moderate volume.

The maintenance cost is higher than it looks at first. Preprocessing edge cases, handling new document types, managing API key rotation, and wiring in a watch folder or webhook all take real time. If you are automating your own personal workflow, the code above is a solid foundation to build on.

If you are deploying this for a team or integrating it into a document management system, dedicated tools are worth a look. renamer.ai handles the OCR and vision path with a REST API and takes the maintenance overhead off your plate. Filebot is strong for media libraries with rule-based naming. AWS Textract makes sense if you are already on AWS and processing at high volume. The right call depends on whether owning the infrastructure is an asset or a cost for your situation.


Final Thoughts

A content-aware renaming pipeline that:

  • Reads embedded PDF text or runs Tesseract OCR on scanned documents
  • Describes photo content using a vision model
  • Extracts structured fields with a tight, zero-temperature LLM prompt
  • Applies a consistent, sanitized filename template
  • Routes files that cannot be reliably named to a manual review queue

Start with dry-run mode on a folder of test files. Review the preview output against what you actually expected. Once the extraction is working the way you want, flip to live mode and process in batches.

The four functions here are designed to stay independent, so you can swap in a different OCR library, point at a different model, or change the filename format without touching the rest.