Automated PDF Invoice Sorter – Script Organization

Clear professional description of the code solution

C
Christian Geimer
·Oct 11, 2026·
0 0 0
Free
Prompt
698 words

Task: Create a fully functional, production‑ready Python automation script that scans a folder of PDF invoices, extracts key information (vendor name, invoice date, total amount), and sorts each PDF into a structured directory hierarchy. The solution must include all supporting files, clear usage instructions, and be ready to run on a typical Windows/macOS/Linux environment.

Exact Requirements:

  1. Project Structure

    invoice_sorter/
    ├── invoice_sorter.py          # main executable script
    ├── config.yaml                # configurable parameters
    ├── requirements.txt           # pip dependencies
    └── README.md                  # usage guide
    
  2. Configuration (config.yaml)

    • source_folder: Path to the folder containing unsorted PDFs.
    • destination_root: Root folder where sorted invoices will be placed.
    • vendor_patterns: Mapping of vendor names to one or more regular‑expression patterns that can identify the vendor in the PDF text.
    • date_formats: List of date formats to try when parsing dates (e.g., "%Y-%m-%d", "%d/%m/%Y").
    • amount_regex: Regular expression to capture the total invoice amount (default should handle common formats like $1,234.56 or USD 1234.56).
    • log_file: Path to a log file for the script’s execution.

    Provide a sample config.yaml with at least three vendor entries (e.g., “Acme Corp”, “Globex Ltd”, “Initech”) and sensible defaults for the other fields.

  3. Dependencies (requirements.txt) Include exact package names and versions (if applicable) for:

    • PyPDF2 (or pdfplumber) for text extraction.
    • pytesseract and Pillow for OCR fallback.
    • pdf2image (if needed for OCR).
    • PyYAML for reading the config file.
    • python-dateutil for flexible date parsing.
    • loguru (or the standard logging module) for logging.
  4. Main Script (invoice_sorter.py)

    • Argument parsing: Accept optional command‑line arguments to override config.yaml values (--source, --dest, --log).
    • Logging: Initialize a logger that writes to both console and the file specified in the config. Include timestamps, log level, and clear messages.
    • PDF Processing Loop: For each PDF in source_folder (including subfolders):
      • Try to extract text using pdfplumber.
      • If extraction fails or yields < 30 characters, fall back to OCR (pytesseract on each page rendered via pdf2image).
      • Identify the vendor by matching the extracted text against the vendor_patterns. If no match, label as UNKNOWN_VENDOR.
      • Locate the invoice date using the list of date_formats and dateutil.parser. If multiple dates are found, pick the one that appears after the vendor name or within the first two pages.
      • Extract the total amount using amount_regex. Normalize to a float with two decimal places.
    • Folder Creation: Build the destination path as: {destination_root}/{year}/{month}/{vendor_name}/ where year and month are derived from the invoice date (YYYY/MM). If the date is missing, use UNKNOWN_DATE.
    • File Moving: Move (or copy, based on a --copy flag) the PDF to the target folder, preserving the original filename. If a file with the same name already exists, append a numeric suffix to avoid overwriting.
    • Error Handling: Gracefully handle corrupted PDFs, missing metadata, or permission issues. Log each error with a clear description and continue processing remaining files.
    • Summary Report: At the end, print and log a concise summary: total files processed, successfully sorted, files with unknown vendor/date, and any errors.
  5. Code Quality

    • Use type hints throughout.
    • Include docstrings for all functions and classes following the Google style.
    • Add inline comments explaining non‑obvious logic (e.g., OCR fallback decision).
    • Structure the script with a main() entry point and separate helper functions (e.g., _extract_text, _detect_vendor, _parse_date, _extract_amount).
  6. README (README.md)

    • Brief project description.
    • Prerequisites (e.g., Tesseract OCR installation instructions for each OS).
    • Step‑by‑step setup: cloning the repo, creating a virtual environment, installing dependencies, editing config.yaml.
    • Usage examples: basic run, overriding config via CLI, enabling copy mode.
    • Troubleshooting tips for common failure points (OCR not installed, unreadable PDFs, regex mismatches).

Expected Output Format:

  • Provide the complete config.yaml content inside a fenced code block labeled yaml.
  • Provide the full requirements.txt inside a fenced code block labeled text.
  • Provide the entire invoice_sorter.py source inside a fenced code block labeled python.
  • Provide the complete README.md inside a fenced code block labeled markdown.

Each file should be ready to copy‑paste into the appropriate location without further modification (aside from optional path adjustments in config.yaml). Ensure that the script runs with python invoice_sorter.py after installing the listed requirements.

Need help?

Connect with verified experts who can help you succeed.

Related Prompts

More prompts in Productivity & Workflow

View All
Productivity & Workflow
Universal

This Is A Prompt For Retrieval Augmented Generation. It Is Useful For Chat, QA, Or Other Applications That Rely On Passing Context To An LLM.

This is a prompt for retrieval-augmented-generation. It is useful for chat, QA, or other applications that rely on passing context to an LLM.

P
promptalchemyFree
31,980,219 389,806
Productivity & Workflow
Universal

Calculate BMI, export exercise and eating schedule

Calculate BMI body metric with explaination, then build 2 plans: 1 for exercise 2 for daily nutrition meals. Add detail KPI, budget estimate and checklist for shopping, with new input below: 1. your gender, age, weight & height (with unit name): {male, 27, 65kg, 1m65} 2. additional health goals & condition: {not sick, using cigarette}

S
schemawriter$1.99
6,544 6,581
Productivity & Workflow
Universal

Gym Routine Creation - Work Out Regiment

Generate a custom gym routine for yourself. Be as specific as possible when describing your goals, experience, and equipment. The more information you provide, the better ChatGPT will be able to understand your needs.

A
aiblueprint$1.99
5,188 5,189
Productivity & Workflow
Universal

Personalized Workout Plan Creation

Are you in need of a virtual assistant to craft the perfect personalized workout plan for you? Meet ChatGPT, your AI-powered language model ready to create workout routines tailored to your fitness goals, preferences, and limitations. ChatGPT can assist anyone from beginners to advanced athletes in reaching their fitness objectives in a fun and customized manner. Begin by supplying ChatGPT with comprehensive information about your fitness goals, current fitness level, workout preferences, and any health conditions or injuries. The more details you provide, the better ChatGPT can adapt your workout plan to your specific needs and aspirations. Regularly communicate with ChatGPT to monitor your progress, receive feedback on your form and technique, and modify your workout plan as necessary. ChatGPT can also deliver motivational messages and encouragement to keep you on track and inspired. Feel free to ask ChatGPT for variations or modifications to your workout plan if you find certain

P
promptstack$1.99
5,091 5,102
Productivity & Workflow
Universal

Growth Mindset Guru

Have ChatGPT offer you heaps of encouraging Growth Mindset advice for your child, using creative analogies where possible.

S
schemawriterFree
1,537 1,546
Productivity & Workflow
ChatGPT

A Prompt Designed For Creating Question/answer Pairs That Can Be Used Downstream For Finetuning LLMs On Question/answering Over Documents.

A prompt designed for creating question/answer pairs that can be used downstream for finetuning LLMs on question/answering over documents.

A
aicanvas$1.99
3,257 20,905