Spaces:
Running on Zero

mrrobot2610's picture
Upload app.py with huggingface_hub
6d6dedf verified
Raw History Blame Contribute Delete
6.27 kB
import spaces
import logging
from importlib.util import find_spec
from pathlib import Path
from time import perf_counter
import cv2
import gradio as gr
import numpy as np
from PIL import Image, ImageOps
# EasyOCR 1.7.2 pins CPU batches through CUDA; ZeroGPU has no CUDA in its web process.
recognition_path = Path(find_spec("easyocr").origin).parent / "recognition.py"
recognition_source = recognition_path.read_text()
recognition_path.write_text(recognition_source.replace("pin_memory=True", "pin_memory=(device != 'cpu')"))
from demo_mode import DemoClassifier, DemoNER
from ocr_engine import LightweightOCR
from postprocessing import PostProcessor
from preprocessing import DocumentPreprocessor
logging.basicConfig(level=logging.INFO)
classifier, ner, postprocessor = DemoClassifier(), DemoNER(), PostProcessor()
preprocessor = DocumentPreprocessor()
ocr = LightweightOCR(use_gpu=False)
Image.MAX_IMAGE_PIXELS = 20_000_000
@spaces.GPU(duration=1)
def hosting_placeholder() -> None:
"""Register ZeroGPU hosting; document processing runs on CPU."""
pass
def extract(text: str, boxes: list[dict]) -> tuple[str, list, dict, str]:
if not text or not text.strip():
raise gr.Error("No text found. Paste document text or try a clearer scan.")
if len(text) > 50_000:
raise gr.Error("Please use at most 50,000 characters.")
prediction = classifier.predict(text)
result = postprocessor.process_document(
prediction["predicted_class"], prediction["confidence"],
text, boxes, ner.predict(text)["entities"],
)
result["mode"] = "rule-based demo (no trained classifier or NER weights)"
result["source_model"] = "mrrobot2610/IDP-Machine-learning"
rows = [[name.replace("_", " ").title(), field["value"]]
for name, field in result["fields"].items()]
summary = f"### {result['document_type'].replace('_', ' ').title()}\n{len(rows)} fields extracted · rule-based demo"
return summary, rows, result, text
def process_text(text: str) -> tuple[str, list, dict, str]:
"""Classify pasted document text and extract fields using the source repository's demo rules."""
return extract(text, [])
def process_image(file_path: str) -> tuple[str, list, dict, str]:
"""Run English OCR on a document image and extract structured fields using demo rules."""
if not file_path:
raise gr.Error("Upload a PNG, JPEG, BMP, or TIFF document first.")
if Path(file_path).stat().st_size > 12 * 1024 * 1024:
raise gr.Error("Please use an image smaller than 12 MB.")
started = perf_counter()
try:
with Image.open(file_path) as image:
if image.width * image.height > Image.MAX_IMAGE_PIXELS:
raise gr.Error("Please use an image with at most 20 million pixels.")
image = ImageOps.exif_transpose(image).convert("RGB")
array = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
except (OSError, Image.DecompressionBombError) as exc:
raise gr.Error("This file could not be read as an image.") from exc
result = ocr.extract_text(preprocessor.preprocess(array), confidence_threshold=0.3)
summary, rows, structured, text = extract(result["text"], result["boxes"])
structured["processing_seconds"] = round(perf_counter() - started, 3)
return summary, rows, structured, text
EXAMPLES = [
["INVOICE #INV-12345\nDate: 28/11/2025\nTotal: $1,250.00\nTax: $125.00"],
["RECEIPT\nCorner Store\nDate: 24/11/2026\nTotal: $42.50\nTax: $2.50"],
["BANK STATEMENT\nDate: 24/11/2026\nClosing balance: $5,200.00"],
]
with gr.Blocks(title="IDP · Document Intelligence", delete_cache=(3600, 3600)) as demo:
gr.Markdown("# 📄 IDP · Document Intelligence\nTurn document images or pasted text into structured data. "
"[View the source model](https://huggingface.co/mrrobot2610/IDP-Machine-learning)")
gr.Markdown("**Demo mode:** real English OCR with the repository’s rule-based classifier and field extractor. "
"The repository does not contain trained classifier or NER checkpoints. "
"Extracted fields may be incorrect; review them before use.")
with gr.Row():
with gr.Column():
with gr.Tab("Upload a document"):
image = gr.File(label="Document image · up to 12 MB / 20 MP", file_types=[".png", ".jpg", ".jpeg", ".bmp", ".tif", ".tiff"])
image_run = gr.Button("Extract from image", variant="primary")
gr.Examples(examples=[["examples/invoice.png"]], inputs=image, label="Try a synthetic invoice")
with gr.Tab("Paste text"):
text_input = gr.Textbox(label="Document text", lines=10, placeholder="Paste an invoice, receipt, form, or bank statement…", max_length=50_000)
text_run = gr.Button("Extract from text", variant="primary")
text_examples = gr.Examples(examples=EXAMPLES, inputs=text_input, label="Try an example")
with gr.Column():
summary = gr.Markdown("### Ready to extract\nUpload a document or try an example.")
table = gr.Dataframe(headers=["Field", "Value"], datatype=["str", "str"], interactive=False, label="Extracted fields")
with gr.Tab("Structured JSON"):
structured = gr.JSON(label="Result")
with gr.Tab("Document text"):
raw_text = gr.Textbox(label="Full text", lines=10, interactive=False)
outputs = [summary, table, structured, raw_text]
image_run.click(process_image, image, outputs, api_name="process_image", concurrency_limit=1)
text_run.click(process_text, text_input, outputs, api_name="process_text", concurrency_limit=1)
gr.Button(visible=False).click(hosting_placeholder, api_name=False)
gr.Markdown("English documents · single image per run · synthetic examples · uploaded files are processed on this Space. "
"Temporary uploads are cleaned periodically.")
if __name__ == "__main__":
demo.queue(max_size=16).launch(
theme=gr.themes.Soft(),
css=".gradio-container {max-width: 1150px !important; margin: auto} .dark .gradio-container {color: var(--body-text-color)}",
mcp_server=True, max_file_size="12mb",
)