Mariem-Daha commited on
Commit
3d7858b
·
verified ·
1 Parent(s): f5d88b8

Upload 10 files

Browse files
.env ADDED
@@ -0,0 +1 @@
 
 
1
+ OPENAI_API_KEY=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
.gitignore ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Environment variables
2
+ .env
3
+ .env.local
4
+ .env.*.local
5
+
6
+ # Python
7
+ __pycache__/
8
+ *.py[cod]
9
+ *$py.class
10
+ *.so
11
+ .Python
12
+ build/
13
+ develop-eggs/
14
+ dist/
15
+ downloads/
16
+ eggs/
17
+ .eggs/
18
+ lib/
19
+ lib64/
20
+ parts/
21
+ sdist/
22
+ var/
23
+ wheels/
24
+ pip-wheel-metadata/
25
+ share/python-wheels/
26
+ *.egg-info/
27
+ .installed.cfg
28
+ *.egg
29
+ MANIFEST
30
+
31
+ # Virtual environments
32
+ venv/
33
+ ENV/
34
+ env/
35
+ .venv
36
+
37
+ # IDEs
38
+ .vscode/
39
+ .idea/
40
+ *.swp
41
+ *.swo
42
+ *~
43
+
44
+ # OS
45
+ .DS_Store
46
+ Thumbs.db
47
+
48
+ # Output files (optional - comment out if you want to track them)
49
+ processed_invoice.png
50
+ preview_invoice.png
51
+ ocr_result.json
52
+ ocr_lines.txt
53
+ smart_output.json
54
+
55
+ # Logs
56
+ *.log
README_HF.md ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Smart OCR Pipeline Full
3
+ emoji: 🧠
4
+ colorFrom: blue
5
+ colorTo: purple
6
+ sdk: gradio
7
+ sdk_version: 4.0.0
8
+ app_file: app_gradio.py
9
+ pinned: false
10
+ license: mit
11
+ ---
12
+
13
+ # Smart OCR Pipeline - Full AI Processing
14
+
15
+ Advanced invoice OCR system with AI-powered post-processing for maximum accuracy.
16
+
17
+ ## Features
18
+
19
+ - 🖼️ **Image Preprocessing**: Automatic deskewing, denoising, and enhancement
20
+ - 📄 **DocTR OCR**: State-of-the-art text extraction
21
+ - 🤖 **GPT-4o-mini Vision**: AI post-processing with image verification
22
+ - ✅ **Validation**: Automatic error correction and math verification
23
+ - 📊 **Structured Output**: Clean JSON with line items, totals, dates, etc.
24
+
25
+ ## How It Works
26
+
27
+ 1. **Upload** an invoice image (JPG, PNG, BMP, TIFF)
28
+ 2. **Process** - The system will:
29
+ - Clean and enhance the image
30
+ - Extract text using DocTR OCR
31
+ - Send both text and image to GPT-4o-mini for structured extraction
32
+ - Validate and correct errors
33
+ 3. **Get Results** - Structured JSON with all invoice data
34
+
35
+ ## Cost
36
+
37
+ - **~$0.01-$0.05 per invoice**
38
+ - Best for: Complex invoices, highest accuracy needed
39
+ - Recommended for: Low-medium volume processing
40
+
41
+ ## Configuration
42
+
43
+ This Space requires an OpenAI API key set as a secret:
44
+ - Secret name: `OPENAI_API_KEY`
45
+ - Get your key from: https://platform.openai.com/api-keys
46
+
47
+ ## Use Cases
48
+
49
+ - Invoice data extraction
50
+ - Receipt processing
51
+ - Document digitization
52
+ - Accounting automation
53
+ - ERP system integration
54
+
55
+ ## Comparison
56
+
57
+ | Feature | Full Version | Text-Only Version |
58
+ |---------|--------------|-------------------|
59
+ | Input to GPT | Text + Image | Text Only |
60
+ | Cost | $0.01-$0.05 | $0.001-$0.003 |
61
+ | Accuracy | Highest | High |
62
+ | Best For | Complex invoices | High volume |
63
+
64
+ For cost-optimized processing, check out the **Text-Only version** (10-50x cheaper!)
65
+
66
+ ## License
67
+
68
+ MIT License
__pycache__/app.cpython-311.pyc ADDED
Binary file (7.57 kB). View file
 
__pycache__/smart_ocr_pipeline_final.cpython-311.pyc ADDED
Binary file (44 kB). View file
 
