Views
No views yet
[!important] This is the OCR weight component of the PaddlePaddle/PaddleOCR-VL model. These weights cannot be used for other use cases. If you wish to do so, please visit the original model page!
This repository directly exposes the OCR-only weights for smoother transformers implementation of the PaddleOCR-VL model.
[!note] Last updated: 4:00 AM (IST), October 25, 2025.
[!note] The latest transformers version used as of the above date istransformers==4.57.1and the torch version2.8.0+cu126
Install the required packages
1!pip install transformers torch torchvision gradio hf_xet \
2 huggingface_hub pillow accelerate peft \
3 matplotlib requests einops av sentencepiece\
4 transformers-stream-generatornotebook login
1from huggingface_hub import notebook_login, HfApi
2notebook_login()Run [app.py]
1import os
2import sys
3from threading import Thread
4from typing import Iterable
5
6import gradio as gr
7import torch
8from PIL import Image
9from transformers import (
10 AutoModelForCausalLM,
11 AutoProcessor,
12 TextIteratorStreamer,
13)
14
15from gradio.themes import Soft
16from gradio.themes.utils import colors, fonts, sizes
17
18# --- Theme and CSS Setup ---
19colors.steel_blue = colors.Color(
20 name="steel_blue",
21 c50="#EBF3F8",
22 c100="#D3E5F0",
23 c200="#A8CCE1",
24 c300="#7DB3D2",
25 c400="#529AC3",
26 c500="#4682B4",
27 c600="#3E72A0",
28 c700="#36638C",
29 c800="#2E5378",
30 c900="#264364",
31 c950="#1E3450",
32)
33
34class SteelBlueTheme(Soft):
35 def __init__(
36 self,
37 *,
38 primary_hue: colors.Color | str = colors.gray,
39 secondary_hue: colors.Color | str = colors.steel_blue,
40 neutral_hue: colors.Color | str = colors.slate,
41 text_size: sizes.Size | str = sizes.text_lg,
42 font: fonts.Font | str | Iterable[fonts.Font | str] = (
43 fonts.GoogleFont("Outfit"), "Arial", "sans-serif",
44 ),
45 font_mono: fonts.Font | str | Iterable[fonts.Font | str] = (
46 fonts.GoogleFont("IBM Plex Mono"), "ui-monospace", "monospace",
47 ),
48 ):
49 super().__init__(
50 primary_hue=primary_hue,
51 secondary_hue=secondary_hue,
52 neutral_hue=neutral_hue,
53 text_size=text_size,
54 font=font,
55 font_mono=font_mono,
56 )
57 super().set(
58 background_fill_primary="*primary_50",
59 background_fill_primary_dark="*primary_900",
60 body_background_fill="linear-gradient(135deg, *primary_200, *primary_100)",
61 body_background_fill_dark="linear-gradient(135deg, *primary_900, *primary_800)",
62 button_primary_text_color="white",
63 button_primary_text_color_hover="white",
64 button_primary_background_fill="linear-gradient(90deg, *secondary_500, *secondary_600)",
65 button_primary_background_fill_hover="linear-gradient(90deg, *secondary_600, *secondary_700)",
66 button_primary_background_fill_dark="linear-gradient(90deg, *secondary_600, *secondary_700)",
67 button_primary_background_fill_hover_dark="linear-gradient(90deg, *secondary_500, *secondary_600)",
68 slider_color="*secondary_500",
69 slider_color_dark="*secondary_600",
70 block_title_text_weight="600",
71 block_border_width="3px",
72 block_shadow="*shadow_drop_lg",
73 button_primary_shadow="*shadow_drop_lg",
74 button_large_padding="11px",
75 color_accent_soft="*primary_100",
76 block_label_background_fill="*primary_200",
77 )
78
79steel_blue_theme = SteelBlueTheme()
80
81css = """
82#main-title h1 {
83 font-size: 2.3em !important;
84}
85#output-title h2 {
86 font-size: 2.1em !important;
87}
88"""
89
90# --- Model Configuration and Loading ---
91MAX_MAX_NEW_TOKENS = 4096
92DEFAULT_MAX_NEW_TOKENS = 2048
93MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096"))
94
95device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
96
97# Load PaddleOCR
98MODEL_ID_P = "strangervisionhf/paddle.ocr_path_expose" # -> Original model: https://huggingface.co/PaddlePaddle/PaddleOCR-VL
99processor = AutoProcessor.from_pretrained(MODEL_ID_P, trust_remote_code=True)
100model = AutoModelForCausalLM.from_pretrained(
101 MODEL_ID_P,
102 trust_remote_code=True,
103 torch_dtype=torch.bfloat16
104).to(device).eval()
105
106# --- Generation Function ---
107def generate_image(text: str, image: Image.Image,
108 max_new_tokens: int = 1024,
109 temperature: float = 0.6,
110 top_p: float = 0.9,
111 top_k: int = 50,
112 repetition_penalty: float = 1.2):
113 """Generate responses for image input using the PaddleOCR model."""
114 if image is None:
115 yield "Please upload an image.", "Please upload an image."
116 return
117
118 images = [image.convert("RGB")]
119
120 # PaddleOCR has a specific message format
121 messages = [
122 {"role": "user", "content": text}
123 ]
124
125 prompt = processor.apply_chat_template(messages, add_generation_prompt=True)
126 inputs = processor(text=prompt, images=images, return_tensors="pt").to(device)
127
128 streamer = TextIteratorStreamer(processor, skip_prompt=True, skip_special_tokens=True)
129 generation_kwargs = {
130 **inputs,
131 "streamer": streamer,
132 "max_new_tokens": max_new_tokens,
133 "temperature": temperature,
134 "top_p": top_p,
135 "top_k": top_k,
136 "repetition_penalty": repetition_penalty,
137 "do_sample": True
138 }
139 thread = Thread(target=model.generate, kwargs=generation_kwargs)
140 thread.start()
141
142 buffer = ""
143 for new_text in streamer:
144 buffer += new_text.replace("<|im_end|>", "").replace("<end_of_utterance>", "")
145 yield buffer, buffer
146
147
148with gr.Blocks(css=css, theme=steel_blue_theme) as demo:
149 gr.Markdown("# **Paddle OCR Only**", elem_id="main-title")
150 with gr.Row():
151 with gr.Column(scale=2):
152 image_query = gr.Textbox(label="Query Input", placeholder="Enter your query here...")
153 image_upload = gr.Image(type="pil", label="Upload Image", height=320)
154 image_submit = gr.Button("Submit", variant="primary")
155
156 with gr.Accordion("Advanced options", open=False):
157 max_new_tokens = gr.Slider(label="Max new tokens", minimum=1, maximum=MAX_MAX_NEW_TOKENS, step=1, value=DEFAULT_MAX_NEW_TOKENS)
158 temperature = gr.Slider(label="Temperature", minimum=0.1, maximum=4.0, step=0.1, value=0.6)
159 top_p = gr.Slider(label="Top-p (nucleus sampling)", minimum=0.05, maximum=1.0, step=0.05, value=0.9)
160 top_k = gr.Slider(label="Top-k", minimum=1, maximum=1000, step=1, value=50)
161 repetition_penalty = gr.Slider(label="Repetition penalty", minimum=1.0, maximum=2.0, step=0.05, value=1.2)
162
163 with gr.Column(scale=3):
164 gr.Markdown("## Output", elem_id="output-title")
165 raw_output = gr.Textbox(label="Raw Output Stream", interactive=False, lines=11, show_copy_button=True)
166 with gr.Accordion("[Result.md]", open=False):
167 formatted_output = gr.Markdown(label="Formatted Result")
168
169 gr.Markdown("Note: Currently, PaddleOCR VL only supports OCR inference. Structured OCR document parsing transformer inference is coming soon. [Report – Bug/Issue](https://huggingface.co/spaces/prithivMLmods/Multimodal-OCR3/discussions/1)")
170
171 image_submit.click(
172 fn=generate_image,
173 inputs=[image_query, image_upload, max_new_tokens, temperature, top_p, top_k, repetition_penalty],
174 outputs=[raw_output, formatted_output]
175 )
176
177if __name__ == "__main__":
178 demo.queue(max_size=50).launch(mcp_server=True, ssr_mode=False, show_error=True)