Spaces:
Runtime error
Runtime error
Download app.py from abidlabs/ocr-model-comparison: direct link, hf CLI and curl.
- Browser
- Download file 8.65 kB
-
https://huggingface.co/spaces/abidlabs/ocr-model-comparison/resolve/main/app.py
- Command line
-
hf download hf://spaces/abidlabs/ocr-model-comparison/app.py
-
curl -L -o app.py https://huggingface.co/spaces/abidlabs/ocr-model-comparison/resolve/main/app.py
8.65 kB
| import gc | |
| import gradio as gr | |
| import spaces | |
| import torch | |
| from PIL import Image | |
| from transformers import ( | |
| AutoProcessor, | |
| AutoTokenizer, | |
| Qwen2_5_VLForConditionalGeneration, | |
| Qwen2VLForConditionalGeneration, | |
| ViTImageProcessor, | |
| VisionEncoderDecoderModel, | |
| ) | |
| # Inference pattern follows the model cards for each model and the working | |
| # reference Space prithivMLmods/Multimodal-OCR (app.py), which loads the same | |
| # Qwen-family models on Spaces GPU hardware. | |
| DEVICE = "cuda" if torch.cuda.is_available() else "cpu" | |
| VLM_DTYPE = torch.float16 | |
| MANGA_MODEL_ID = "kha-white/manga-ocr-base" | |
| QARI_MODEL_ID = "NAMAA-Space/Qari-OCR-v0.3-VL-2B-Instruct" | |
| NANONETS_MODEL_ID = "nanonets/Nanonets-OCR2-3B" | |
| MAX_IMAGE_DIM = 2000 # bound the vision-token count for large uploads | |
| QARI_PROMPT = ( | |
| "Below is the image of one page of a document, as well as some raw textual " | |
| "content that was previously extracted for it. Just return the plain text " | |
| "representation of this document as if you were reading it naturally. " | |
| "Do not hallucinate." | |
| ) | |
| NANONETS_PROMPT = ( | |
| "Extract the text from the above document as if you were reading it " | |
| "naturally. Return the tables in html format. Return the equations in " | |
| "LaTeX representation. If there is an image in the document and image " | |
| "caption is not present, add a small description of the image inside the " | |
| "<img></img> tag; otherwise, add the image caption inside <img></img>. " | |
| "Watermarks should be wrapped in brackets. Ex: <watermark>OFFICIAL " | |
| "COPY</watermark>. Page numbers should be wrapped in brackets. Ex: " | |
| "<page_number>14</page_number> or <page_number>9/22</page_number>. " | |
| "Prefer using \u2610 and \u2611 for check boxes." | |
| ) | |
| print(f"Device: {DEVICE}") | |
| print(f"torch: {torch.__version__}") | |
| print("Loading kha-white/manga-ocr-base ...") | |
| manga_model = VisionEncoderDecoderModel.from_pretrained(MANGA_MODEL_ID).to(DEVICE).eval() | |
| manga_feature_extractor = ViTImageProcessor.from_pretrained(MANGA_MODEL_ID) | |
| manga_tokenizer = AutoTokenizer.from_pretrained(MANGA_MODEL_ID) | |
| print("Loading NAMAA-Space/Qari-OCR-v0.3-VL-2B-Instruct ...") | |
| qari_processor = AutoProcessor.from_pretrained(QARI_MODEL_ID) | |
| qari_model = ( | |
| Qwen2VLForConditionalGeneration.from_pretrained(QARI_MODEL_ID, torch_dtype=VLM_DTYPE) | |
| .to(DEVICE) | |
| .eval() | |
| ) | |
| print("Loading nanonets/Nanonets-OCR2-3B ...") | |
| nanonets_processor = AutoProcessor.from_pretrained(NANONETS_MODEL_ID) | |
| nanonets_model = ( | |
| Qwen2_5_VLForConditionalGeneration.from_pretrained(NANONETS_MODEL_ID, torch_dtype=VLM_DTYPE) | |
| .to(DEVICE) | |
| .eval() | |
| ) | |
| print("All three models loaded.") | |
| def prepare_image(image): | |
| if image is None: | |
| return None | |
| image = image.convert("RGB") | |
| if max(image.size) > MAX_IMAGE_DIM: | |
| image.thumbnail((MAX_IMAGE_DIM, MAX_IMAGE_DIM)) | |
| return image | |
| def run_vlm(model, processor, image, prompt, max_new_tokens): | |
| """Shared Qwen2-VL / Qwen2.5-VL generation, per the model-card usage.""" | |
| messages = [ | |
| { | |
| "role": "user", | |
| "content": [ | |
| {"type": "image"}, | |
| {"type": "text", "text": prompt}, | |
| ], | |
| } | |
| ] | |
| text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) | |
| inputs = processor(text=[text], images=[image], padding=True, return_tensors="pt").to(model.device) | |
| with torch.inference_mode(): | |
| output_ids = model.generate(**inputs, max_new_tokens=max_new_tokens, do_sample=False) | |
| trimmed = [out[len(inp):] for inp, out in zip(inputs.input_ids, output_ids)] | |
| return processor.batch_decode( | |
| trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=True | |
| )[0] | |
| def run_mangaocr(image): | |
| image = prepare_image(image) | |
| if image is None: | |
| return "Please upload an image first." | |
| try: | |
| pixel_values = manga_feature_extractor(images=image, return_tensors="pt").pixel_values.to(DEVICE) | |
| with torch.inference_mode(): | |
| generated_ids = manga_model.generate(pixel_values, max_new_tokens=256) | |
| return manga_tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] | |
| except Exception as e: | |
| return f"[ERROR] {e}" | |
| finally: | |
| gc.collect() | |
| if torch.cuda.is_available(): | |
| torch.cuda.empty_cache() | |
| def run_qari(image): | |
| image = prepare_image(image) | |
| if image is None: | |
| return "Please upload an image first." | |
| try: | |
| return run_vlm(qari_model, qari_processor, image, QARI_PROMPT, max_new_tokens=1024) | |
| except Exception as e: | |
| return f"[ERROR] {e}" | |
| finally: | |
| gc.collect() | |
| if torch.cuda.is_available(): | |
| torch.cuda.empty_cache() | |
| def run_nanonets(image): | |
| image = prepare_image(image) | |
| if image is None: | |
| return "Please upload an image first." | |
| try: | |
| return run_vlm(nanonets_model, nanonets_processor, image, NANONETS_PROMPT, max_new_tokens=2048) | |
| except Exception as e: | |
| return f"[ERROR] {e}" | |
| finally: | |
| gc.collect() | |
| if torch.cuda.is_available(): | |
| torch.cuda.empty_cache() | |
| COMPARISON_TABLE = """ | |
| | | manga-ocr-base | Qari-OCR v0.3 (2B) | Nanonets-OCR2-3B | | |
| |---|---|---|---| | |
| | **Parameters** | ~0.4B (ViT + RoBERTa decoder) | 2.2B (Qwen2-VL finetune) | 3.75B (Qwen2.5-VL finetune) | | |
| | **Scope** | Japanese manga speech bubbles (manga109s) | Arabic documents, layout-aware | Multilingual documents: tables, LaTeX, signatures, watermarks | | |
| | **Output** | Plain text per line/region | Markdown/HTML structure | Structured markdown | | |
| | **Downloads / Likes** | 10.5M / 192 | 490K / 22 | 4.1M / 517 | | |
| | **License** | Apache-2.0 | Apache-2.0 | Qwen license | | |
| | **Last updated** | 2022 (battle-tested) | 2025 | 2025 | | |
| """ | |
| INTRO = """ | |
| # Small OCR Models β Side-by-Side Comparison | |
| Upload **one image** and run it through all three small OCR models. Each model was | |
| built for a very different job, so expect very different outputs: | |
| - **[manga-ocr-base](https://huggingface.co/kha-white/manga-ocr-base)** β Japanese manga speech bubbles. Best on a *cropped text line*; full pages give noisy results. | |
| - **[Qari-OCR v0.3](https://huggingface.co/NAMAA-Space/Qari-OCR-v0.3-VL-2B-Instruct)** β Arabic documents with layout/HTML structure. | |
| - **[Nanonets-OCR2-3B](https://huggingface.co/nanonets/Nanonets-OCR2-3B)** β general multilingual documents β markdown (tables in HTML, equations in LaTeX). | |
| First run per model includes generation warm-up, so expect some latency. | |
| """ | |
| with gr.Blocks(title="Small OCR Models β Comparison") as demo: | |
| gr.Markdown(INTRO) | |
| with gr.Row(): | |
| image_input = gr.Image( | |
| type="pil", | |
| label="Input image (shared by all three models)", | |
| height=420, | |
| ) | |
| with gr.Row(): | |
| run_all_btn = gr.Button("Run all three", variant="primary", scale=2) | |
| with gr.Row(): | |
| with gr.Column(): | |
| gr.Markdown("### manga-ocr-base (`kha-white/manga-ocr-base`)\nJapanese manga / printed Japanese text. No prompt β direct transcription.") | |
| manga_btn = gr.Button("Run manga-ocr only") | |
| manga_output = gr.Textbox(label="manga-ocr output", lines=12, show_copy_button=True) | |
| with gr.Column(): | |
| gr.Markdown("### Qari-OCR v0.3 (`NAMAA-Space/Qari-OCR-v0.3-VL-2B-Instruct`)\nArabic documents, layout-aware (HTML/Markdown). Card prompt.") | |
| qari_btn = gr.Button("Run Qari-OCR only") | |
| qari_output = gr.Textbox(label="Qari-OCR output", lines=12, show_copy_button=True) | |
| with gr.Column(): | |
| gr.Markdown("### Nanonets-OCR2-3B (`nanonets/Nanonets-OCR2-3B`)\nMultilingual documents \u2192 structured markdown. Card extraction prompt.") | |
| nanonets_btn = gr.Button("Run Nanonets-OCR2 only") | |
| nanonets_output = gr.Textbox(label="Nanonets-OCR2 output", lines=12, show_copy_button=True) | |
| # "Run all three" fires the three GPU tasks concurrently (one event per model) | |
| run_all_btn.click(run_mangaocr, inputs=image_input, outputs=manga_output) | |
| run_all_btn.click(run_qari, inputs=image_input, outputs=qari_output) | |
| run_all_btn.click(run_nanonets, inputs=image_input, outputs=nanonets_output) | |
| manga_btn.click(run_mangaocr, inputs=image_input, outputs=manga_output) | |
| qari_btn.click(run_qari, inputs=image_input, outputs=qari_output) | |
| nanonets_btn.click(run_nanonets, inputs=image_input, outputs=nanonets_output) | |
| gr.Markdown("## Spec comparison\n" + COMPARISON_TABLE) | |
| if __name__ == "__main__": | |
| demo.launch() | |