Views
No views yet

Nanonets-OCR2-3B-AWQ-nvfp4 model is anexperimentalquantized version of the Nanonets-OCR2-3B model, featuring 3 billion parameters and multiple tensor types including F32, BF16, F8_E4M3, and U8, optimized for efficient inference. It is based on the Qwen/Qwen2.5-VL-3B-Instruct base model and fine-tuned on Nanonets-OCR2 data, designed for advanced image-to-markdown OCR tasks such as recognizing LaTeX equations, complex tables, signatures, watermarks, checkboxes, and multilingual handwritten text, outputting documents in structured markdown with intelligent semantic tagging suitable for large language model downstream processing. Despite being experimental and not yet deployed by any inference provider, it supports image-text-to-text processing ideal for complex document workflows involving multipart content types including flowcharts and organizational charts, with applications in business, financial, and multilingual domains. This quantized variant is part of ongoing efforts to enable efficient use of this powerful OCR technology on lighter hardware while maintaining sophisticated extraction capabilities.
gradio
torch
torchvision
transformers==4.57.1
accelerate
matplotlib
anyio
compressed-tensors1import os
2import sys
3import random
4import uuid
5import json
6import time
7from threading import Thread
8from typing import Iterable
9from huggingface_hub import snapshot_download
10
11import gradio as gr
12import torch
13import numpy as np
14from PIL import Image
15import cv2
16
17from transformers import (
18 Qwen2_5_VLForConditionalGeneration,
19 AutoProcessor,
20 TextIteratorStreamer,
21)
22
23from transformers.image_utils import load_image
24
25css = """
26#main-title h1 {
27 font-size: 2.3em !important;
28}
29#output-title h2 {
30 font-size: 2.1em !important;
31}
32"""
33
34MAX_MAX_NEW_TOKENS = 4096
35DEFAULT_MAX_NEW_TOKENS = 1024
36MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096"))
37
38device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
39
40MODEL_ID = "prithivMLmods/Nanonets-OCR2-3B-AWQ-nvfp4"
41print(f"Loading model: {MODEL_ID}")
42processor = AutoProcessor.from_pretrained(MODEL_ID, trust_remote_code=True)
43model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
44 MODEL_ID,
45 trust_remote_code=True,
46 torch_dtype="auto",
47).to(device).eval()
48print("Model loaded successfully.")
49
50def generate_image(text: str, image: Image.Image,
51 max_new_tokens: int, temperature: float, top_p: float,
52 top_k: int, repetition_penalty: float):
53 """
54 Generates responses using the Nanonets-OCR2-3B model for image input.
55 Yields raw text and Markdown-formatted text.
56 """
57 if image is None:
58 yield "Please upload an image.", "Please upload an image."
59 return
60
61 messages = [{
62 "role": "user",
63 "content": [
64 {"type": "image"},
65 {"type": "text", "text": text},
66 ]
67 }]
68 prompt_full = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
69
70 inputs = processor(
71 text=[prompt_full],
72 images=[image],
73 return_tensors="pt",
74 padding=True).to(device)
75
76 streamer = TextIteratorStreamer(processor, skip_prompt=True, skip_special_tokens=True)
77 generation_kwargs = {
78 **inputs,
79 "streamer": streamer,
80 "max_new_tokens": max_new_tokens,
81 "do_sample": True,
82 "temperature": temperature,
83 "top_p": top_p,
84 "top_k": top_k,
85 "repetition_penalty": repetition_penalty,
86 }
87 thread = Thread(target=model.generate, kwargs=generation_kwargs)
88 thread.start()
89
90 buffer = ""
91 for new_text in streamer:
92 buffer += new_text
93 time.sleep(0.01)
94 yield buffer, buffer
95
96with gr.Blocks(css=css) as demo:
97 gr.Markdown("# **Nanonets-OCR2-3B-AWQ-nvfp4**", elem_id="main-title")
98 with gr.Row():
99 with gr.Column(scale=2):
100 image_query = gr.Textbox(label="Query Input", placeholder="Enter your query here...")
101 image_upload = gr.Image(type="pil", label="Upload Image", height=290)
102
103 image_submit = gr.Button("Submit", variant="primary")
104
105 with gr.Accordion("Advanced options", open=False):
106 max_new_tokens = gr.Slider(label="Max new tokens", minimum=1, maximum=MAX_MAX_NEW_TOKENS, step=1, value=DEFAULT_MAX_NEW_TOKENS)
107 temperature = gr.Slider(label="Temperature", minimum=0.1, maximum=4.0, step=0.1, value=0.7)
108 top_p = gr.Slider(label="Top-p (nucleus sampling)", minimum=0.05, maximum=1.0, step=0.05, value=0.9)
109 top_k = gr.Slider(label="Top-k", minimum=1, maximum=1000, step=1, value=50)
110 repetition_penalty = gr.Slider(label="Repetition penalty", minimum=1.0, maximum=2.0, step=0.05, value=1.1)
111
112 with gr.Column(scale=3):
113 gr.Markdown("## Output", elem_id="output-title")
114 output = gr.Textbox(label="Raw Output Stream", interactive=False, lines=15, show_copy_button=True)
115 with gr.Accordion("(Result.md)", open=False):
116 markdown_output = gr.Markdown(label="(Result.Md)")
117
118 image_submit.click(
119 fn=generate_image,
120 inputs=[image_query, image_upload, max_new_tokens, temperature, top_p, top_k, repetition_penalty],
121 outputs=[output, markdown_output]
122 )
123
124if __name__ == "__main__":
125 demo.queue(max_size=50).launch(debug=True)All the restrictions and guidelines will be followed as in the original model Nanonets-OCR2-3B.


| Resource Type | Description | Link |
|---|---|---|
| Original Model Card | Official release of Nanonets-OCR2-3B by Nanonets | nanonets/Nanonets-OCR2-3B |
| Optimized Model (AWQ-nvfp4) | Quantized version optimized for efficient inference and deployment | prithivMLmods/Nanonets-OCR2-3B-AWQ-nvfp4 |
| Demo Space | Interactive demo hosted on Hugging Face Spaces | Multimodal-OCR3 Demo |