app_gradio.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import json
4
+ from pathlib import Path
5
+ from smart_ocr_pipeline_final import main as process_invoice
6
+
7
+ # Set page title and description
8
+ title = "🧠 Smart OCR Pipeline - Full AI Processing"
9
+ description = """
10
+ **Advanced Invoice OCR with AI Post-Processing**
11
+
12
+ This service uses:
13
+ - DocTR for text extraction
14
+ - GPT-4o-mini Vision for structured data extraction (with image)
15
+ - Advanced validation and error correction
16
+ - Math verification and auto-correction
17
+
18
+ **Cost:** ~$0.01-$0.05 per invoice
19
+ **Best for:** Complex invoices, highest accuracy needed
20
+ """
21
+
22
+ def process_invoice_gradio(image):
23
+ """Process invoice image and return structured data"""
24
+ if image is None:
25
+ return "Please upload an image first."
26
+
27
+ try:
28
+ # Save uploaded image temporarily
29
+ temp_dir = "temp_uploads"
30
+ Path(temp_dir).mkdir(exist_ok=True)
31
+
32
+ temp_path = os.path.join(temp_dir, "temp_invoice.jpg")
33
+ image.save(temp_path)
34
+
35
+ # Process with OCR pipeline
36
+ result = process_invoice(temp_path, temp_dir)
37
+
38
+ # Format output as JSON
39
+ output = json.dumps(result, indent=2, ensure_ascii=False)
40
+
41
+ return output
42
+
43
+ except Exception as e:
44
+ return f"Error processing invoice: {str(e)}"
45
+
46
+ # Create Gradio interface
47
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
48
+ gr.Markdown(f"# {title}")
49
+ gr.Markdown(description)
50
+
51
+ with gr.Row():
52
+ with gr.Column():
53
+ image_input = gr.Image(
54
+ type="pil",
55
+ label="Upload Invoice Image",
56
+ sources=["upload", "clipboard"]
57
+ )
58
+ submit_btn = gr.Button("Process Invoice", variant="primary")
59
+
60
+ with gr.Column():
61
+ output = gr.Textbox(
62
+ label="Extracted Data (JSON)",
63
+ lines=20,
64
+ max_lines=30
65
+ )
66
+
67
+ # Examples
68
+ gr.Markdown("### 📋 Features:")
69
+ gr.Markdown("""
70
+ - ✅ Image preprocessing (deskew, denoise, enhance)
71
+ - ✅ DocTR OCR extraction
72
+ - ✅ GPT-4o-mini Vision post-processing
73
+ - ✅ Automatic validation and error correction
74
+ - ✅ Math verification
75
+ - ✅ Structured JSON output
76
+ """)
77
+
78
+ # Event handler
79
+ submit_btn.click(
80
+ fn=process_invoice_gradio,
81
+ inputs=image_input,
82
+ outputs=output
83
+ )
84
+
85
+ # Launch with authentication (optional)
86
+ if __name__ == "__main__":
87
+ demo.launch(
88
+ share=False,
89
+ server_name="0.0.0.0",
90
+ server_port=7860
91
+ )
render.yaml ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ services:
2
+ - type: web
3
+ name: smart-ocr-api
4
+ env: python
5
+ plan: starter
6
+ buildCommand: pip install -r requirements.txt
7
+ startCommand: uvicorn app:app --host 0.0.0.0 --port $PORT
8
+ envVars:
9
+ - key: OPENAI_API_KEY
10
+ sync: false # You'll set this in Render dashboard
11
+ healthCheckPath: /health
12
+ autoDeploy: false # Set to true for auto-deploy on git push
requirements.txt ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Core dependencies for Smart OCR Pipeline
2
+ openai>=1.3.0
3
+ python-dotenv>=1.0.0
4
+
5
+ # Web framework (FastAPI for Render)
6
+ fastapi>=0.104.0
7
+ uvicorn[standard]>=0.24.0
8
+ python-multipart>=0.0.6
9
+
10
+ # Gradio for Hugging Face Spaces
11
+ gradio>=4.0.0
12
+
13
+ # Image processing
14
+ opencv-python>=4.8.0
15
+ numpy>=1.24.0
16
+ Pillow>=10.0.0
17
+
18
+ # OCR engines
19
+ python-doctr[torch]>=0.7.0
20
+
21
+ # Optional: Tesseract fallback
22
+ # pytesseract>=0.3.10
23
+ # Install Tesseract separately: https://github.com/tesseract-ocr/tesseract
24
+
25
+ # Optional: EasyOCR fallback
26
+ # easyocr>=1.7.0
smart_ocr_pipeline_final.py ADDED
@@ -0,0 +1,743 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ smart_ocr_pipeline_final.py
5
+ ---------------------------------
6
+ Production-ready merge of your v3 + v1 pipelines with:
7
+ - Secure OpenAI setup (no hard-coded key)
8
+ - Global DocTR model cache (faster)
9
+ - Strong preprocessing (deskew, CLAHE, sharpen)
10
+ - Geometry-aware line grouping
11
+ - GPT-4o-mini Vision post-processing (cost-aware)
12
+ - Validation & auto-correction (math checks, type normalization)
13
+ - Lightweight fallback rerun on large mismatches
14
+ - Optional EasyOCR/Tesseract fallback if DocTR fails
15
+ - Structured logging
16
+
17
+ Usage:
18
+ python smart_ocr_pipeline_final.py <path/to/invoice.jpg> [output_dir]
19
+
20
+ Default output_dir is "." (kept from your first code).
21
+ """
22
+
23
+ import os
24
+ import sys
25
+ import json
26
+ import base64
27
+ import time
28
+ import logging
29
+ from pathlib import Path
30
+ from typing import Dict, List, Tuple, Optional
31
+
32
+ # Image processing
33
+ import cv2
34
+ import numpy as np
35
+ from PIL import Image
36
+
37
+ # OCR engines
38
+ from doctr.io import DocumentFile
39
+ from doctr.models import ocr_predictor
40
+
41
+ # OpenAI
42
+ from openai import OpenAI
43
+
44
+ # Optional: dotenv for local development (no-op if .env absent)
45
+ try:
46
+ from dotenv import load_dotenv
47
+ load_dotenv()
48
+ except Exception:
49
+ pass
50
+
51
+
52
+ # ============================================================
53
+ # Logging
54
+ # ============================================================
55
+
56
+ def setup_logger() -> logging.Logger:
57
+ logger = logging.getLogger("smart_ocr")
58
+ logger.setLevel(logging.INFO)
59
+ if not logger.handlers:
60
+ ch = logging.StreamHandler(sys.stdout)
61
+ ch.setFormatter(logging.Formatter("%(asctime)s | %(levelname)s | %(message)s"))
62
+ logger.addHandler(ch)
63
+ return logger
64
+
65
+
66
+ log = setup_logger()
67
+
68
+
69
+ # ============================================================
70
+ # 1) SETUP & CONFIGURATION
71
+ # ============================================================
72
+
73
+ def setup_environment() -> OpenAI:
74
+ """
75
+ Initialize OpenAI client with a reliable API key source.
76
+ Uses env var OPENAI_API_KEY. Fail fast if missing.
77
+ """
78
+ api_key = os.getenv("OPENAI_API_KEY")
79
+ if not api_key:
80
+ raise ValueError(
81
+ "OPENAI_API_KEY not found. Set it in your environment, e.g.\n"
82
+ "Windows (PowerShell): $env:OPENAI_API_KEY='sk-...'\n"
83
+ "macOS/Linux (bash): export OPENAI_API_KEY='sk-...'"
84
+ )
85
+ log.info("OpenAI client initialized")
86
+ return OpenAI(api_key=api_key)
87
+
88
+
89
+ # Global cache for DocTR model (faster repeated runs)
90
+ _DOCTR_MODEL = None
91
+
92
+
93
+ def get_doctr_model():
94
+ global _DOCTR_MODEL
95
+ if _DOCTR_MODEL is None:
96
+ t0 = time.time()
97
+ _DOCTR_MODEL = ocr_predictor(pretrained=True)
98
+ log.info(f"DocTR model loaded in {time.time() - t0:.2f}s")
99
+ return _DOCTR_MODEL
100
+
101
+
102
+ # ============================================================
103
+ # 2) IMAGE PREPROCESSING
104
+ # ============================================================
105
+
106
+ def preprocess_image(input_path: str, output_dir: str = ".") -> Tuple[str, str]:
107
+ log.info("Loading image for preprocessing…")
108
+ img = cv2.imread(input_path)
109
+ if img is None:
110
+ raise ValueError(f"Could not load image: {input_path}")
111
+
112
+ log.info("Cleaning image (grayscale → denoise → deskew → CLAHE → normalize → sharpen)…")
113
+ gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
114
+ denoised = cv2.bilateralFilter(gray, 9, 75, 75)
115
+ desk = deskew_image(denoised)
116
+
117
+ # Contrast + normalize
118
+ clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
119
+ enhanced = clahe.apply(desk)
120
+ normalized = cv2.normalize(enhanced, None, 0, 255, cv2.NORM_MINMAX)
121
+
122
+ # Light sharpen
123
+ kernel = np.array([[-1, -1, -1],
124
+ [-1, 9, -1],
125
+ [-1, -1, -1]])
126
+ sharpened = cv2.filter2D(normalized, -1, kernel)
127
+
128
+ processed_path = os.path.join(output_dir, "processed_invoice.png")
129
+ cv2.imwrite(processed_path, sharpened)
130
+ log.info(f"Processed image saved: {processed_path}")
131
+
132
+ preview_path = create_preview(sharpened, output_dir)
133
+ log.info(f"Preview image saved: {preview_path}")
134
+
135
+ return processed_path, preview_path
136
+
137
+
138
+ def deskew_image(image: np.ndarray) -> np.ndarray:
139
+ try:
140
+ edges = cv2.Canny(image, 50, 150, apertureSize=3)
141
+ lines = cv2.HoughLines(edges, 1, np.pi / 180, 200)
142
+ if lines is None:
143
+ return image
144
+ angles = [np.degrees(theta) - 90 for rho, theta in lines[:, 0]]
145
+ median_angle = np.median(angles)
146
+ if abs(median_angle) > 0.5:
147
+ (h, w) = image.shape[:2]
148
+ M = cv2.getRotationMatrix2D((w // 2, h // 2), median_angle, 1.0)
149
+ rot = cv2.warpAffine(image, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)
150
+ log.info(f"Deskewed by {median_angle:.2f}°")
151
+ return rot
152
+ return image
153
+ except Exception as e:
154
+ log.warning(f"Deskew failed, using original: {e}")
155
+ return image
156
+
157
+
158
+ def create_preview(image: np.ndarray, output_dir: str) -> str:
159
+ # Use 1024 max side to give the vision model more detail (as in your v3)
160
+ pil_img = Image.fromarray(image)
161
+ pil_img.thumbnail((1024, 1024), Image.Resampling.LANCZOS)
162
+ preview_path = os.path.join(output_dir, "preview_invoice.png")
163
+ pil_img.save(preview_path)
164
+ return preview_path
165
+
166
+
167
+ # ============================================================
168
+ # 3) OCR EXTRACTION + LINE GROUPING
169
+ # ============================================================
170
+
171
+ HEADER_KEYWORDS = [
172
+ "quantità", "prezzo", "sconto", "importo", "iva",
173
+ "descrizione", "codice",
174
+ "tot.", "tot,", "tot", "totale", "merce", "conforme",
175
+ "trasporto", "porto", "peso", "colli",
176
+ "quantity", "price", "discount", "amount", "description", "code", "total",
177
+ ]
178
+
179
+
180
+ def clean_blocks(blocks: List[Dict]) -> List[Dict]:
181
+ clean = []
182
+ for b in blocks:
183
+ text = b.get("text", "").strip()
184
+ lt = text.lower()
185
+ if len(text) <= 1:
186
+ continue
187
+ if any(k in lt for k in HEADER_KEYWORDS):
188
+ continue
189
+ clean.append(b)
190
+ return clean
191
+
192
+
193
+ def group_by_y(blocks: List[Dict], y_threshold: float = 0.015) -> List[str]:
194
+ if not blocks:
195
+ return []
196
+ blocks_sorted = sorted(blocks, key=lambda b: (b["geometry"][0][1], b["geometry"][0][0]))
197
+
198
+ lines, current_line = [], [blocks_sorted[0]]
199
+ current_y = blocks_sorted[0]["geometry"][0][1]
200
+
201
+ for b in blocks_sorted[1:]:
202
+ y = b["geometry"][0][1]
203
+ if abs(y - current_y) <= y_threshold:
204
+ current_line.append(b)
205
+ else:
206
+ text = " ".join(x["text"] for x in sorted(current_line, key=lambda x: x["geometry"][0][0]))
207
+ if text.strip():
208
+ lines.append(text.strip())
209
+ current_line = [b]
210
+ current_y = y
211
+
212
+ if current_line:
213
+ text = " ".join(x["text"] for x in sorted(current_line, key=lambda x: x["geometry"][0][0]))
214
+ if text.strip():
215
+ lines.append(text.strip())
216
+
217
+ return lines
218
+
219
+
220
+ def extract_text_with_doctr(image_path: str, output_dir: str = ".") -> Tuple[str, Dict, List[str]]:
221
+ log.info("Running DocTR OCR with geometry-based line grouping…")
222
+ model = get_doctr_model()
223
+ doc = DocumentFile.from_images(image_path)
224
+ result = model(doc)
225
+
226
+ all_blocks: List[Dict] = []
227
+ pages = []
228
+
229
+ for page_idx, page in enumerate(result.pages):
230
+ page_blocks = []
231
+ line_strings = []
232
+ for block in page.blocks:
233
+ for line in block.lines:
234
+ for word in line.words:
235
+ page_blocks.append({
236
+ "text": word.value,
237
+ "confidence": float(word.confidence),
238
+ "geometry": word.geometry, # [[x1,y1], [x2,y2]] normalized 0..1
239
+ })
240
+ line_text = " ".join([w.value for w in line.words]).strip()
241
+ if line_text:
242
+ line_strings.append(line_text)
243
+
244
+ pages.append({"page_number": page_idx + 1, "blocks": page_blocks, "lines": line_strings})
245
+ all_blocks.extend(page_blocks)
246
+
247
+ confs = [b["confidence"] for b in all_blocks if "confidence" in b]
248
+ avg_conf = float(np.mean(confs)) if confs else 0.0
249
+ ocr_json = {"pages": pages, "average_confidence": avg_conf}
250
+
251
+ # Clean + group
252
+ cleaned_blocks = clean_blocks(all_blocks)
253
+ y_lines = group_by_y(cleaned_blocks, y_threshold=0.01)
254
+ doctr_lines = sum((p["lines"] for p in pages), [])
255
+ chosen_lines = y_lines if len(y_lines) >= len(doctr_lines) else doctr_lines
256
+ formatted_lines = [f"{i+1}. {ln}" for i, ln in enumerate(chosen_lines)]
257
+
258
+ # Save debugs
259
+ ocr_result_path = os.path.join(output_dir, "ocr_result.json")
260
+ with open(ocr_result_path, "w", encoding="utf-8") as f:
261
+ json.dump(ocr_json, f, indent=2, ensure_ascii=False)
262
+ lines_path = os.path.join(output_dir, "ocr_lines.txt")
263
+ with open(lines_path, "w", encoding="utf-8") as f:
264
+ f.write("\n".join(formatted_lines))
265
+
266
+ log.info(f"DocTR complete (confidence: {avg_conf:.2f}; lines: {len(formatted_lines)})")
267
+ return "\n".join(chosen_lines), ocr_json, formatted_lines
268
+
269
+
270
+ # ============================================================
271
+ # 4) AI POST-PROCESSING (GPT-4o-mini Vision by default)
272
+ # ============================================================
273
+
274
+ def extract_structured_data(
275
+ client: OpenAI,
276
+ formatted_lines: List[str],
277
+ preview_path: str,
278
+ model_name: str = "gpt-4o-mini"
279
+ ) -> Dict:
280
+ """
281
+ Use GPT Vision to parse structured JSON from numbered, grouped lines + image.
282
+ """
283
+ log.info(f"Processing with {model_name} …")
284
+
285
+ with open(preview_path, "rb") as img_file:
286
+ img_b64 = base64.b64encode(img_file.read()).decode("utf-8")
287
+
288
+ def is_header(line: str) -> bool:
289
+ low = line.lower()
290
+ return any(k in low for k in HEADER_KEYWORDS)
291
+
292
+ filtered_lines = [ln for ln in formatted_lines if not is_header(ln)]
293
+
294
+ system_message = """
295
+ You are a professional invoice/receipt parser for ChefCode.
296
+ You receive:
297
+ (1) Numbered OCR lines (already grouped horizontally by row).
298
+ (2) The invoice image.
299
+
300
+ Return ONLY valid JSON with this schema:
301
+ {
302
+ "supplier": "string",
303
+ "invoice_number": "string",
304
+ "date": "YYYY-MM-DD or null",
305
+ "line_items": [
306
+ {
307
+ "lot_number": "string",
308
+ "item_name": "string",
309
+ "unit": "string",
310
+ "quantity": number,
311
+ "unit_price": number or null,
312
+ "line_total": number or null,
313
+ "type": "string"
314
+ }
315
+ ],
316
+ "total_amount": number or null,
317
+ "confidence": "high | medium | low"
318
+ }
319
+
320
+ Extraction rules (critical):
321
+ - The table is horizontal: Lot → Item → Unit → Quantity → Unit Price → Line Total.
322
+ - The quantity is the number DIRECTLY AFTER the unit.
323
+ - If numbers for a line appear missing, check up to TWO lines BELOW that line in OCR_LINES,
324
+ ignoring header words (Quantità, Prezzo, Sconto, Importo, IVA).
325
+ - Do not skip any visible row; compare OCR row count with extracted items and recover missing lines.
326
+ - Verify math: quantity × unit_price ≈ line_total (±3%). If off, re-read digits from the image.
327
+ - If two adjacent rows share identical numbers, re-check both in the image; do not merge distinct items.
328
+ - Use "." as decimal separator and strip any currency symbols.
329
+ - Keep supplier and item names exactly as printed; do not translate them.
330
+ - Infer "type" (meat/vegetable/dairy/grain/condiment/beverage/grocery). If invoice language is Italian,
331
+ output these category words in Italian (carne, verdura, latticini, cereali, condimento, bevanda, drogheria).
332
+ - Output ONLY JSON — no prose, no markdown.
333
+ """.strip()
334
+
335
+ user_message = f"""Extract structured data from this invoice.
336
+
337
+ OCR_LINES (count={len(filtered_lines)}):
338
+ {chr(10).join(filtered_lines)}
339
+ """
340
+
341
+ resp = client.chat.completions.create(
342
+ model=model_name,
343
+ temperature=0.1,
344
+ max_completion_tokens=2000,
345
+ messages=[
346
+ {"role": "system", "content": system_message},
347
+ {
348
+ "role": "user",
349
+ "content": [
350
+ {"type": "text", "text": user_message},
351
+ {
352
+ "type": "image_url",
353
+ "image_url": {"url": f"data:image/png;base64,{img_b64}", "detail": "high"},
354
+ },
355
+ ],
356
+ },
357
+ ],
358
+ )
359
+ # ✅ Capture real token usage directly from the API response
360
+ usage = None
361
+ try:
362
+ if hasattr(resp, "usage") and resp.usage:
363
+ usage = {
364
+ "prompt_tokens": resp.usage.prompt_tokens,
365
+ "completion_tokens": resp.usage.completion_tokens,
366
+ "total_tokens": resp.usage.total_tokens,
367
+ }
368
+ print(f"🔢 Token usage: {usage}")
369
+ else:
370
+ print("⚠️ No token usage info found in response.")
371
+ except Exception as e:
372
+ print(f"⚠️ Couldn't read token usage: {e}")
373
+
374
+
375
+ raw = resp.choices[0].message.content.strip()
376
+ # ✅ Save token usage into the structured data so it appears in smart_output.json
377
+
378
+ if raw.startswith("```json"):
379
+ raw = raw.replace("```json", "").replace("```", "").strip()
380
+ elif raw.startswith("```"):
381
+ raw = raw.replace("```", "").strip()
382
+
383
+ try:
384
+ data = json.loads(raw)
385
+ except json.JSONDecodeError as e:
386
+ log.error(f"JSON parse error: {e}")
387
+ return {"error": "json_parse_error", "raw_response": raw, "confidence": "low"}
388
+
389
+ log.info("GPT response parsed")
390
+
391
+ if usage:
392
+ data["usage"] = usage
393
+ return data
394
+
395
+
396
+
397
+ # ============================================================
398
+ # 5) VALIDATION & AUTO-CORRECTION
399
+ # ============================================================
400
+
401
+ def _coerce_number(x):
402
+ if x is None:
403
+ return None
404
+ if isinstance(x, (int, float)):
405
+ return float(x)
406
+ try:
407
+ s = str(x).replace("€", "").replace("EUR", "").replace(",", ".").strip()
408
+ return float(s)
409
+ except Exception:
410
+ return None
411
+
412
+
413
+ def detect_invoice_language(structured: Dict) -> str:
414
+ supplier = structured.get("supplier", "").lower()
415
+ items = structured.get("line_items", [])
416
+ italian_indicators = ["srl", "spa", "via", "roma", "milano", "kg", "lt"]
417
+ text_to_check = supplier + " " + " ".join(it.get("item_name", "").lower() for it in items[:3])
418
+ italian_count = sum(1 for word in italian_indicators if word in text_to_check)
419
+ return "it" if italian_count >= 2 else "en"
420
+
421
+
422
+ def normalize_item_types(structured: Dict) -> Dict:
423
+ language = detect_invoice_language(structured)
424
+ if language != "it":
425
+ return structured
426
+ type_mapping = {
427
+ "grain": "cereali",
428
+ "meat": "carne",
429
+ "fish": "pesce",
430
+ "vegetable": "verdura",
431
+ "fruit": "frutta",
432
+ "dairy": "latticini",
433
+ "condiment": "condimento",
434
+ "beverage": "bevanda",
435
+ "grocery": "alimentari",
436
+ "other": "altro"
437
+ }
438
+ items = structured.get("line_items", [])
439
+ for it in items:
440
+ item_type = (it.get("type") or "").lower()
441
+ if item_type in type_mapping:
442
+ it["type"] = type_mapping[item_type]
443
+ return structured
444
+
445
+
446
+ def reconcile_and_validate(structured: Dict, ocr_json: Dict) -> Dict:
447
+ notes = []
448
+ items = structured.get("line_items", []) or []
449
+ fixed_items = []
450
+
451
+ for it in items:
452
+ q = _coerce_number(it.get("quantity"))
453
+ p = _coerce_number(it.get("unit_price"))
454
+ t = _coerce_number(it.get("line_total"))
455
+
456
+ if q == 0: q = None
457
+ if p == 0: p = None
458
+ if t == 0: t = None
459
+
460
+ if q is not None and p is not None:
461
+ calc = round(q * p, 2)
462
+ if t is not None and t > 0 and abs(calc - t) > 0.1 * (t if t else 1):
463
+ notes.append(
464
+ f"⚠️ Large mismatch (>10%) for '{it.get('item_name','')}': q={q}, p={p}, expected={calc}, got={t}. Auto-correcting to {calc}."
465
+ )
466
+ t = calc
467
+ elif t is None or abs(calc - t) <= 0.05:
468
+ t = calc
469
+ elif abs(calc - t) <= 0.15:
470
+ notes.append(f"✓ Corrected line_total from {t} to {calc} for '{it.get('item_name','')}'.")
471
+ t = calc
472
+ else:
473
+ notes.append(f"⚠️ Line math mismatch for '{it.get('item_name','')}' (q*p={calc}, got {t}). Corrected.")
474
+ t = calc
475
+
476
+ it["quantity"] = q
477
+ it["unit_price"] = p
478
+ it["line_total"] = t
479
+ fixed_items.append(it)
480
+
481
+ structured["line_items"] = fixed_items
482
+
483
+ structured = normalize_item_types(structured)
484
+
485
+ line_sum = round(sum(it.get("line_total") or 0 for it in fixed_items), 2)
486
+ ta = _coerce_number(structured.get("total_amount"))
487
+
488
+ if ta is None:
489
+ structured["total_amount"] = line_sum
490
+ notes.append(f"Set total_amount from sum(line_totals) = {line_sum}.")
491
+ else:
492
+ if ta > 0:
493
+ diff_percent = abs(line_sum - ta) / ta * 100
494
+ if diff_percent <= 1.0:
495
+ notes.append(f"✓ Total validated: sum={line_sum}, header={ta}, diff={diff_percent:.2f}%")
496
+ structured["total_amount"] = line_sum
497
+ elif diff_percent <= 5.0:
498
+ notes.append(f"⚠️ Total mismatch (±{diff_percent:.2f}%): sum={line_sum}, header={ta}")
499
+ structured["confidence"] = "medium"
500
+ else:
501
+ notes.append(f"❌ Large total mismatch ({diff_percent:.2f}%): sum={line_sum}, header={ta}")
502
+ structured["confidence"] = "low"
503
+ else:
504
+ structured["total_amount"] = line_sum
505
+ notes.append(f"Set total_amount from sum(line_totals) = {line_sum}.")
506
+
507
+ ocr_line_count = sum(len(p["lines"]) for p in ocr_json.get("pages", []))
508
+ if len(fixed_items) < max(3, int(0.5 * ocr_line_count)):
509
+ notes.append(f"Only {len(fixed_items)}/{ocr_line_count} OCR lines became items; possible skips.")
510
+
511
+ if any("❌" in n for n in notes):
512
+ structured["confidence"] = "low"
513
+ elif any("⚠️" in n for n in notes):
514
+ if structured.get("confidence") != "low":
515
+ structured["confidence"] = "medium"
516
+ elif not any("mismatch" in n.lower() for n in notes):
517
+ structured["confidence"] = structured.get("confidence", "high")
518
+
519
+ if notes:
520
+ existing = structured.get("validation_notes")
521
+ structured["validation_notes"] = ("; ".join(notes) if not existing else (existing + "; " + "; ".join(notes)))
522
+
523
+ return structured
524
+
525
+
526
+ # ============================================================
527
+ # 5B) LIGHTWEIGHT FALLBACK
528
+ # ============================================================
529
+
530
+ def extract_structured_data_lightweight(
531
+ client: OpenAI, filtered_lines: List[str], preview_path: str, model_name: str = "gpt-4o-mini"
532
+ ) -> Dict:
533
+ log.info("Re-running with lightweight prompt (numeric focus)…")
534
+ with open(preview_path, "rb") as f:
535
+ img_b64 = base64.b64encode(f.read()).decode("utf-8")
536
+
537
+ system_message = """You are a precise invoice data extractor.
538
+ FOCUS: Extract ONLY the numeric columns accurately. Do not worry about perfect item names.
539
+ Return valid JSON with this schema:
540
+ {
541
+ "supplier": "string",
542
+ "invoice_number": "string",
543
+ "date": "string",
544
+ "line_items": [
545
+ {
546
+ "lot_number": "string",
547
+ "item_name": "string",
548
+ "unit": "string",
549
+ "quantity": number,
550
+ "unit_price": number,
551
+ "line_total": number,
552
+ "type": "string"
553
+ }
554
+ ],
555
+ "total_amount": number,
556
+ "confidence": "high|medium|low"
557
+ }
558
+ CRITICAL RULES:
559
+ 1. For each line, extract: quantity, unit_price, line_total in that exact order
560
+ 2. Verify: quantity × unit_price ≈ line_total (±2%)
561
+ 3. Count ALL visible rows in the table - don't skip any
562
+ 4. Sum all line_totals and verify against invoice total
563
+ 5. If a row has numbers, include it - better to have all rows than miss some
564
+ Return ONLY valid JSON, no markdown."""
565
+
566
+ user_message = f"""Extract ALL line items from this invoice. Focus on getting every row with numbers.
567
+ OCR_LINES (count={len(filtered_lines)}):
568
+ {chr(10).join(filtered_lines)}
569
+ Extract EVERY line item visible in the table."""
570
+
571
+ resp = client.chat.completions.create(
572
+ model=model_name,
573
+ max_completion_tokens=3000,
574
+ messages=[
575
+ {"role": "system", "content": system_message},
576
+ {
577
+ "role": "user",
578
+ "content": [
579
+ {"type": "text", "text": user_message},
580
+ {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{img_b64}", "detail": "high"}},
581
+ ],
582
+ },
583
+ ],
584
+ )
585
+
586
+ if not resp.choices:
587
+ log.error("No choices in response")
588
+ return {"error": "no_choices", "confidence": "low"}
589
+
590
+ choice = resp.choices[0]
591
+ raw = (choice.message.content or "").strip()
592
+ if not raw:
593
+ log.error(f"Empty response from GPT (finish_reason={choice.finish_reason})")
594
+ return {"error": "empty_response", "finish_reason": choice.finish_reason, "confidence": "low"}
595
+
596
+ if raw.startswith("```json"):
597
+ raw = raw.replace("```json", "").replace("```", "").strip()
598
+ elif raw.startswith("```"):
599
+ raw = raw.replace("```", "").strip()
600
+
601
+ try:
602
+ data = json.loads(raw)
603
+ except json.JSONDecodeError as e:
604
+ log.error(f"JSON parse error: {e}")
605
+ return {"error": "json_parse_error", "raw_response": raw[:500], "confidence": "low"}
606
+
607
+ log.info(f"Lightweight extraction: {len(data.get('line_items', []))} items")
608
+ return data
609
+
610
+
611
+ def should_rerun_lightweight(structured: Dict) -> bool:
612
+ line_items = structured.get("line_items", [])
613
+ if not line_items:
614
+ return False
615
+ line_sum = sum(_coerce_number(it.get("line_total")) or 0 for it in line_items)
616
+ header_total = _coerce_number(structured.get("total_amount"))
617
+ if header_total is None or header_total == 0:
618
+ return False
619
+ diff_percent = abs(line_sum - header_total) / header_total * 100
620
+ if diff_percent > 30:
621
+ log.warning(f"Large total mismatch: {diff_percent:.1f}% (line_sum={line_sum}, header={header_total})")
622
+ return True
623
+ return False
624
+
625
+
626
+ # ============================================================
627
+ # 6) OPTIONAL FALLBACK OCR (Tesseract / EasyOCR)
628
+ # ============================================================
629
+
630
+ def fallback_ocr_plain(image_path: str, output_dir: str) -> Tuple[str, Dict, List[str]]:
631
+ """
632
+ Fallback if DocTR throws: try pytesseract or EasyOCR.
633
+ Returns raw text, json (minimal), and naive line list.
634
+ """
635
+ try:
636
+ import pytesseract
637
+ log.info("Running Tesseract OCR (fallback)…")
638
+ img = cv2.imread(image_path)
639
+ text = pytesseract.image_to_string(img) or ""
640
+ lines = [ln.strip() for ln in text.splitlines() if ln.strip()]
641
+ ocr_json = {
642
+ "pages": [{"page_number": 1, "blocks": [], "lines": lines}],
643
+ "average_confidence": 0.7,
644
+ "engine": "tesseract_fallback",
645
+ }
646
+ return text, ocr_json, [f"{i+1}. {ln}" for i, ln in enumerate(lines)]
647
+ except Exception:
648
+ pass
649
+
650
+ try:
651
+ import easyocr
652
+ log.info("Running EasyOCR (fallback)…")
653
+ reader = easyocr.Reader(["it", "en"], gpu=False)
654
+ results = reader.readtext(image_path, detail=1, paragraph=False)
655
+ lines = [res[1] for res in results if len(res) >= 2 and res[1].strip()]
656
+ ocr_json = {
657
+ "pages": [{"page_number": 1, "blocks": [], "lines": lines}],
658
+ "average_confidence": 0.75,
659
+ "engine": "easyocr_fallback",
660
+ }
661
+ return "\n".join(lines), ocr_json, [f"{i+1}. {ln}" for i, ln in enumerate(lines)]
662
+ except Exception as e:
663
+ log.error(f"All OCR fallbacks failed: {e}")
664
+ return "", {"pages": [], "average_confidence": 0.0, "engine": "none"}, []
665
+
666
+
667
+ # ============================================================
668
+ # 7) MAIN PIPELINE
669
+ # ============================================================
670
+
671
+ def main(invoice_path: str, output_dir: str = "."):
672
+ print("\n" + "="*60)
673
+ print("🧠 SMART OCR PIPELINE (final, gpt-4o-mini by default)")
674
+ print("="*60 + "\n")
675
+
676
+ Path(output_dir).mkdir(parents=True, exist_ok=True)
677
+
678
+ # 1) Setup
679
+ client = setup_environment()
680
+
681
+ # 2) Preprocess
682
+ t0 = time.time()
683
+ processed_path, preview_path = preprocess_image(invoice_path, output_dir)
684
+
685
+ # 3) OCR
686
+ try:
687
+ ocr_text, ocr_json, formatted_lines = extract_text_with_doctr(processed_path, output_dir)
688
+ except Exception as e:
689
+ log.error(f"DocTR OCR failed: {e}")
690
+ ocr_text, ocr_json, formatted_lines = fallback_ocr_plain(processed_path, output_dir)
691
+
692
+ # 4) AI post-processing
693
+ structured = extract_structured_data(client, formatted_lines, preview_path, model_name="gpt-4o-mini")
694
+
695
+ # 5) Validation & save
696
+ structured = reconcile_and_validate(structured, ocr_json)
697
+
698
+ # 6) Lightweight fallback rerun if needed
699
+ if should_rerun_lightweight(structured):
700
+ log.info("Triggering lightweight fallback extraction…")
701
+ structured_retry = extract_structured_data_lightweight(client, formatted_lines, preview_path, model_name="gpt-4o-mini")
702
+ retry_items = len(structured_retry.get("line_items", []))
703
+ original_items = len(structured.get("line_items", []))
704
+ if retry_items > original_items:
705
+ log.info(f"Using lightweight result: {retry_items} items vs {original_items} items")
706
+ structured = reconcile_and_validate(structured_retry, ocr_json)
707
+ structured["rerun_applied"] = "lightweight_fallback"
708
+ else:
709
+ log.info(f"Keeping original result: {original_items} items vs {retry_items} items")
710
+ structured["rerun_attempted"] = "lightweight_fallback_not_better"
711
+
712
+ final_output = {
713
+ "status": "success",
714
+ "pipeline_version": "3.1_final_gpt4o-mini",
715
+ "input_file": Path(invoice_path).name,
716
+ "ocr_confidence": ocr_json.get("average_confidence", 0.0),
717
+ "lines_detected": sum(len(p["lines"]) for p in ocr_json.get("pages", [])) if ocr_json.get("pages") else 0,
718
+ "data": structured,
719
+ "elapsed_sec": round(time.time() - t0, 2),
720
+ "usage": structured.get("usage", None),
721
+ }
722
+
723
+ out_path = os.path.join(output_dir, "smart_output.json")
724
+ with open(out_path, "w", encoding="utf-8") as f:
725
+ json.dump(final_output, f, indent=2, ensure_ascii=False)
726
+
727
+ log.info(f"Final output saved: {out_path}")
728
+ log.info(f" • OCR Confidence: {final_output['ocr_confidence']:.2f}")
729
+ log.info(f" • Items parsed: {len(structured.get('line_items', []))}")
730
+ log.info(f" • Total: {structured.get('total_amount')}")
731
+ log.info(f" • Elapsed: {final_output['elapsed_sec']}s")
732
+
733
+ print("\nDone.\n")
734
+ return final_output
735
+
736
+
737
+ if __name__ == "__main__":
738
+ if len(sys.argv) < 2:
739
+ print("Usage: python smart_ocr_pipeline_final.py <path/to/invoice.jpg> [output_dir]")
740
+ sys.exit(1)
741
+ invoice_path = sys.argv[1]
742
+ output_dir = sys.argv[2] if len(sys.argv) > 2 else "."
743
+ main(invoice_path, output_dir)
static/index.html ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Smart OCR API Test</title>
7
+ <style>
8
+ body {
9
+ font-family: Arial, sans-serif;
10
+ max-width: 800px;
11
+ margin: 0 auto;
12
+ padding: 20px;
13
+ background-color: #f5f5f5;
14
+ }
15
+ .container {
16
+ background: white;
17
+ padding: 30px;
18
+ border-radius: 8px;
19
+ box-shadow: 0 2px 10px rgba(0,0,0,0.1);
20
+ }
21
+ h1 {
22
+ color: #333;
23
+ text-align: center;
24
+ }
25
+ .upload-section {
26
+ margin: 20px 0;
27
+ padding: 20px;
28
+ border: 2px dashed #ddd;
29
+ border-radius: 8px;
30
+ text-align: center;
31
+ }
32
+ input[type="file"] {
33
+ margin: 10px 0;
34
+ }
35
+ button {
36
+ background: #007bff;
37
+ color: white;
38
+ border: none;
39
+ padding: 12px 24px;
40
+ border-radius: 4px;
41
+ cursor: pointer;
42
+ font-size: 16px;
43
+ }
44
+ button:hover {
45
+ background: #0056b3;
46
+ }
47
+ button:disabled {
48
+ background: #ccc;
49
+ cursor: not-allowed;
50
+ }
51
+ .result {
52
+ margin: 20px 0;
53
+ padding: 15px;
54
+ background: #f8f9fa;
55
+ border-radius: 4px;
56
+ white-space: pre-wrap;
57
+ font-family: monospace;
58
+ max-height: 400px;
59
+ overflow-y: auto;
60
+ }
61
+ .error {
62
+ background: #f8d7da;
63
+ color: #721c24;
64
+ border: 1px solid #f5c6cb;
65
+ }
66
+ .success {
67
+ background: #d4edda;
68
+ color: #155724;
69
+ border: 1px solid #c3e6cb;
70
+ }
71
+ .loading {
72
+ display: none;
73
+ text-align: center;
74
+ margin: 20px 0;
75
+ }
76
+ .spinner {
77
+ border: 4px solid #f3f3f3;
78
+ border-top: 4px solid #007bff;
79
+ border-radius: 50%;
80
+ width: 40px;
81
+ height: 40px;
82
+ animation: spin 2s linear infinite;
83
+ margin: 0 auto;
84
+ }
85
+ @keyframes spin {
86
+ 0% { transform: rotate(0deg); }
87
+ 100% { transform: rotate(360deg); }
88
+ }
89
+ </style>
90
+ </head>
91
+ <body>
92
+ <div class="container">
93
+ <h1>🧠 Smart OCR API Test</h1>
94
+
95
+ <div class="upload-section">
96
+ <h3>Upload Invoice Image</h3>
97
+ <p>Supported formats: JPG, PNG, BMP, TIFF</p>
98
+ <input type="file" id="fileInput" accept=".jpg,.jpeg,.png,.bmp,.tiff,.tif">
99
+ <br>
100
+ <button onclick="processFile()">Process OCR</button>
101
+ </div>
102
+
103
+ <div class="loading" id="loading">
104
+ <div class="spinner"></div>
105
+ <p>Processing your invoice... This may take a few moments.</p>
106
+ </div>
107
+
108
+ <div id="result"></div>
109
+ </div>
110
+
111
+ <script>
112
+ async function processFile() {
113
+ const fileInput = document.getElementById('fileInput');
114
+ const file = fileInput.files[0];
115
+
116
+ if (!file) {
117
+ alert('Please select a file first');
118
+ return;
119
+ }
120
+
121
+ const loading = document.getElementById('loading');
122
+ const result = document.getElementById('result');
123
+ const button = document.querySelector('button');
124
+
125
+ // Show loading state
126
+ loading.style.display = 'block';
127
+ result.innerHTML = '';
128
+ button.disabled = true;
129
+
130
+ try {
131
+ const formData = new FormData();
132
+ formData.append('file', file);
133
+ formData.append('output_format', 'json');
134
+
135
+ const response = await fetch('/ocr/process', {
136
+ method: 'POST',
137
+ body: formData
138
+ });
139
+
140
+ const data = await response.json();
141
+
142
+ if (response.ok) {
143
+ result.innerHTML = `<div class="result success">
144
+ <strong>✅ OCR Processing Successful!</strong>
145
+
146
+ <strong>Summary:</strong>
147
+ • Status: ${data.status}
148
+ • Pipeline Version: ${data.pipeline_version}
149
+ • Input File: ${data.input_file}
150
+ • OCR Confidence: ${data.ocr_confidence?.toFixed(2) || 'N/A'}
151
+ • Lines Detected: ${data.lines_detected || 'N/A'}
152
+ • Processing Time: ${data.elapsed_sec}s
153
+
154
+ <strong>Extracted Data:</strong>
155
+ ${JSON.stringify(data.data, null, 2)}
156
+ </div>`;
157
+ } else {
158
+ result.innerHTML = `<div class="result error">
159
+ <strong>❌ Error:</strong>
160
+ ${data.detail || 'Unknown error occurred'}
161
+ </div>`;
162
+ }
163
+ } catch (error) {
164
+ result.innerHTML = `<div class="result error">
165
+ <strong>❌ Network Error:</strong>
166
+ ${error.message}
167
+ </div>`;
168
+ } finally {
169
+ loading.style.display = 'none';
170
+ button.disabled = false;
171
+ }
172
+ }
173
+
174
+ // Allow drag & drop
175
+ const uploadSection = document.querySelector('.upload-section');
176
+
177
+ uploadSection.addEventListener('dragover', (e) => {
178
+ e.preventDefault();
179
+ uploadSection.style.backgroundColor = '#e3f2fd';
180
+ });
181
+
182
+ uploadSection.addEventListener('dragleave', () => {
183
+ uploadSection.style.backgroundColor = '';
184
+ });
185
+
186
+ uploadSection.addEventListener('drop', (e) => {
187
+ e.preventDefault();
188
+ uploadSection.style.backgroundColor = '';
189
+
190
+ const files = e.dataTransfer.files;
191
+ if (files.length > 0) {
192
+ document.getElementById('fileInput').files = files;
193
+ }
194
+ });
195
+ </script>
196
+ </body>
197
+ </html>