I need to create a purchase order recognition software. I will receive a PDF file with a purchase order in a specific directory. The application needs to monitor the directory. When the PDF file is received, it needs to recognise the information inside it and generate a resulting XML file in a specific format.
The purchase orders will come in many formats which are not pre-defined, however they will always include a basic set of information: buyer details ,shipping details and order lines. I need step by step instructions to create the application.
Assistant
User
I need a solution which will allow users to correct the recognition and learn new templates used for orders. The solution will also need to provide a UI to present the recognized documents and what data was extracted. Provide a step by step instructions without implementation. I will ask details about each step if I have to. I need a robust solution which will improve during its lifetime.
Assistant
Okay, let's break down the process of creating this purchase order recognition software. This is a common task, but the variability in PDF formats makes the "recognition" part the most challenging. We'll outline the steps using Python, as it's well-suited for this kind of task due to its libraries for file system monitoring, PDF processing, and XML handling.
Understanding the Core Challenge:
The main difficulty is extracting structured data (buyer, shipping, line items) from unstructured or semi-structured text in PDFs that come in many different, undefined formats. Simple keyword matching often isn't enough. This step will require significant custom logic and potentially iterative refinement as you encounter new PDF layouts.
Overall Architecture:
Directory Monitor: Watches a specified folder for new files.
File Detection: When a new .pdf file appears, trigger processing.
PDF Text Extraction: Read the text content from the PDF.
Information Parsing/Recognition: Analyze the extracted text to identify and pull out the required data fields (buyer details, shipping details, line items - quantity, description, price, etc.). This is the core logic you'll need to build and refine.
Data Structuring: Organize the extracted data into a clear structure (e.g., a Python dictionary).
XML Generation: Create an XML file based on the structured data in the required format.
Output: Save the generated XML file to a specified output directory.
File Management: Move the processed PDF to an archive folder and error PDFs to an error folder.
Step-by-Step Instructions:
Step 0: Set up your Environment
Install Python: If you don't have Python installed, download and install the latest version (3.6+) from python.org.
Create a Project Directory: Create a folder for your project (e.g., po_recognizer).
Create a Virtual Environment (Recommended): Open a terminal or command prompt in your project directory and run:
bash
python -m venv venv
Activate the virtual environment:
On Windows: venv\Scripts\activate
On macOS/Linux: source venv/bin/activate
This keeps project dependencies separate.
Step 1: Install Required Libraries
You'll need libraries for directory monitoring, PDF text extraction, and potentially more robust text processing.
Install Libraries: With your virtual environment activated, install the necessary packages:
bash
pip install watchdog pdfminer.six lxml
watchdog: For monitoring the file system.
pdfminer.six: A robust library for extracting text (and layout information) from PDFs.
lxml: A powerful and fast library for working with XML (alternative to built-in xml.etree.ElementTree, often preferred). You can use the built-in xml.etree.ElementTree if you prefer simpler XML generation, but lxml is good for more complex cases and validation. We'll show ElementTree as it's standard.
Step 2: Directory Monitoring (Using watchdog)
We'll create a script that watches the input directory.
Create a File: Inside your project directory, create a Python file named po_monitor.py.
Implement the Monitor: Add the following code:
python
Step 3: PDF Text Extraction (Using pdfminer.six)
Now, let's add the function to extract text from a PDF.
Create a PDF processing file: Create a new file pdf_utils.py.
Implement Text Extraction: Add the following code to pdf_utils.py.
python
from io import StringIO
from pdfminer.high_level import extract_text_to_fp, extract_text
from pdfminer.layout import LAParams
def extract_text_from_pdf(pdf_path):
"""
Extracts text from a PDF file.
May struggle with image-based PDFs or complex layouts.
"""
try:
# Using extract_text directly for simplicity
# LAParams can be tuned for better layout preservation if needed
# laparms = LAParams()
# text = extract_text(pdf_path, laparams=laparms)
text = extract_text(pdf_path)
return text
except Exception as e:
print(f"Error extracting text from {pdf_path}: {e}")
return None
# Example of getting text with potential layout info (more complex)
# def extract_layout_info_from_pdf(pdf_path):
# """
# Extracts text along with layout information (coordinates).
# More complex to process but potentially useful for parsing.
# """
# output_string = StringIO()
# with open(pdf_path, 'rb') as in_file:
# # Requires more advanced pdfminer usage
# # See pdfminer.six documentation for details on parsing with layout
# # This function signature isn't correct for returning structured layout easily
# # You'd typically iterate through pages, and page objects to get text boxes and their coords.
# # For simplicity, we stick to extract_text for the main example.
# pass # Implementation omitted for brevity - check pdfminer docs if needed
Step 4: Information Parsing / Recognition (The Core Logic)
This is where the magic (and difficulty) happens. You need to analyze the extracted text and pull out specific pieces of information. Since formats are variable, you'll need a flexible approach.
Create a Parsing File: Create a new file po_parser.py.
Implement Parsing Logic: This function will be highly custom to the types of variations you expect. Here's a conceptual outline using simple keyword matching and line processing. You will need to heavily refine this based on your actual PDF examples.
python
Step 5: XML Generation (Using xml.etree.ElementTree)
Now, convert the structured Python dictionary into an XML format.
Create an XML utility file: Create a new file xml_utils.py.
Implement XML Generation: Add the following code to xml_utils.py. Define the desired XML structure.
python
Step 6: Finalizing the Monitor Script
The po_monitor.py script should now be connected. Review it to ensure imports are correct and the process_purchase_order function calls the helper functions.
python
Step 7: Running the Application
Save all files: Save po_monitor.py, pdf_utils.py, po_parser.py, and xml_utils.py in your project directory.
Activate Virtual Environment: If not already active, activate it (venv\Scripts\activate or source venv/bin/activate).
Run the Monitor: Execute the main script:
bash
python po_monitor.py
Test: Place a .pdf file (a sample purchase order) into the input_pos directory. Watch the console output.
If processing is successful (based on your parse_po_text logic finding data), an XML file should appear in output_xmls, and the original PDF should move to archive_pos.
If processing fails, the PDF should move to error_pos.
Step 8: Improving and Refining
This initial setup provides the framework. The most significant effort will be improving po_parser.py.
Analyze Error Files: Whenever a PDF goes into the error_pos folder, examine that specific PDF and compare it to the extracted text to understand whyparse_po_text failed.
Enhance po_parser.py:
More Robust Keyword Matching: Use regular expressions (re module) to find patterns instead of simple string starts/contains. Account for variations in spacing, capitalization, punctuation.
Layout Analysis: If pdfminer.six's extract_text isn't sufficient, look into using pdfminer.six to get layout objects (like LTTextBoxHorizontal) with their coordinates. This allows you to understand where text is on the page, which is crucial for identifying columns (like in line items) or related fields (like address lines following a "Ship To" label). This is significantly more complex than simple text extraction.
Sectioning: Try to identify distinct sections (Header, Bill To, Ship To, Line Items, Footer) using keywords or spatial analysis. Parse each section separately.
Line Item Parsing: This is the hardest. If text extraction maintains relative column spacing, you might be able to split lines based on assumed column boundaries determined from the header row's layout. Otherwise, complex regex or pattern matching per line might be needed.
Handling Variations: Create logic to handle different ways fields are labeled ("PO #", "Purchase Order No.", "Order Number").
Validation: Add more checks within parse_po_text to validate the extracted data (e.g., are quantities/prices numeric? Does the structure make sense?).
Logging: Replace print statements with a proper logging library (logging) to manage output levels (INFO, WARNING, ERROR).
Configuration: Use a configuration file (like configparser or YAML) for directories, delays, and potentially parsing rules.
Error Handling: Implement more specific error handling in process_purchase_order and the parsing functions.
Concurrency: For high volume, you might need to process files in parallel (e.g., using concurrent.futures.ThreadPoolExecutor) instead of sequentially in the on_created event. Be mindful of thread-safety if accessing shared resources (though in this design, each file is processed independently).
This step-by-step guide provides a solid foundation. The success of the "recognition" part (Step 4) depends heavily on the complexity and variability of the PDF formats you will receive. Be prepared to spend the majority of your development time on refining the parse_po_text function. Good luck!
Okay, let's outline the steps for building a robust Purchase Order recognition system that includes user correction, learning from feedback, and a user interface. This goes beyond simple automation and involves building a full application stack.
This will be a complex project, involving backend processing, a database, and a frontend UI. We will break it down into logical steps.
Core Components of the Enhanced System:
File Monitoring & Ingestion: Detects new PDFs.
PDF Processing Engine: Extracts text, layout, and potentially images.
Recognition Engine: Attempts to parse extracted data into structured fields, potentially using multiple rules or models and providing confidence scores.
Data Storage (Database): Stores the original PDF paths, extracted raw text/layout, the initially recognized data, the corrected data, the state of each PO (e.g., "pending review", "approved"), and potentially templates or recognition rules.
Backend Application/API: Manages data in the database, interacts with the recognition engine, handles requests from the UI, triggers XML generation, and manages the processing workflow.
User Interface (UI): A web or desktop application for users to view pending POs, see the extracted data side-by-side with the PDF, make corrections, and approve/reject POs.
XML Generation Module: Creates the final XML output based on the approved (potentially corrected) data from the database.
Learning Engine: Analyzes user corrections to improve the Recognition Engine over time.
Workflow/State Management: Tracks the status of each PO as it moves through the system.
Step-by-Step Plan (Without Implementation Details):
Choose a database system (e.g., SQLite for simplicity during development, PostgreSQL or MySQL for production).
Step 2: Database Design & Implementation:
Design the database schema. Key tables will likely include:
PurchaseOrders: Stores metadata about each PO file (filename, path, current state, timestamps).
ExtractedText: Stores the raw text and potentially layout information extracted from the PDF, linked to the PurchaseOrders table.
RecognizedData: Stores the individual fields identified by the Recognition Engine (field name, initial value, confidence score, reference to the text location if available), linked to the PurchaseOrders table. This table might store multiple versions (initial vs. corrected).
LineItems: Stores the parsed line item data (qty, description, price, etc.), linked to the PurchaseOrders table.
Templates (Optional but recommended): Stores information about different PO formats/templates the system knows about.
CorrectionsLog (Important for Learning): Records every instance of a user modifying a recognized field, linking the original value, the corrected value, and the specific RecognizedData entry.
Set up the chosen database.
Create the database tables based on the schema.
Step 3: Enhance PDF Text and Layout Extraction:
Develop a module to extract text from PDFs. This module should ideally aim to preserve layout information (like text box coordinates) as this is invaluable for sophisticated parsing and potentially for highlighting text in the UI. (Libraries like pdfminer.six can provide this). Handle potential issues like scanned PDFs (requires OCR integration).
Step 4: Develop the Core Recognition Engine:
Design the logic that takes the extracted text/layout and attempts to identify the required fields (buyer details, shipping details, line items, etc.).
This engine should be designed to apply a set of rules or models. Initially, these rules might be heuristic (regex patterns, keyword proximity, layout analysis).
The engine should output the extracted data for each field along with a confidence score.
Implement the functionality for the Recognition Engine to save its results (the initial recognized data with confidence scores) into the RecognizedData and LineItems tables in the database, linked to the corresponding PurchaseOrders entry.
Step 5: Implement File Monitoring and Ingestion:
Develop the directory monitoring script (similar to the previous example using watchdog).
When a new PDF is detected:
Create a new record in the PurchaseOrders table with the initial state (e.g., "Detected").
Call the PDF Extraction module (Step 3) to get text/layout.
Save the raw extracted text/layout to the ExtractedText table.
Call the Recognition Engine (Step 4) to process the data.
Update the PurchaseOrders record state to "Awaiting Review".
Step 6: Develop the Backend Application/API:
Choose a web framework (e.g., Flask, Django, FastAPI) for the backend.
Create API endpoints that will be used by the UI:
/api/pos: List POs based on status (e.g., 'awaiting review').
/api/pos/{id}: Get detailed information for a specific PO, including the original PDF path, raw text, initially recognized data, and current state.
/api/pos/{id}/data: Endpoint to receive updated (corrected) data from the UI.
/api/pos/{id}/approve: Endpoint to mark a PO as approved and trigger final processing (XML generation, file movement).
/api/pos/{id}/reject: Endpoint to mark a PO as rejected and trigger file movement.
Phase 2: User Interface & Correction Workflow
Step 7: Develop the User Interface (UI):
Choose a frontend technology (e.g., HTML/CSS/JavaScript with a framework like React, Vue, or Angular, or use server-side rendering with your chosen backend framework).
Build the following UI components:
A dashboard or list showing POs in the "Awaiting Review" state.
A detailed view for a single PO. This view should:
Display the original PDF (embedding a PDF viewer is required - look into libraries like PDF.js or browser capabilities).
Display the extracted data fields in an editable form next to the PDF.
Show the confidence score for each field if available.
Ideally, allow clicking on an extracted field in the form to highlight the corresponding text location in the PDF (requires coordinate data from extraction and PDF viewer integration).
Allow users to edit the extracted data fields.
Include "Approve" and "Reject" buttons.
Step 8: Implement the Correction and Feedback Mechanism in the UI & Backend:
In the UI, when a user edits a field, track the original recognized value and the new corrected value.
When the user clicks "Approve":
Send the corrected data (all fields) to the backend API's /api/pos/{id}/data endpoint.
The backend receives the data, updates the RecognizedData and LineItems tables with the corrected values for that PO.
Crucially, log each individual change (original value vs. corrected value) into the CorrectionsLog table, referencing the specific PO and field.
Call the /api/pos/{id}/approve endpoint. The backend updates the PO state to "Approved" or "Processed".
Phase 3: Final Output & Learning
Step 9: Implement XML Generation from Corrected Data:
Modify or create a module (similar to xml_utils.py) that reads the corrected data for an approved PO directly from the database (the RecognizedData and LineItems tables).
Generate the XML file in the required format using this data.
This process should be triggered by the backend when a PO is marked as "Approved".
Step 10: Implement File Management for Approved/Rejected POs:
Modify the backend logic triggered by the "Approve" or "Reject" actions.
If Approved: Move the original PDF file from the input_pos directory to the archive_pos directory.
If Rejected: Move the original PDF file from the input_pos directory to the error_pos directory.
Update the file path in the database record accordingly if needed, or rely on the filename/original path structure.
Step 11: Develop the Learning Engine:
Design the logic for the Learning Engine. This engine will analyze the CorrectionsLog data accumulated over time.
How it learns depends on your Recognition Engine approach:
Rule-Based Learning: If using regex and heuristics, the learning engine could:
Identify common patterns in corrections (e.g., "users always change field X when keyword Y is missing").
Propose new or modified regex rules or keyword lists.
Potentially require human oversight to approve new rules before they are deployed.
Try to group POs by similarity to identify potential "templates" and create template-specific rules.
ML-Based Learning: If using a machine learning model (more complex), the corrections log provides labeled data. The learning engine would:
Use the corrected data (potentially linked with the extracted text locations provided by user highlighting in the UI, if implemented) as training examples.
Periodically re-train or fine-tune the ML model.
Implement the Learning Engine logic as a separate process or triggered task.
Step 12: Integrate Learning Engine Output into Recognition Engine:
Modify the Recognition Engine (Step 4) to load and use the updated rules or models produced by the Learning Engine (Step 11).
Consider a versioning system for rules/models so you can roll back if new rules cause issues.
Plan how to deploy the different components (monitor, backend API, database, frontend UI, learning engine task). This might involve containers (Docker), virtual machines, or cloud services.
Set up the production environment (directories, database connection, etc.).
Step 15: Logging and Monitoring:
Implement comprehensive logging throughout all components to track processing steps, errors, and system health.
Set up monitoring to track the status of the monitor, the backend, and the number of POs in each state.
Step 16: Testing and Iteration:
Rigorously test the system with a wide variety of purchase order PDFs.
Monitor the accuracy of the Recognition Engine.
Analyze the CorrectionsLog to identify common parsing issues and guide improvements to the Recognition Engine and Learning Engine.
Continuously refine the parsing rules, models, and the learning process based on real-world usage and feedback. This is an ongoing process for a "robust solution which will improve during its lifetime."
Key Considerations for Robustness and Improvement:
Error Handling: Implement detailed error handling at every step (file access, PDF parsing errors, database errors, API errors, recognition failures). Log everything.
Validation: Validate extracted data where possible (e.g., numeric fields should be numbers).
Scalability: Consider the expected volume of POs when choosing technologies and designing the architecture (especially the database and backend).
Security: Secure your API endpoints and database access.
User Experience: Make the UI intuitive and efficient for reviewing and correcting data. Highlighting text in the PDF corresponding to fields is a major UX improvement for this type of task.
This detailed plan provides a roadmap. Each step, particularly the Recognition Engine, UI PDF handling, and Learning Engine, involves significant design and implementation work. You can now ask for details on specific steps as needed.
import time
import os
import sys
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
# --- Configuration ---
INPUT_DIR = "./input_pos"
OUTPUT_DIR = "./output_xmls"
ARCHIVE_DIR = "./archive_pos"
ERROR_DIR = "./error_pos"
# Create directories if they don't exist
for d in [INPUT_DIR, OUTPUT_DIR, ARCHIVE_DIR, ERROR_DIR]:
os.makedirs(d, exist_ok=True)
# --- Placeholder for your processing logic ---
def process_purchase_order(pdf_path):
"""
This function will contain the logic to:
1. Extract text from the PDF.
2. Parse the text to find PO details (buyer, shipping, lines).
3. Generate the XML data structure.
4. Save the XML file.
"""
print(f"Processing file: {pdf_path}")
try:
# Simulate processing delay and success/failure
# Replace this with your actual extraction and parsing logic
import random
# time.sleep(random.uniform(1, 3)) # Simulate work
# --- Replace with actual calls to your functions ---
# extracted_text = extract_text_from_pdf(pdf_path)
# po_data = parse_po_text(extracted_text)
# generate_xml(po_data, output_path)
# For now, just simulate success
success = True # Set this based on whether parsing/XML generation worked
output_filename = os.path.splitext(os.path.basename(pdf_path))[0] + ".xml"
output_path = os.path.join(OUTPUT_DIR, output_filename)
if success:
print(f"Successfully processed {pdf_path}. (Simulated XML creation: {output_path})")
# --- Placeholder: Replace with actual XML generation code ---
with open(output_path, "w") as f:
f.write(f"<PurchaseOrder><Status>Processed successfully placeholder</Status></PurchaseOrder>")
# --- End Placeholder ---
return True # Indicate success
else:
print(f"Failed to process {pdf_path}. (Simulated failure)")
return False # Indicate failure
except Exception as e:
print(f"An error occurred while processing {pdf_path}: {e}")
return False # Indicate failure
# --- Watchdog Event Handler ---
class POHandler(FileSystemEventHandler):
def on_created(self, event):
if not event.is_directory and event.src_path.lower().endswith('.pdf'):
pdf_path = event.src_path
print(f"New PDF detected: {pdf_path}")
# Give the file system a moment to finish writing the file
time.sleep(1)
# Process the file
processing_success = process_purchase_order(pdf_path)
# File management
base_name = os.path.basename(pdf_path)
if processing_success:
archive_path = os.path.join(ARCHIVE_DIR, base_name)
try:
os.rename(pdf_path, archive_path)
print(f"Moved {base_name} to archive: {archive_path}")
except OSError as e:
print(f"Error moving {base_name} to archive: {e}")
else:
error_path = os.path.join(ERROR_DIR, base_name)
try:
os.rename(pdf_path, error_path)
print(f"Moved {base_name} to error: {error_path}")
except OSError as e:
print(f"Error moving {base_name} to error: {e}")
# --- Main function to start the monitor ---
if __name__ == "__main__":
event_handler = POHandler()
observer = Observer()
observer.schedule(event_handler, INPUT_DIR, recursive=False) # Monitor only the input dir
print(f"Monitoring directory: {INPUT_DIR}")
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
print("Monitor stopped.")
observer.join()
Create Directories: Run the script once, or manually create the input_pos, output_xmls, archive_pos, and error_pos directories in your project folder.
Integrate into po_monitor.py:
Add from pdf_utils import extract_text_from_pdf at the top of po_monitor.py.
Inside the process_purchase_order function, replace the simulation with:
python
def process_purchase_order(pdf_path):
print(f"Processing file: {pdf_path}")
output_filename = os.path.splitext(os.path.basename(pdf_path))[0] + ".xml"
output_path = os.path.join(OUTPUT_DIR, output_filename)
try:
extracted_text = extract_text_from_pdf(pdf_path)
if extracted_text is None:
print(f"Could not extract text from {pdf_path}.")
return False # Indicate failure
# --- Step 4: Call your parsing function ---
# Replace with your actual parsing logic function
po_data = parse_po_text(extracted_text)
# --- End Step 4 ---
if po_data: # Check if parsing was successful (your parse function should return None or empty if failed)
# --- Step 5 & 6: Generate and Save XML ---
generate_xml(po_data, output_path)
print(f"Successfully processed {pdf_path} and created {output_path}")
# --- End Step 5 & 6 ---
return True # Indicate success
else:
print(f"Failed to parse data from {pdf_path}.")
return False # Indicate failure
except Exception as e:
print(f"An unexpected error occurred while processing {pdf_path}: {e}")
return False # Indicate failure
import re
def parse_po_text(text):
"""
Parses the extracted text to find PO details.
This is a basic example using keyword and line-based matching.
YOU WILL NEED TO CUSTOMIZE AND EXPAND THIS SIGNIFICANTLY.
Returns a dictionary like:
{
"buyer": {"name": "...", "address": "..."},
"shipping": {"name": "...", "address": "..."},
"order_lines": [
{"qty": "...", "description": "...", "unit_price": "...", "total": "..."},
...
],
"po_number": "...", # Example of other fields
# Add other fields as needed
}
Returns None or an empty structure if parsing fails.
"""
po_data = {
"buyer": {},
"shipping": {},
"order_lines": []
# Add other fields you expect
}
lines = text.splitlines()
# --- Example: Extract Buyer and Shipping (Naive Approach) ---
# Look for lines starting with or containing keywords
buyer_found = False
shipping_found = False
for i, line in enumerate(lines):
line_lower = line.lower()
if re.search(r'buyer\s*:', line_lower):
# Assuming buyer details are on the same line or next few lines
po_data['buyer']['name'] = line.split(':', 1)[-1].strip() if ':' in line else lines[i+1].strip() if i+1 < len(lines) else ""
# More logic needed to get address, etc. Maybe grab the next few non-empty lines?
address_lines = []
j = i + 1
while j < len(lines) and lines[j].strip() and not re.search(r'ship\s*:', lines[j].lower()):
address_lines.append(lines[j].strip())
j += 1
po_data['buyer']['address'] = "\n".join(address_lines)
buyer_found = True
elif re.search(r'ship\s*to\s*:', line_lower) or re.search(r'shipping\s*address\s*:', line_lower):
# Similar logic for shipping
po_data['shipping']['name'] = line.split(':', 1)[-1].strip() if ':' in line else lines[i+1].strip() if i+1 < len(lines) else ""
address_lines = []
j = i + 1
while j < len(lines) and lines[j].strip() and not re.search(r'(item|qty|description|po number)', lines[j].lower()): # Stop at potential line item headers
address_lines.append(lines[j].strip())
j += 1
po_data['shipping']['address'] = "\n".join(address_lines)
shipping_found = True
# Add logic for PO Number, Date, etc.
if re.search(r'po number\s*:', line_lower) or re.search(r'purchase order #\s*:', line_lower):
po_data['po_number'] = line.split(':', 1)[-1].strip()
# Add checks for other header fields...
# --- Example: Extract Order Lines (Very Difficult with Variable Formats) ---
# This requires identifying the table structure.
# A simple approach is to look for header keywords (QTY, DESCRIPTION, PRICE, TOTAL)
# and then try to parse lines below them based on column position or patterns.
# Finding the start of line items is tricky.
# Look for common header patterns (case-insensitive, variable spacing)
line_item_start_index = -1
header_patterns = [
r'qty\s+description\s+unit\s+price\s+total',
r'quantity\s+item\s+price\s+amount',
# Add more patterns you observe in your PDFs
]
for i, line in enumerate(lines):
for pattern in header_patterns:
if re.search(pattern, line, re.IGNORECASE):
line_item_start_index = i
print(f"Found potential line item header at line {i}: {line}")
# Basic approach: Assume lines *after* the header are line items
# until a total line or end of document.
# A more robust approach would analyze column positions from the header line.
break # Found a header pattern for this line
if line_item_start_index != -1:
break # Found the header, stop scanning for it
if line_item_start_index != -1:
# Iterate through lines *after* the assumed header
# This is highly dependent on consistent formatting under the header.
# You might need to use text coordinates (if using pdfminer layout)
# or more complex regex to match line item patterns.
# Simple example: Try to match lines that look like a line item
# This regex is illustrative and will likely need major tuning
line_item_pattern = re.compile(r'^\s*(\d+)\s+(.+?)\s+([\d\.]+)\s+([\d\.]+)$')
# Example pattern: Start, (qty), (description, non-greedy), (price), (total), End
# This assumes fixed column-like structure. Real PDFs vary wildly.
for i in range(line_item_start_index + 1, len(lines)):
line = lines[i].strip()
if not line: # Skip empty lines
continue
# Stop if we hit a summary line or footer
if re.search(r'(subtotal|tax|shipping|total|terms)', line, re.IGNORECASE):
print(f"Stopping line item parsing at potential footer: {line}")
break
match = line_item_pattern.match(line)
if match:
# print(f"Matched line item: {line}")
qty, description, unit_price, total = match.groups()
po_data['order_lines'].append({
"qty": qty.strip(),
"description": description.strip(),
"unit_price": unit_price.strip(),
"total": total.strip() # This might be line total or overall total depending on format
# You might need regex groups for currency symbols, commas, etc.
})
else:
# Handle lines that might be part of the description but wrap
# Or lines that don't match the pattern (e.g., blank lines, notes)
# print(f"Line did not match item pattern: {line}")
pass # Decide how to handle non-matching lines
# --- Validation (Optional but recommended) ---
# Check if essential fields were found. If not, consider it a parsing failure.
if not po_data.get('buyer', {}).get('name') or not po_data.get('order_lines'):
print("Parsing failed: Could not find essential data (e.g., buyer name or line items).")
return None # Indicate parsing failure
return po_data
Integrate into po_monitor.py:
Add from po_parser import parse_po_text at the top of po_monitor.py.
Ensure the process_purchase_order function calls po_data = parse_po_text(extracted_text) as shown in Step 3.
import xml.etree.ElementTree as ET
from xml.dom import minidom # For pretty printing
def prettify(elem):
"""Return a pretty-printed XML string for the Element."""
rough_string = ET.tostring(elem, 'utf-8')
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent=" ") # Use 2 spaces for indent
def generate_xml(po_data, output_path):
"""
Generates an XML file from the parsed PO data.
Define your desired XML structure here.
"""
# Define the root element
root = ET.Element("PurchaseOrder")
# Add basic fields (like PO Number if extracted)
if po_data.get("po_number"):
ET.SubElement(root, "PONumber").text = str(po_data["po_number"])
# Add Buyer details
buyer_elem = ET.SubElement(root, "Buyer")
if po_data.get("buyer", {}).get("name"):
ET.SubElement(buyer_elem, "Name").text = po_data["buyer"]["name"]
if po_data.get("buyer", {}).get("address"):
# Handle multi-line addresses
address_lines = po_data["buyer"]["address"].splitlines()
address_elem = ET.SubElement(buyer_elem, "Address")
for line in address_lines:
ET.SubElement(address_elem, "Line").text = line.strip()
# Add Shipping details
shipping_elem = ET.SubElement(root, "Shipping")
if po_data.get("shipping", {}).get("name"):
ET.SubElement(shipping_elem, "Name").text = po_data["shipping"]["name"]
if po_data.get("shipping", {}).get("address"):
address_lines = po_data["shipping"]["address"].splitlines()
address_elem = ET.SubElement(shipping_elem, "Address")
for line in address_lines:
ET.SubElement(address_elem, "Line").text = line.strip()
# Add Order Lines
order_lines_elem = ET.SubElement(root, "OrderLines")
for line_item in po_data.get("order_lines", []):
line_elem = ET.SubElement(order_lines_elem, "LineItem")
if line_item.get("qty"):
ET.SubElement(line_elem, "Quantity").text = str(line_item["qty"])
if line_item.get("description"):
ET.SubElement(line_elem, "Description").text = line_item["description"]
if line_item.get("unit_price"):
ET.SubElement(line_elem, "UnitPrice").text = str(line_item["unit_price"])
if line_item.get("total"): # Add line total if extracted
ET.SubElement(line_elem, "LineTotal").text = str(line_item["total"])
# Add other fields per line item as needed
# Create an ElementTree object
tree = ET.ElementTree(root)
# Write the XML to the file
try:
# Use the prettify function for readable output
with open(output_path, "w", encoding="utf-8") as f:
f.write(prettify(root))
# If minidom is not desired, use:
# tree.write(output_path, encoding="utf-8", xml_declaration=True)
print(f"XML saved to {output_path}")
except Exception as e:
print(f"Error writing XML to {output_path}: {e}")
raise # Re-raise the exception to be caught by the processing function
Integrate into po_monitor.py:
Add from xml_utils import generate_xml at the top of po_monitor.py.
Ensure the process_purchase_order function calls generate_xml(po_data, output_path) as shown in Step 3.
# po_monitor.py (Complete script structure)
import time
import os
import sys
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
# Import your processing logic
from pdf_utils import extract_text_from_pdf
from po_parser import parse_po_text # You NEED to implement and refine this
from xml_utils import generate_xml # You NEED to define your XML structure here
# --- Configuration ---
INPUT_DIR = "./input_pos"
OUTPUT_DIR = "./output_xmls"
ARCHIVE_DIR = "./archive_pos"
ERROR_DIR = "./error_pos"
# Create directories if they don't exist
for d in [INPUT_DIR, OUTPUT_DIR, ARCHIVE_DIR, ERROR_DIR]:
os.makedirs(d, exist_ok=True)
# --- Processing Logic ---
def process_purchase_order(pdf_path):
"""
Processes a single PDF file: extracts text, parses data, generates XML, and handles file movement.
"""
print(f"Processing file: {pdf_path}")
base_name = os.path.basename(pdf_path)
output_filename = os.path.splitext(base_name)[0] + ".xml"
output_path = os.path.join(OUTPUT_DIR, output_filename)
processing_success = False # Assume failure unless successful
try:
# 1. Extract text
extracted_text = extract_text_from_pdf(pdf_path)
if extracted_text is None:
print(f"Could not extract text from {base_name}.")
# File will be moved to error by the outer logic
return False
# 2. Parse the text
# This is the core function you'll need to refine heavily
po_data = parse_po_text(extracted_text)
if po_data is None: # parse_po_text should return None on failure
print(f"Failed to parse data from {base_name}.")
# File will be moved to error
return False
# 3. Generate and Save XML
generate_xml(po_data, output_path)
print(f"Successfully created XML: {output_path}")
processing_success = True # Mark as success
except Exception as e:
print(f"An error occurred during processing {base_name}: {e}")
# File will be moved to error
processing_success = False
finally:
# 4. File Management (moved from event handler for clarity)
if processing_success:
archive_path = os.path.join(ARCHIVE_DIR, base_name)
try:
os.rename(pdf_path, archive_path)
print(f"Moved {base_name} to archive: {archive_path}")
except OSError as e:
print(f"Error moving {base_name} to archive: {e}")
else:
error_path = os.path.join(ERROR_DIR, base_name)
try:
# Avoid overwriting if a file with the same name is already there
if os.path.exists(error_path):
name, ext = os.path.splitext(base_name)
error_path = os.path.join(ERROR_DIR, f"{name}_{int(time.time())}{ext}") # Add timestamp
print(f"Error file exists, renaming {base_name} to {os.path.basename(error_path)}")
os.rename(pdf_path, error_path)
print(f"Moved {base_name} to error: {error_path}")
except OSError as e:
print(f"Error moving {base_name} to error: {e}")
return processing_success # Return processing status
# --- Watchdog Event Handler ---
class POHandler(FileSystemEventHandler):
def on_created(self, event):
if not event.is_directory and event.src_path.lower().endswith('.pdf'):
pdf_path = event.src_path
print(f"New PDF detected: {pdf_path}")
# Add a small delay to ensure the file is fully written, especially important on some OS/networks
# You might need to adjust this delay or add a more robust check (e.g., try opening the file exclusively)
time.sleep(1)
# Process the file - the process function now handles file movement
process_purchase_order(pdf_path)
# --- Main function to start the monitor ---
if __name__ == "__main__":
event_handler = POHandler()
observer = Observer()
observer.schedule(event_handler, INPUT_DIR, recursive=False) # Monitor only the input dir
print("-" * 30)
print(f"Starting Purchase Order Monitor")
print(f" Input Directory: {os.path.abspath(INPUT_DIR)}")
print(f" Output Directory: {os.path.abspath(OUTPUT_DIR)}")
print(f" Archive Directory: {os.path.abspath(ARCHIVE_DIR)}")
print(f" Error Directory: {os.path.abspath(ERROR_DIR)}")
print("-" * 30)
observer.start()
try:
# Keep the script running
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
print("Monitor stopped.")
observer.join()
Advanced Techniques: If simple heuristics fail for a significant number of formats, consider:
OCR: If PDFs are scanned images, you'll need Optical Character Recognition (OCR) like Tesseract (pytesseract Python wrapper). You'd first convert the PDF page(s) to images (pdf2image) and then run OCR.
Machine Learning: Train a model (e.g., using spaCy's entity recognition or a custom model) to identify fields based on context and patterns observed in many examples. This requires a dataset of labeled POs.
Commercial APIs: Services like Google Cloud Document AI, Amazon Textract, Microsoft Azure Form Recognizer are specifically built for this and excel at handling variable forms using pre-trained models. They are paid services.
Step 13: Implement Workflow State Transitions:
Ensure the backend correctly manages the state of each PO in the PurchaseOrders table (e.g., "Detected" -> "Awaiting Review" -> "Approved" / "Rejected" -> "Processed" / "Error").
The UI should primarily show POs in the "Awaiting Review" state.