Below is an example of how you can build a full‐stack invoice parsing application. In this example, we’ll create a Python backend (using Flask) that accepts an invoice file upload, processes/parses the invoice using an OCR/invoice-parsing library (such as invoice2data), and then returns the extracted invoice information as JSON. On the frontend, we’ll build a simple React application that lets users select an invoice (PDF or image), upload it, and view the parsed results.
Note: This is a basic “proof-of-concept” sample application. In a production application you would include authentication, error handling, database storage, input validations, deployment configurations, etc. You might also choose a different stack (for example, Node.js/Express for backend) or a more advanced invoice parsing solution (machine learning models, commercial OCR services, etc.) depending on your requirements.
Overview of the Application
-
Backend (Python Flask):
- Provides an endpoint (
/upload) for file uploads.
- Saves the file, parses it using an invoice parsing library, and returns the extracted data in JSON.
- Uses the invoice2data library (or similar) for parsing invoices.
- Dependencies: Python 3, Flask, invoice2data (and any OCR libraries such as Tesseract if needed).
-
Frontend (React):
- Provides a user interface to select and upload an invoice.
- Displays the parsed invoice data returned from the backend.
- Dependencies: Node.js, Create React App, Axios.
Step 1. Back-end Setup (Python Flask)
1.1. Create and Activate a Virtual Environment (Optional but Recommended)
python3 -m venv venv
source venv/bin/activate # On Windows use: venv\Scripts\activate
1.2. Install Dependencies
pip install Flask invoice2data # invoice2data depends on additional libraries; check its docs for complete instructions.
Tip: If your invoice parser requires OCR (for example, Tesseract), install it and its Python bindings (e.g., using pip install pytesseract) and ensure that Tesseract is installed on your machine.
1.3. Create the Flask Application
Create a file named app.py with the following code:
from flask import Flask, request, jsonify
from invoice2data import extract_data
import os
app = Flask(__name__)
# Directory to temporarily store uploaded invoices.
UPLOAD_FOLDER = './uploads'
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
@app.route('/upload', methods=['POST'])
def upload_invoice():
# Check if the file part is in the request
if 'file' not in request.files:
return jsonify({'error': 'No file part in the request.'}), 400
file = request.files['file']
if file.filename == '':
return jsonify({'error': 'No file selected.'}), 400
# Save the file to disk
filepath = os.path.join(UPLOAD_FOLDER, file.filename)
file.save(filepath)
try:
# Note: invoice2data requires you to have invoice templates saved.
# By default, it will look for a folder named 'templates'.
# You can create templates for specific invoice formats.
result = extract_data(filepath, template_dir='templates')
if result is None:
return jsonify({'error': 'Could not parse the invoice.'}), 500
return jsonify(result), 200
except Exception as e:
return jsonify({'error': str(e)}), 500
if __name__ == '__main__':
# Run the app on port 5000 with debug mode enabled.
app.run(debug=True, port=5000)
1.4. Invoice Parsing Templates
The invoice2data library uses template files (usually in YAML) to tell it how to extract data from various invoice formats. You’ll need to create a folder called templates in your project directory and add one or more template files for your invoice formats. See the invoice2data documentation for details.
1.5. Running the Backend
Run the Flask app with:
python app.py
You should see your Flask server running on http://localhost:5000.
Step 2. Front-end Setup (React)
2.1. Create a React App
In a new terminal window (or folder), create a new React app using Create React App:
npx create-react-app invoice-parser-frontend
cd invoice-parser-frontend
2.2. Install Axios
We will use Axios to send requests to the Flask backend.
npm install axios
2.3. Create a Component for Invoice Upload
Replace the contents of src/App.js with the following code:
import React, { useState } from 'react';
import axios from 'axios';
import './App.css';
function App() {
const [selectedFile, setSelectedFile] = useState(null);
const [parsedData, setParsedData] = useState(null);
const [error, setError] = useState("");
const handleFileChange = (event) => {
setSelectedFile(event.target.files[0]);
setParsedData(null);
setError("");
};
const handleSubmit = (event) => {
event.preventDefault();
if (!selectedFile) {
setError("Please select a file first!");
return;
}
const formData = new FormData();
formData.append('file', selectedFile);
// Ensure the URL matches your Flask backend. Change port if necessary.
axios.post('http://localhost:5000/upload', formData, {
headers: { "Content-Type": "multipart/form-data" }
})
.then(response => {
setParsedData(response.data);
})
.catch(err => {
console.error(err);
setError("Error uploading or parsing the file.");
});
};
return (
<div className="App">
<h1>Invoice Parsing Application</h1>
<form onSubmit={handleSubmit}>
<input type="file" onChange={handleFileChange} />
<br />
<button type="submit">Upload and Parse Invoice</button>
</form>
{error && <p style={{ color: 'red' }}>{error}</p>}
{parsedData && (
<div>
<h2>Parsed Invoice Data</h2>
<pre>{JSON.stringify(parsedData, null, 2)}</pre>
</div>
)}
</div>
);
}
export default App;
2.4. Run the React Frontend
Start the development server:
npm start
Your React app should open in your default browser at http://localhost:3000.
Step 3. Testing Your Application
-
Start the Backend:
Ensure your Flask backend is running on port 5000.
-
Start the Frontend:
Run the React app (it should run on port 3000).
-
Upload an Invoice:
- Open the React app in your browser.
- Choose an invoice file (ensure it’s in a format that your parsing templates can handle).
- Click the “Upload and Parse Invoice” button.
- The parsed invoice data should appear on the page as JSON.
Next Steps & Enhancements
- Authentication & Security: Add user authentication, secure file uploads, and sanitize inputs to prevent security issues.
- Error Handling & Logging: Improve error handling in both frontend and backend.
- Database Integration: Store the parsed invoices in a database (using PostgreSQL, MongoDB, etc.) for historical record keeping.
- Processing Enhancements: Consider integrating more sophisticated OCR libraries (such as Tesseract via pytesseract) or commercial solutions if your invoices vary widely in format.
- Deployment: Containerize your app (using Docker) and deploy it using services like Heroku, AWS, or DigitalOcean.
This example lays out the basic architecture of a full-stack invoice parsing application. You now have a starting point to further modify and expand the capabilities of your application based on your specific requirements. Enjoy coding!