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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
|
| 10 |
-
If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
|
| 11 |
-
forums](https://discuss.streamlit.io).
|
| 12 |
-
|
| 13 |
-
In the meantime, below is an example of what you can do with just a few lines of code:
|
| 14 |
-
"""
|
| 15 |
-
|
| 16 |
-
num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
|
| 17 |
-
num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
|
| 18 |
-
|
| 19 |
-
indices = np.linspace(0, 1, num_points)
|
| 20 |
-
theta = 2 * np.pi * num_turns * indices
|
| 21 |
-
radius = indices
|
| 22 |
-
|
| 23 |
-
x = radius * np.cos(theta)
|
| 24 |
-
y = radius * np.sin(theta)
|
| 25 |
-
|
| 26 |
-
df = pd.DataFrame({
|
| 27 |
-
"x": x,
|
| 28 |
-
"y": y,
|
| 29 |
-
"idx": indices,
|
| 30 |
-
"rand": np.random.randn(num_points),
|
| 31 |
-
})
|
| 32 |
-
|
| 33 |
-
st.altair_chart(alt.Chart(df, height=700, width=700)
|
| 34 |
-
.mark_point(filled=True)
|
| 35 |
-
.encode(
|
| 36 |
-
x=alt.X("x", axis=None),
|
| 37 |
-
y=alt.Y("y", axis=None),
|
| 38 |
-
color=alt.Color("idx", legend=None, scale=alt.Scale()),
|
| 39 |
-
size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
|
| 40 |
-
))
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
from PIL import Image
|
| 3 |
+
import torch
|
| 4 |
+
from transformers import AutoProcessor, AutoModelForImageTextToText
|
| 5 |
+
import json
|
| 6 |
+
import cv2
|
| 7 |
import numpy as np
|
| 8 |
import pandas as pd
|
| 9 |
+
from io import BytesIO, StringIO
|
| 10 |
+
import datetime
|
| 11 |
+
from enum import Enum
|
| 12 |
+
from typing import Dict, Any, Optional
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
# ========================================
|
| 16 |
+
# DOCUMENT TYPES & TEMPLATES
|
| 17 |
+
# ========================================
|
| 18 |
+
|
| 19 |
+
class DocumentType(str, Enum):
|
| 20 |
+
"""Supported document types"""
|
| 21 |
+
GENERAL = "general"
|
| 22 |
+
ID_CARD = "id_card"
|
| 23 |
+
RECEIPT = "receipt"
|
| 24 |
+
INVOICE = "invoice"
|
| 25 |
+
BUSINESS_CARD = "business_card"
|
| 26 |
+
FORM = "form"
|
| 27 |
+
HANDWRITTEN = "handwritten"
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
DOCUMENT_TEMPLATES = {
|
| 31 |
+
DocumentType.GENERAL: {
|
| 32 |
+
"name": "π General Text",
|
| 33 |
+
"description": "Extract all text from any document",
|
| 34 |
+
"prompt": "Extract all text from this image. Preserve the layout and structure. Output plain text.",
|
| 35 |
+
"icon": "π"
|
| 36 |
+
},
|
| 37 |
+
|
| 38 |
+
DocumentType.ID_CARD: {
|
| 39 |
+
"name": "π ID Card / Passport",
|
| 40 |
+
"description": "Extract structured data from identity documents",
|
| 41 |
+
"prompt": """Extract structured data from this identity document.
|
| 42 |
+
|
| 43 |
+
Output ONLY valid JSON:
|
| 44 |
+
{
|
| 45 |
+
"document_type": "",
|
| 46 |
+
"full_name": "",
|
| 47 |
+
"sex": "",
|
| 48 |
+
"date_of_birth": "",
|
| 49 |
+
"date_of_expiry": "",
|
| 50 |
+
"nationality": "",
|
| 51 |
+
"document_number": "",
|
| 52 |
+
"additional_info": {}
|
| 53 |
+
}""",
|
| 54 |
+
"icon": "π"
|
| 55 |
+
},
|
| 56 |
+
|
| 57 |
+
DocumentType.RECEIPT: {
|
| 58 |
+
"name": "π§Ύ Receipt",
|
| 59 |
+
"description": "Extract items, prices, and totals from receipts",
|
| 60 |
+
"prompt": """Extract information from this receipt.
|
| 61 |
+
|
| 62 |
+
Output ONLY valid JSON:
|
| 63 |
+
{
|
| 64 |
+
"merchant_name": "",
|
| 65 |
+
"date": "",
|
| 66 |
+
"time": "",
|
| 67 |
+
"items": [
|
| 68 |
+
{"name": "", "quantity": 1, "price": 0.0}
|
| 69 |
+
],
|
| 70 |
+
"subtotal": 0.0,
|
| 71 |
+
"tax": 0.0,
|
| 72 |
+
"total": 0.0,
|
| 73 |
+
"payment_method": ""
|
| 74 |
+
}""",
|
| 75 |
+
"icon": "π§Ύ"
|
| 76 |
+
},
|
| 77 |
+
|
| 78 |
+
DocumentType.INVOICE: {
|
| 79 |
+
"name": "π Invoice",
|
| 80 |
+
"description": "Extract invoice details and line items",
|
| 81 |
+
"prompt": """Extract information from this invoice.
|
| 82 |
+
|
| 83 |
+
Output ONLY valid JSON:
|
| 84 |
+
{
|
| 85 |
+
"invoice_number": "",
|
| 86 |
+
"date": "",
|
| 87 |
+
"due_date": "",
|
| 88 |
+
"vendor": {
|
| 89 |
+
"name": "",
|
| 90 |
+
"address": "",
|
| 91 |
+
"contact": ""
|
| 92 |
+
},
|
| 93 |
+
"customer": {
|
| 94 |
+
"name": "",
|
| 95 |
+
"address": "",
|
| 96 |
+
"contact": ""
|
| 97 |
+
},
|
| 98 |
+
"line_items": [
|
| 99 |
+
{"description": "", "quantity": 1, "unit_price": 0.0, "amount": 0.0}
|
| 100 |
+
],
|
| 101 |
+
"subtotal": 0.0,
|
| 102 |
+
"tax": 0.0,
|
| 103 |
+
"total": 0.0
|
| 104 |
+
}""",
|
| 105 |
+
"icon": "π"
|
| 106 |
+
},
|
| 107 |
+
|
| 108 |
+
DocumentType.BUSINESS_CARD: {
|
| 109 |
+
"name": "πΌ Business Card",
|
| 110 |
+
"description": "Extract contact information",
|
| 111 |
+
"prompt": """Extract contact information from this business card.
|
| 112 |
+
|
| 113 |
+
Output ONLY valid JSON:
|
| 114 |
+
{
|
| 115 |
+
"name": "",
|
| 116 |
+
"title": "",
|
| 117 |
+
"company": "",
|
| 118 |
+
"email": "",
|
| 119 |
+
"phone": "",
|
| 120 |
+
"mobile": "",
|
| 121 |
+
"website": "",
|
| 122 |
+
"address": "",
|
| 123 |
+
"social_media": {}
|
| 124 |
+
}""",
|
| 125 |
+
"icon": "πΌ"
|
| 126 |
+
},
|
| 127 |
+
|
| 128 |
+
DocumentType.FORM: {
|
| 129 |
+
"name": "π Form",
|
| 130 |
+
"description": "Extract filled form data",
|
| 131 |
+
"prompt": """Extract all fields and values from this form.
|
| 132 |
+
|
| 133 |
+
Output ONLY valid JSON with field names as keys and filled values:
|
| 134 |
+
{
|
| 135 |
+
"field_name": "value"
|
| 136 |
+
}""",
|
| 137 |
+
"icon": "π"
|
| 138 |
+
},
|
| 139 |
+
|
| 140 |
+
DocumentType.HANDWRITTEN: {
|
| 141 |
+
"name": "βοΈ Handwritten Note",
|
| 142 |
+
"description": "Extract text from handwritten documents",
|
| 143 |
+
"prompt": "Extract all handwritten text from this image. Output plain text, preserving line breaks.",
|
| 144 |
+
"icon": "βοΈ"
|
| 145 |
+
}
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
# ========================================
|
| 150 |
+
# MODEL LOADING
|
| 151 |
+
# ========================================
|
| 152 |
+
|
| 153 |
+
@st.cache_resource
|
| 154 |
+
def load_glm_ocr():
|
| 155 |
+
"""Load GLM-OCR model (cached)"""
|
| 156 |
+
MODEL_NAME = "zai-org/GLM-OCR"
|
| 157 |
+
|
| 158 |
+
with st.spinner("π Loading OCR model... (first time may take 1β3 minutes)"):
|
| 159 |
+
processor = AutoProcessor.from_pretrained(
|
| 160 |
+
MODEL_NAME,
|
| 161 |
+
trust_remote_code=True
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 165 |
+
dtype = torch.bfloat16 if torch.cuda.is_available() else torch.float32
|
| 166 |
+
|
| 167 |
+
model = AutoModelForImageTextToText.from_pretrained(
|
| 168 |
+
MODEL_NAME,
|
| 169 |
+
torch_dtype=dtype,
|
| 170 |
+
device_map="auto" if torch.cuda.is_available() else None,
|
| 171 |
+
low_cpu_mem_usage=True,
|
| 172 |
+
trust_remote_code=True
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
if not torch.cuda.is_available():
|
| 176 |
+
model = model.to(device)
|
| 177 |
+
|
| 178 |
+
model.eval()
|
| 179 |
+
|
| 180 |
+
return processor, model, device
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
processor, model, device = load_glm_ocr()
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
# ========================================
|
| 187 |
+
# IMAGE PREPROCESSING
|
| 188 |
+
# ========================================
|
| 189 |
+
|
| 190 |
+
def preprocess_image(
|
| 191 |
+
image: Image.Image,
|
| 192 |
+
enhance_contrast: bool = False,
|
| 193 |
+
denoise: bool = False,
|
| 194 |
+
sharpen: bool = False,
|
| 195 |
+
auto_rotate: bool = False,
|
| 196 |
+
prevent_cropping: bool = False
|
| 197 |
+
) -> Image.Image:
|
| 198 |
+
"""
|
| 199 |
+
Preprocess image with optional enhancements
|
| 200 |
+
|
| 201 |
+
Args:
|
| 202 |
+
image: PIL Image
|
| 203 |
+
enhance_contrast: Apply CLAHE contrast enhancement
|
| 204 |
+
denoise: Apply denoising
|
| 205 |
+
sharpen: Apply sharpening
|
| 206 |
+
auto_rotate: Attempt to auto-rotate text to horizontal
|
| 207 |
+
|
| 208 |
+
Returns:
|
| 209 |
+
Preprocessed PIL Image
|
| 210 |
+
"""
|
| 211 |
+
if prevent_cropping and not auto_rotate:
|
| 212 |
+
raise Exception(f"Auto-Rotate must be enabled when Prevent-Cropping is active")
|
| 213 |
+
|
| 214 |
+
# Convert to OpenCV format
|
| 215 |
+
img_cv = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
|
| 216 |
+
gray = cv2.cvtColor(img_cv, cv2.COLOR_BGR2GRAY)
|
| 217 |
+
|
| 218 |
+
# Denoise
|
| 219 |
+
if denoise:
|
| 220 |
+
gray = cv2.fastNlMeansDenoising(gray, None, 10, 7, 21)
|
| 221 |
+
|
| 222 |
+
# Enhance contrast
|
| 223 |
+
if enhance_contrast:
|
| 224 |
+
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
|
| 225 |
+
gray = clahe.apply(gray)
|
| 226 |
+
|
| 227 |
+
# Sharpen
|
| 228 |
+
if sharpen:
|
| 229 |
+
kernel = np.array([[-1, -1, -1],
|
| 230 |
+
[-1, 9, -1],
|
| 231 |
+
[-1, -1, -1]])
|
| 232 |
+
gray = cv2.filter2D(gray, -1, kernel)
|
| 233 |
+
|
| 234 |
+
# Auto-rotate (basic implementation)
|
| 235 |
+
if auto_rotate:
|
| 236 |
+
# blur for calculate the rotation angle correctly
|
| 237 |
+
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
|
| 238 |
+
|
| 239 |
+
# Detect lines
|
| 240 |
+
edges = cv2.Canny(blurred, 50, 150)
|
| 241 |
+
lines = cv2.HoughLinesP(edges, 1, np.pi / 180, 100, minLineLength=80, maxLineGap=10)
|
| 242 |
+
|
| 243 |
+
if lines is not None and len(lines) > 0:
|
| 244 |
+
angles = []
|
| 245 |
+
for line in lines:
|
| 246 |
+
x1, y1, x2, y2 = line[0]
|
| 247 |
+
angle = np.degrees(np.arctan2(y2 - y1, x2 - x1))
|
| 248 |
+
if -45 < angle < 45:
|
| 249 |
+
angles.append(angle)
|
| 250 |
+
|
| 251 |
+
if len(angles) > 0:
|
| 252 |
+
# Use median to be robust against outliers
|
| 253 |
+
median_angle = np.median(angles)
|
| 254 |
+
# If lines are detected near vertical, adjust (rare for text)
|
| 255 |
+
if abs(median_angle) > 45:
|
| 256 |
+
median_angle -= 90 * np.sign(median_angle)
|
| 257 |
+
rotation_angle = median_angle # negative to correct back to horizontal
|
| 258 |
+
|
| 259 |
+
(h, w) = gray.shape[:2]
|
| 260 |
+
center = (w // 2, h // 2)
|
| 261 |
+
M = cv2.getRotationMatrix2D(center, rotation_angle, 1.0)
|
| 262 |
+
|
| 263 |
+
if prevent_cropping:
|
| 264 |
+
# Calculate new image size to prevent cropping
|
| 265 |
+
cos = np.abs(M[0, 0])
|
| 266 |
+
sin = np.abs(M[0, 1])
|
| 267 |
+
|
| 268 |
+
w = int((h * sin) + (w * cos))
|
| 269 |
+
h = int((h * cos) + (w * sin))
|
| 270 |
+
|
| 271 |
+
# Adjust transformation matrix
|
| 272 |
+
M[0, 2] += (w / 2) - center[0]
|
| 273 |
+
M[1, 2] += (h / 2) - center[1]
|
| 274 |
+
|
| 275 |
+
gray = cv2.warpAffine(gray, M, (w, h),
|
| 276 |
+
flags=cv2.INTER_CUBIC,
|
| 277 |
+
borderMode=cv2.BORDER_REPLICATE)
|
| 278 |
+
|
| 279 |
+
# Convert back to RGB
|
| 280 |
+
return Image.fromarray(cv2.cvtColor(gray, cv2.COLOR_GRAY2RGB))
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
# ========================================
|
| 284 |
+
# OCR EXTRACTION
|
| 285 |
+
# ========================================
|
| 286 |
+
|
| 287 |
+
def extract_text(
|
| 288 |
+
image: Image.Image,
|
| 289 |
+
prompt: str,
|
| 290 |
+
max_tokens: int = 2048
|
| 291 |
+
) -> tuple[str, int]:
|
| 292 |
+
"""
|
| 293 |
+
Extract text from image using GLM-OCR
|
| 294 |
+
|
| 295 |
+
Args:
|
| 296 |
+
image: PIL Image
|
| 297 |
+
prompt: Extraction prompt
|
| 298 |
+
max_tokens: Maximum tokens to generate
|
| 299 |
+
|
| 300 |
+
Returns:
|
| 301 |
+
Tuple of (extracted_text, processing_time_ms)
|
| 302 |
+
"""
|
| 303 |
+
start_time = datetime.datetime.now()
|
| 304 |
+
|
| 305 |
+
# Prepare messages
|
| 306 |
+
messages = [
|
| 307 |
+
{
|
| 308 |
+
"role": "user",
|
| 309 |
+
"content": [
|
| 310 |
+
{"type": "image", "image": image},
|
| 311 |
+
{"type": "text", "text": prompt}
|
| 312 |
+
]
|
| 313 |
+
}
|
| 314 |
+
]
|
| 315 |
+
|
| 316 |
+
# Apply chat template
|
| 317 |
+
inputs = processor.apply_chat_template(
|
| 318 |
+
messages,
|
| 319 |
+
tokenize=True,
|
| 320 |
+
add_generation_prompt=True,
|
| 321 |
+
return_dict=True,
|
| 322 |
+
return_tensors="pt"
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
# Move to device
|
| 326 |
+
inputs = {k: v.to(device) for k, v in inputs.items() if k != "token_type_ids"}
|
| 327 |
+
|
| 328 |
+
# Generate
|
| 329 |
+
with torch.no_grad():
|
| 330 |
+
generated_ids = model.generate(
|
| 331 |
+
**inputs,
|
| 332 |
+
max_new_tokens=max_tokens,
|
| 333 |
+
do_sample=False,
|
| 334 |
+
temperature=0.0
|
| 335 |
+
)
|
| 336 |
+
|
| 337 |
+
# Decode
|
| 338 |
+
output_text = processor.decode(
|
| 339 |
+
generated_ids[0][inputs["input_ids"].shape[1]:],
|
| 340 |
+
skip_special_tokens=True
|
| 341 |
+
)
|
| 342 |
+
|
| 343 |
+
# Cleanup
|
| 344 |
+
del inputs, generated_ids
|
| 345 |
+
if torch.cuda.is_available():
|
| 346 |
+
torch.cuda.empty_cache()
|
| 347 |
+
|
| 348 |
+
# Calculate processing time
|
| 349 |
+
processing_time = (datetime.datetime.now() - start_time).total_seconds() * 1000
|
| 350 |
+
|
| 351 |
+
return output_text, int(processing_time)
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
# ========================================
|
| 355 |
+
# STREAMLIT UI
|
| 356 |
+
# ========================================
|
| 357 |
+
|
| 358 |
+
st.set_page_config(
|
| 359 |
+
page_title="Universal OCR Scanner",
|
| 360 |
+
page_icon="π",
|
| 361 |
+
layout="wide",
|
| 362 |
+
initial_sidebar_state="expanded"
|
| 363 |
+
)
|
| 364 |
+
|
| 365 |
+
# Header
|
| 366 |
+
st.title("π Universal OCR Scanner")
|
| 367 |
+
st.markdown("Extract text and structured data from **any document** - receipts, IDs, invoices, forms, and more!")
|
| 368 |
+
|
| 369 |
+
# Sidebar - Document Type Selection
|
| 370 |
+
with st.sidebar:
|
| 371 |
+
st.header("π Document Type")
|
| 372 |
+
|
| 373 |
+
# Show document type cards
|
| 374 |
+
doc_type = st.radio(
|
| 375 |
+
"Select document type:",
|
| 376 |
+
options=list(DocumentType),
|
| 377 |
+
format_func=lambda x: f"{DOCUMENT_TEMPLATES[x]['icon']} {DOCUMENT_TEMPLATES[x]['name']}",
|
| 378 |
+
label_visibility="collapsed"
|
| 379 |
+
)
|
| 380 |
+
|
| 381 |
+
# Show description
|
| 382 |
+
st.info(DOCUMENT_TEMPLATES[doc_type]['description'])
|
| 383 |
+
|
| 384 |
+
st.markdown("---")
|
| 385 |
+
|
| 386 |
+
# Preprocessing options
|
| 387 |
+
st.header("βοΈ Image Enhancement")
|
| 388 |
+
|
| 389 |
+
with st.expander("π¨ Preprocessing Options", expanded=False):
|
| 390 |
+
enhance_contrast = st.checkbox("Enhance Contrast", value=False,
|
| 391 |
+
help="Improve visibility of faded text")
|
| 392 |
+
denoise = st.checkbox("Reduce Noise", value=False,
|
| 393 |
+
help="Remove image noise and artifacts")
|
| 394 |
+
sharpen = st.checkbox("Sharpen Text", value=False,
|
| 395 |
+
help="Make text edges crisper")
|
| 396 |
+
auto_rotate = st.checkbox("Auto-Rotate", value=False,
|
| 397 |
+
help="Automatically straighten tilted documents")
|
| 398 |
+
prevent_cropping = st.checkbox("Prevent-Cropping", value=False,
|
| 399 |
+
help="Prevent cropping when rotate")
|
| 400 |
+
|
| 401 |
+
st.markdown("---")
|
| 402 |
+
|
| 403 |
+
# Advanced options
|
| 404 |
+
with st.expander("π§ Advanced Options", expanded=False):
|
| 405 |
+
show_preprocessed = st.checkbox("Show Preprocessed Image", value=False)
|
| 406 |
+
max_tokens = st.slider("Max Output Tokens", 512, 4096, 2048, 256,
|
| 407 |
+
help="Increase for longer documents")
|
| 408 |
+
custom_prompt = st.checkbox("Use Custom Prompt", value=False)
|
| 409 |
+
|
| 410 |
+
st.markdown("---")
|
| 411 |
+
|
| 412 |
+
# Info
|
| 413 |
+
st.caption("π‘ **Tips:**")
|
| 414 |
+
st.caption("β’ Use good lighting")
|
| 415 |
+
st.caption("β’ Avoid shadows")
|
| 416 |
+
st.caption("β’ Keep text horizontal")
|
| 417 |
+
st.caption("β’ Use high resolution images")
|
| 418 |
+
|
| 419 |
+
# Main content area
|
| 420 |
+
col1, col2 = st.columns([1, 1])
|
| 421 |
+
|
| 422 |
+
with col1:
|
| 423 |
+
st.subheader("π€ Upload Document")
|
| 424 |
+
|
| 425 |
+
# Tabs for upload methods
|
| 426 |
+
upload_tab, camera_tab = st.tabs(["π Upload File", "πΈ Take Photo"])
|
| 427 |
+
|
| 428 |
+
image = None
|
| 429 |
+
|
| 430 |
+
with upload_tab:
|
| 431 |
+
uploaded_file = st.file_uploader(
|
| 432 |
+
"Choose an image...",
|
| 433 |
+
type=["jpg", "jpeg", "png", "webp"],
|
| 434 |
+
help="Supported formats: JPG, PNG, WEBP"
|
| 435 |
+
)
|
| 436 |
+
if uploaded_file is not None:
|
| 437 |
+
image = Image.open(uploaded_file).convert("RGB")
|
| 438 |
+
|
| 439 |
+
with camera_tab:
|
| 440 |
+
camera_picture = st.camera_input("Take a photo")
|
| 441 |
+
if camera_picture is not None:
|
| 442 |
+
image = Image.open(BytesIO(camera_picture.getvalue())).convert("RGB")
|
| 443 |
+
|
| 444 |
+
# Show original image
|
| 445 |
+
if image is not None:
|
| 446 |
+
st.image(image, caption="Original Image", use_container_width=True)
|
| 447 |
+
|
| 448 |
+
with col2:
|
| 449 |
+
st.subheader("π Extraction Settings")
|
| 450 |
+
|
| 451 |
+
# Show/edit prompt
|
| 452 |
+
if custom_prompt:
|
| 453 |
+
prompt = st.text_area(
|
| 454 |
+
"Custom Extraction Prompt:",
|
| 455 |
+
value=DOCUMENT_TEMPLATES[doc_type]['prompt'],
|
| 456 |
+
height=200,
|
| 457 |
+
help="Customize how the OCR extracts data"
|
| 458 |
+
)
|
| 459 |
+
else:
|
| 460 |
+
prompt = DOCUMENT_TEMPLATES[doc_type]['prompt']
|
| 461 |
+
st.code(prompt, language="text")
|
| 462 |
+
|
| 463 |
+
# Process button
|
| 464 |
+
if image is not None:
|
| 465 |
+
process_button = st.button(
|
| 466 |
+
"π Extract Text",
|
| 467 |
+
type="primary",
|
| 468 |
+
use_container_width=True
|
| 469 |
+
)
|
| 470 |
+
else:
|
| 471 |
+
st.info("π Upload or capture an image to begin")
|
| 472 |
+
process_button = False
|
| 473 |
+
|
| 474 |
+
# Processing
|
| 475 |
+
if image is not None and process_button:
|
| 476 |
+
with st.spinner("π Processing document..."):
|
| 477 |
+
try:
|
| 478 |
+
# Preprocess image
|
| 479 |
+
if enhance_contrast or denoise or sharpen or auto_rotate or prevent_cropping:
|
| 480 |
+
preprocessed_image = preprocess_image(
|
| 481 |
+
image,
|
| 482 |
+
enhance_contrast=enhance_contrast,
|
| 483 |
+
denoise=denoise,
|
| 484 |
+
sharpen=sharpen,
|
| 485 |
+
auto_rotate=auto_rotate,
|
| 486 |
+
prevent_cropping=prevent_cropping
|
| 487 |
+
)
|
| 488 |
+
else:
|
| 489 |
+
preprocessed_image = image
|
| 490 |
+
|
| 491 |
+
# Show preprocessed if requested
|
| 492 |
+
if show_preprocessed and preprocessed_image != image:
|
| 493 |
+
st.subheader("π§ Preprocessed Image")
|
| 494 |
+
col_a, col_b = st.columns(2)
|
| 495 |
+
with col_a:
|
| 496 |
+
st.image(image, caption="Original", use_container_width=True)
|
| 497 |
+
with col_b:
|
| 498 |
+
st.image(preprocessed_image, caption="Enhanced", use_container_width=True)
|
| 499 |
+
|
| 500 |
+
# Extract text
|
| 501 |
+
output_text, processing_time = extract_text(
|
| 502 |
+
preprocessed_image,
|
| 503 |
+
prompt=prompt,
|
| 504 |
+
max_tokens=max_tokens
|
| 505 |
+
)
|
| 506 |
+
|
| 507 |
+
# Display results
|
| 508 |
+
st.success(f"β
Extraction complete! ({processing_time}ms)")
|
| 509 |
+
|
| 510 |
+
# Try to parse as JSON for structured documents
|
| 511 |
+
is_json = False
|
| 512 |
+
parsed_data = None
|
| 513 |
+
|
| 514 |
+
if doc_type in [DocumentType.ID_CARD, DocumentType.RECEIPT,
|
| 515 |
+
DocumentType.INVOICE, DocumentType.BUSINESS_CARD,
|
| 516 |
+
DocumentType.FORM]:
|
| 517 |
+
try:
|
| 518 |
+
# Clean JSON from markdown
|
| 519 |
+
clean_text = output_text
|
| 520 |
+
if "```json" in clean_text:
|
| 521 |
+
clean_text = clean_text.split("```json")[1].split("```")[0].strip()
|
| 522 |
+
elif "```" in clean_text:
|
| 523 |
+
clean_text = clean_text.split("```")[1].split("```")[0].strip()
|
| 524 |
+
|
| 525 |
+
parsed_data = json.loads(clean_text)
|
| 526 |
+
is_json = True
|
| 527 |
+
except json.JSONDecodeError:
|
| 528 |
+
is_json = False
|
| 529 |
+
|
| 530 |
+
# Display based on type
|
| 531 |
+
st.markdown("---")
|
| 532 |
+
st.subheader("π Extracted Data")
|
| 533 |
+
|
| 534 |
+
if is_json and parsed_data:
|
| 535 |
+
# Structured data display
|
| 536 |
+
col_display, col_download = st.columns([2, 1])
|
| 537 |
+
|
| 538 |
+
with col_display:
|
| 539 |
+
# Format display based on document type
|
| 540 |
+
if doc_type == DocumentType.RECEIPT:
|
| 541 |
+
st.markdown("### π§Ύ Receipt Details")
|
| 542 |
+
|
| 543 |
+
# Merchant info
|
| 544 |
+
if "merchant_name" in parsed_data:
|
| 545 |
+
st.markdown(f"**Merchant:** {parsed_data['merchant_name']}")
|
| 546 |
+
if "date" in parsed_data:
|
| 547 |
+
st.markdown(f"**Date:** {parsed_data['date']}")
|
| 548 |
+
if "time" in parsed_data:
|
| 549 |
+
st.markdown(f"**Time:** {parsed_data['time']}")
|
| 550 |
+
|
| 551 |
+
# Items table
|
| 552 |
+
if "items" in parsed_data and parsed_data["items"]:
|
| 553 |
+
st.markdown("**Items:**")
|
| 554 |
+
items_df = pd.DataFrame(parsed_data["items"])
|
| 555 |
+
st.dataframe(items_df, use_container_width=True, hide_index=True)
|
| 556 |
+
|
| 557 |
+
# Totals
|
| 558 |
+
st.markdown("---")
|
| 559 |
+
if "subtotal" in parsed_data:
|
| 560 |
+
st.markdown(f"**Subtotal:** ${parsed_data['subtotal']:.2f}")
|
| 561 |
+
if "tax" in parsed_data:
|
| 562 |
+
st.markdown(f"**Tax:** ${parsed_data['tax']:.2f}")
|
| 563 |
+
if "total" in parsed_data:
|
| 564 |
+
st.markdown(f"**Total:** ${parsed_data['total']:.2f}")
|
| 565 |
+
|
| 566 |
+
elif doc_type == DocumentType.INVOICE:
|
| 567 |
+
st.markdown("### π Invoice Details")
|
| 568 |
+
|
| 569 |
+
col_inv1, col_inv2 = st.columns(2)
|
| 570 |
+
|
| 571 |
+
with col_inv1:
|
| 572 |
+
st.markdown("**Invoice Info:**")
|
| 573 |
+
if "invoice_number" in parsed_data:
|
| 574 |
+
st.text(f"Number: {parsed_data['invoice_number']}")
|
| 575 |
+
if "date" in parsed_data:
|
| 576 |
+
st.text(f"Date: {parsed_data['date']}")
|
| 577 |
+
if "due_date" in parsed_data:
|
| 578 |
+
st.text(f"Due: {parsed_data['due_date']}")
|
| 579 |
+
|
| 580 |
+
with col_inv2:
|
| 581 |
+
if "vendor" in parsed_data:
|
| 582 |
+
st.markdown("**Vendor:**")
|
| 583 |
+
vendor = parsed_data["vendor"]
|
| 584 |
+
if isinstance(vendor, dict):
|
| 585 |
+
for k, v in vendor.items():
|
| 586 |
+
if v:
|
| 587 |
+
st.text(f"{k.title()}: {v}")
|
| 588 |
+
|
| 589 |
+
# Line items
|
| 590 |
+
if "line_items" in parsed_data and parsed_data["line_items"]:
|
| 591 |
+
st.markdown("**Line Items:**")
|
| 592 |
+
items_df = pd.DataFrame(parsed_data["line_items"])
|
| 593 |
+
st.dataframe(items_df, use_container_width=True, hide_index=True)
|
| 594 |
+
|
| 595 |
+
# Total
|
| 596 |
+
if "total" in parsed_data:
|
| 597 |
+
st.markdown(f"### **Total: ${parsed_data['total']:.2f}**")
|
| 598 |
+
|
| 599 |
+
else:
|
| 600 |
+
# Generic structured data display
|
| 601 |
+
for key, value in parsed_data.items():
|
| 602 |
+
if isinstance(value, dict):
|
| 603 |
+
st.markdown(f"**{key.replace('_', ' ').title()}:**")
|
| 604 |
+
for k, v in value.items():
|
| 605 |
+
st.text(f" {k}: {v}")
|
| 606 |
+
elif isinstance(value, list):
|
| 607 |
+
st.markdown(f"**{key.replace('_', ' ').title()}:**")
|
| 608 |
+
if value and isinstance(value[0], dict):
|
| 609 |
+
df = pd.DataFrame(value)
|
| 610 |
+
st.dataframe(df, use_container_width=True, hide_index=True)
|
| 611 |
+
else:
|
| 612 |
+
for item in value:
|
| 613 |
+
st.text(f" β’ {item}")
|
| 614 |
+
else:
|
| 615 |
+
st.markdown(f"**{key.replace('_', ' ').title()}:** {value}")
|
| 616 |
+
|
| 617 |
+
with col_download:
|
| 618 |
+
st.subheader("πΎ Downloads")
|
| 619 |
+
|
| 620 |
+
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 621 |
+
|
| 622 |
+
# JSON download
|
| 623 |
+
json_str = json.dumps(parsed_data, ensure_ascii=False, indent=2)
|
| 624 |
+
st.download_button(
|
| 625 |
+
label="π JSON",
|
| 626 |
+
data=json_str,
|
| 627 |
+
file_name=f"{doc_type.value}_{timestamp}.json",
|
| 628 |
+
mime="application/json",
|
| 629 |
+
use_container_width=True
|
| 630 |
+
)
|
| 631 |
+
|
| 632 |
+
# CSV download (flattened)
|
| 633 |
+
try:
|
| 634 |
+
# Flatten nested structures
|
| 635 |
+
flat_data = {}
|
| 636 |
+
for k, v in parsed_data.items():
|
| 637 |
+
if isinstance(v, (dict, list)):
|
| 638 |
+
flat_data[k] = json.dumps(v, ensure_ascii=False)
|
| 639 |
+
else:
|
| 640 |
+
flat_data[k] = v
|
| 641 |
+
|
| 642 |
+
df = pd.DataFrame([flat_data])
|
| 643 |
+
csv_buffer = StringIO()
|
| 644 |
+
df.to_csv(csv_buffer, index=False, encoding='utf-8')
|
| 645 |
+
|
| 646 |
+
st.download_button(
|
| 647 |
+
label="π CSV",
|
| 648 |
+
data=csv_buffer.getvalue(),
|
| 649 |
+
file_name=f"{doc_type.value}_{timestamp}.csv",
|
| 650 |
+
mime="text/csv",
|
| 651 |
+
use_container_width=True
|
| 652 |
+
)
|
| 653 |
+
except:
|
| 654 |
+
pass
|
| 655 |
+
|
| 656 |
+
# Raw text download
|
| 657 |
+
st.download_button(
|
| 658 |
+
label="π TXT",
|
| 659 |
+
data=output_text,
|
| 660 |
+
file_name=f"{doc_type.value}_{timestamp}.txt",
|
| 661 |
+
mime="text/plain",
|
| 662 |
+
use_container_width=True
|
| 663 |
+
)
|
| 664 |
+
|
| 665 |
+
# Show raw JSON in expander
|
| 666 |
+
with st.expander("π View Raw JSON"):
|
| 667 |
+
st.json(parsed_data)
|
| 668 |
+
|
| 669 |
+
else:
|
| 670 |
+
# Plain text display
|
| 671 |
+
st.text_area(
|
| 672 |
+
"Extracted Text:",
|
| 673 |
+
value=output_text,
|
| 674 |
+
height=400,
|
| 675 |
+
label_visibility="collapsed"
|
| 676 |
+
)
|
| 677 |
+
|
| 678 |
+
# Download
|
| 679 |
+
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 680 |
+
st.download_button(
|
| 681 |
+
label="πΎ Download as TXT",
|
| 682 |
+
data=output_text,
|
| 683 |
+
file_name=f"extracted_text_{timestamp}.txt",
|
| 684 |
+
mime="text/plain"
|
| 685 |
+
)
|
| 686 |
+
|
| 687 |
+
except Exception as e:
|
| 688 |
+
st.error(f"β Error during extraction: {str(e)}")
|
| 689 |
+
import traceback
|
| 690 |
+
|
| 691 |
+
with st.expander("Show Error Details"):
|
| 692 |
+
st.code(traceback.format_exc())
|
| 693 |
+
|
| 694 |
+
# Footer
|
| 695 |
+
st.markdown("---")
|
| 696 |
+
col_footer1, col_footer2, col_footer3 = st.columns(3)
|
| 697 |
+
|
| 698 |
+
with col_footer1:
|
| 699 |
+
st.caption("β‘ Powered by GLM-OCR")
|
| 700 |
+
|
| 701 |
+
with col_footer2:
|
| 702 |
+
st.caption(f"π₯οΈ Device: {device.upper()}")
|
| 703 |
|
| 704 |
+
with col_footer3:
|
| 705 |
+
st.caption("π Universal Document Scanner")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|