Automated PDF Invoice Sorter – Script Organization
Clear professional description of the code solution
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:
-
Project Structure
invoice_sorter/ ├── invoice_sorter.py # main executable script ├── config.yaml # configurable parameters ├── requirements.txt # pip dependencies └── README.md # usage guide -
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.56orUSD 1234.56).log_file: Path to a log file for the script’s execution.
Provide a sample
config.yamlwith at least three vendor entries (e.g., “Acme Corp”, “Globex Ltd”, “Initech”) and sensible defaults for the other fields. -
Dependencies (
requirements.txt) Include exact package names and versions (if applicable) for:PyPDF2(orpdfplumber) for text extraction.pytesseractandPillowfor OCR fallback.pdf2image(if needed for OCR).PyYAMLfor reading the config file.python-dateutilfor flexible date parsing.loguru(or the standardloggingmodule) for logging.
-
Main Script (
invoice_sorter.py)- Argument parsing: Accept optional command‑line arguments to override
config.yamlvalues (--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 (
pytesseracton each page rendered viapdf2image). - Identify the vendor by matching the extracted text against the
vendor_patterns. If no match, label asUNKNOWN_VENDOR. - Locate the invoice date using the list of
date_formatsanddateutil.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.
- Try to extract text using
- Folder Creation: Build the destination path as:
{destination_root}/{year}/{month}/{vendor_name}/whereyearandmonthare derived from the invoice date (YYYY/MM). If the date is missing, useUNKNOWN_DATE. - File Moving: Move (or copy, based on a
--copyflag) 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.
- Argument parsing: Accept optional command‑line arguments to override
-
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).
-
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.yamlcontent inside a fenced code block labeledyaml. - Provide the full
requirements.txtinside a fenced code block labeledtext. - Provide the entire
invoice_sorter.pysource inside a fenced code block labeledpython. - Provide the complete
README.mdinside a fenced code block labeledmarkdown.
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.
Related Prompts
More prompts in Productivity & Workflow
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.
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}
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.
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
Growth Mindset Guru
Have ChatGPT offer you heaps of encouraging Growth Mindset advice for your child, using creative analogies where possible.
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.