Automated PDF Invoice Sorter – Dest Python
Clear professional description of the code solution
Task:
Create a production‑ready Python automation script named invoice_sorter.py that scans a directory of PDF invoice files, extracts key metadata (vendor name, invoice date, and invoice number), and moves each PDF into a structured folder hierarchy based on that metadata. The solution must be fully functional, well‑documented, and include supporting files (requirements, README, unit tests).
Requirements:
-
Environment & Dependencies
- Use Python 3.10+ and a virtual environment.
- Required packages:
pdfplumber,pytesseract,Pillow,PyPDF2,python-dotenv,loguru. - Provide a
requirements.txtfile listing exact versions.
-
Configuration
- Accept configuration via a
.envfile (e.g.,SOURCE_DIR,DEST_ROOT,TESSERACT_CMD,LOG_LEVEL). - Include a sample
.env.examplewith comments explaining each variable.
- Accept configuration via a
-
CLI Interface
- Use
argparseto support:--source(overrideSOURCE_DIR)--dest(overrideDEST_ROOT)--dry-run(show actions without moving files)--log-level(overrideLOG_LEVEL)
- Use
-
Metadata Extraction
- First attempt to extract text with
pdfplumber. - If the PDF is image‑based or text extraction fails, fall back to OCR using
pytesseract. - Identify the following fields using robust regex patterns (handle common variations):
- Vendor Name – e.g., “Acme Corp”, “XYZ Ltd.”
- Invoice Date – accept formats
MM/DD/YYYY,DD-MM-YYYY,YYYY.MM.DD; output ISOYYYY-MM-DD. - Invoice Number – alphanumeric patterns like
INV-12345or2023/001.
- First attempt to extract text with
-
Folder Structure
- Destination path:
//// - Rename the file to
Invoice__.pdf(e.g.,Invoice_INV-12345_2023-07-15.pdf).
- Destination path:
-
Logging & Error Handling
- Use
logurufor structured logs (to console andinvoice_sorter.log). - Log each processed file, extracted metadata, and any errors (e.g., missing fields, unreadable PDF).
- If required metadata cannot be extracted, move the file to
/Unsorted/and log the reason.
- Use
-
Idempotency & Safety
- Ensure the script can be re‑run without duplicating or overwriting files.
- If a target filename already exists, append a numeric suffix (
_1,_2, …).
-
Testing
- Provide a
tests/directory with at least three pytest cases:- Successful extraction from a text‑based PDF.
- OCR fallback for an image‑only PDF.
- Handling of a PDF missing one of the required fields (should go to
Unsorted).
- Provide a
-
Documentation
- Include a comprehensive
README.mdcovering:- Project overview.
- Setup instructions (virtualenv, installing Tesseract OCR,
pip install -r requirements.txt). - Configuration guide.
- Usage examples (with CLI flags).
- Testing instructions.
- Include a comprehensive
-
Code Quality
- Use type hints throughout.
- Follow PEP 8 style.
- Include docstrings for all functions/classes.
- Provide a
main()entry point guarded byif __name__ == "__main__":.
Expected Output Format:
invoice_sorter.py– full script with shebang, imports, functions, CLI, and entry point..env.example– sample environment file with comments.requirements.txt– pinned package versions.README.md– markdown documentation as described.tests/test_invoice_sorter.py– pytest file with the three required test cases.- Any additional helper modules (if you choose to split logic) should be included and referenced in the README.
Please deliver all files in a single Markdown code block per file, clearly labeled with the filename (e.g., python\n# invoice_sorter.py\n...), so the buyer can copy each file directly. Ensure the solution is ready to run after following the README setup steps.
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.