prithivMLmods commited on
Commit
af83f4b
·
verified ·
1 Parent(s): da693b8

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +263 -0
README.md CHANGED
@@ -21,3 +21,266 @@ Last updated: 7:30 PM (IST), October 29, 2025.
21
 
22
  > [!note]
23
  The latest transformers version used as of the above date is `transformers==4.57.1`, the torch version `2.6.0+cu124`, torch.version.cuda = `12.4` and and tested on the device `NVIDIA H200 MIG 3g.71gb`
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
  > [!note]
23
  The latest transformers version used as of the above date is `transformers==4.57.1`, the torch version `2.6.0+cu124`, torch.version.cuda = `12.4` and and tested on the device `NVIDIA H200 MIG 3g.71gb`
24
+
25
+ ## Quick Start with Transformers
26
+
27
+ #### Install the required packages
28
+
29
+ ```
30
+ torch==2.6.0
31
+ transformers==4.57.1
32
+ einops
33
+ addict
34
+ easydict
35
+ pip install flash-attn==2.7.3
36
+ ```
37
+
38
+ ### Run [app.py]
39
+
40
+ ```py
41
+ import gradio as gr
42
+ import torch
43
+ import requests
44
+ from transformers import AutoModel, AutoTokenizer
45
+ import spaces
46
+ from typing import Iterable
47
+ import os
48
+ import tempfile
49
+ from PIL import Image, ImageDraw
50
+ import re
51
+ from gradio.themes import Soft
52
+ from gradio.themes.utils import colors, fonts, sizes
53
+ from docling_core.types.doc import DoclingDocument, DocTagsDocument
54
+
55
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
56
+
57
+ print("CUDA_VISIBLE_DEVICES=", os.environ.get("CUDA_VISIBLE_DEVICES"))
58
+ print("torch.__version__ =", torch.__version__)
59
+ print("torch.version.cuda =", torch.version.cuda)
60
+ print("cuda available:", torch.cuda.is_available())
61
+ print("cuda device count:", torch.cuda.device_count())
62
+ if torch.cuda.is_available():
63
+ print("current device:", torch.cuda.current_device())
64
+ print("device name:", torch.cuda.get_device_name(torch.cuda.current_device()))
65
+
66
+ print("Using device:", device)
67
+
68
+
69
+ colors.steel_blue = colors.Color(
70
+ name="steel_blue",
71
+ c50="#EBF3F8",
72
+ c100="#D3E5F0",
73
+ c200="#A8CCE1",
74
+ c300="#7DB3D2",
75
+ c400="#529AC3",
76
+ c500="#4682B4",
77
+ c600="#3E72A0",
78
+ c700="#36638C",
79
+ c800="#2E5378",
80
+ c900="#264364",
81
+ c950="#1E3450",
82
+ )
83
+
84
+ class SteelBlueTheme(Soft):
85
+ def __init__(
86
+ self,
87
+ *,
88
+ primary_hue: colors.Color | str = colors.gray,
89
+ secondary_hue: colors.Color | str = colors.steel_blue,
90
+ neutral_hue: colors.Color | str = colors.slate,
91
+ text_size: sizes.Size | str = sizes.text_lg,
92
+ font: fonts.Font | str | Iterable[fonts.Font | str] = (
93
+ fonts.GoogleFont("Outfit"), "Arial", "sans-serif",
94
+ ),
95
+ font_mono: fonts.Font | str | Iterable[fonts.Font | str] = (
96
+ fonts.GoogleFont("IBM Plex Mono"), "ui-monospace", "monospace",
97
+ ),
98
+ ):
99
+ super().__init__(
100
+ primary_hue=primary_hue,
101
+ secondary_hue=secondary_hue,
102
+ neutral_hue=neutral_hue,
103
+ text_size=text_size,
104
+ font=font,
105
+ font_mono=font_mono,
106
+ )
107
+ super().set(
108
+ background_fill_primary="*primary_50",
109
+ background_fill_primary_dark="*primary_900",
110
+ body_background_fill="linear-gradient(135deg, *primary_200, *primary_100)",
111
+ body_background_fill_dark="linear-gradient(135deg, *primary_900, *primary_800)",
112
+ button_primary_text_color="white",
113
+ button_primary_text_color_hover="white",
114
+ button_primary_background_fill="linear-gradient(90deg, *secondary_500, *secondary_600)",
115
+ button_primary_background_fill_hover="linear-gradient(90deg, *secondary_600, *secondary_700)",
116
+ button_primary_background_fill_dark="linear-gradient(90deg, *secondary_600, *secondary_700)",
117
+ button_primary_background_fill_hover_dark="linear-gradient(90deg, *secondary_500, *secondary_600)",
118
+ slider_color="*secondary_500",
119
+ slider_color_dark="*secondary_600",
120
+ block_title_text_weight="600",
121
+ block_border_width="3px",
122
+ block_shadow="*shadow_drop_lg",
123
+ button_primary_shadow="*shadow_drop_lg",
124
+ button_large_padding="11px",
125
+ color_accent_soft="*primary_100",
126
+ block_label_background_fill="*primary_200",
127
+ )
128
+
129
+ steel_blue_theme = SteelBlueTheme()
130
+
131
+ css = """
132
+ #main-title h1 {
133
+ font-size: 2.3em !important;
134
+ }
135
+ #output-title h2 {
136
+ font-size: 2.1em !important;
137
+ }
138
+ """
139
+
140
+ print("Determining device...")
141
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
142
+ print(f"✅ Using device: {device}")
143
+
144
+ print("Loading model and tokenizer...")
145
+ model_name = "strangervisionhf/deepseek-ocr-latest-transformers"
146
+ tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
147
+
148
+ model = AutoModel.from_pretrained(
149
+ model_name,
150
+ _attn_implementation="flash_attention_2",
151
+ trust_remote_code=True,
152
+ use_safetensors=True,
153
+ ).to(device).eval() # Move to device and set to eval mode
154
+
155
+ if device.type == 'cuda':
156
+ model = model.to(torch.bfloat16)
157
+
158
+ print("✅ Model loaded successfully to device and in eval mode.")
159
+
160
+ def find_result_image(path):
161
+ for filename in os.listdir(path):
162
+ if "grounding" in filename or "result" in filename:
163
+ try:
164
+ image_path = os.path.join(path, filename)
165
+ return Image.open(image_path)
166
+ except Exception as e:
167
+ print(f"Error opening result image {filename}: {e}")
168
+ return None
169
+
170
+ @spaces.GPU
171
+ def process_ocr_task(image, model_size, task_type, ref_text):
172
+ """
173
+ Processes an image with DeepSeek-OCR. The model is already on the correct device.
174
+ """
175
+ if image is None:
176
+ return "Please upload an image first.", None
177
+
178
+ print("✅ Model is already on the designated device.")
179
+
180
+ with tempfile.TemporaryDirectory() as output_path:
181
+ # Build the prompt
182
+ if task_type == "Free OCR":
183
+ prompt = "<image>\nFree OCR."
184
+ elif task_type == "Convert to Markdown":
185
+ prompt = "<image>\n<|grounding|>Convert the document to markdown."
186
+ elif task_type == "Parse Figure":
187
+ prompt = "<image>\nParse the figure."
188
+ elif task_type == "Locate Object by Reference":
189
+ if not ref_text or ref_text.strip() == "":
190
+ raise gr.Error("For the 'Locate' task, you must provide the reference text to find!")
191
+ prompt = f"<image>\nLocate <|ref|>{ref_text.strip()}<|/ref|> in the image."
192
+ else:
193
+ prompt = "<image>\nFree OCR."
194
+
195
+ temp_image_path = os.path.join(output_path, "temp_image.png")
196
+ image.save(temp_image_path)
197
+
198
+ size_configs = {
199
+ "Tiny": {"base_size": 512, "image_size": 512, "crop_mode": False},
200
+ "Small": {"base_size": 640, "image_size": 640, "crop_mode": False},
201
+ "Base": {"base_size": 1024, "image_size": 1024, "crop_mode": False},
202
+ "Large": {"base_size": 1280, "image_size": 1280, "crop_mode": False},
203
+ "Gundam (Recommended)": {"base_size": 1024, "image_size": 640, "crop_mode": True},
204
+ }
205
+ config = size_configs.get(model_size, size_configs["Gundam (Recommended)"])
206
+
207
+ print(f"🏃 Running inference with prompt: {prompt}")
208
+ text_result = model.infer(
209
+ tokenizer,
210
+ prompt=prompt,
211
+ image_file=temp_image_path,
212
+ output_path=output_path,
213
+ base_size=config["base_size"],
214
+ image_size=config["image_size"],
215
+ crop_mode=config["crop_mode"],
216
+ save_results=True,
217
+ test_compress=True,
218
+ eval_mode=True,
219
+ )
220
+
221
+ print(f"====\n📄 Text Result: {text_result}\n====")
222
+
223
+ result_image_pil = None
224
+ pattern = re.compile(r"<\|det\|>\[\[(\d+),\s*(\d+),\s*(\d+),\s*(\d+)\]\]<\|/det\|>")
225
+ matches = list(pattern.finditer(text_result))
226
+
227
+ if matches:
228
+ print(f"✅ Found {len(matches)} bounding box(es). Drawing on the original image.")
229
+ image_with_bboxes = image.copy()
230
+ draw = ImageDraw.Draw(image_with_bboxes)
231
+ w, h = image.size
232
+
233
+ for match in matches:
234
+ coords_norm = [int(c) for c in match.groups()]
235
+ x1_norm, y1_norm, x2_norm, y2_norm = coords_norm
236
+
237
+ x1 = int(x1_norm / 1000 * w)
238
+ y1 = int(y1_norm / 1000 * h)
239
+ x2 = int(x2_norm / 1000 * w)
240
+ y2 = int(y2_norm / 1000 * h)
241
+
242
+ draw.rectangle([x1, y1, x2, y2], outline="red", width=3)
243
+
244
+ result_image_pil = image_with_bboxes
245
+ else:
246
+ print("⚠️ No bounding box coordinates found in text result. Falling back to search for a result image file.")
247
+ result_image_pil = find_result_image(output_path)
248
+
249
+ return text_result, result_image_pil
250
+
251
+ with gr.Blocks(css=css, theme=steel_blue_theme) as demo:
252
+ gr.Markdown("# **DeepSeek OCR [exp]**", elem_id="main-title")
253
+
254
+
255
+ with gr.Row():
256
+ with gr.Column(scale=1):
257
+ image_input = gr.Image(type="pil", label="Upload Image", sources=["upload", "clipboard"])
258
+ model_size = gr.Dropdown(choices=["Tiny", "Small", "Base", "Large", "Gundam (Recommended)"], value="Large", label="Resolution Size")
259
+ task_type = gr.Dropdown(choices=["Free OCR", "Convert to Markdown", "Parse Figure", "Locate Object by Reference"], value="Convert to Markdown", label="Task Type")
260
+ ref_text_input = gr.Textbox(label="Reference Text (for Locate task)", placeholder="e.g., the teacher, 20-10, a red car...", visible=False)
261
+ submit_btn = gr.Button("Process Image", variant="primary")
262
+
263
+ with gr.Column(scale=2):
264
+ output_text = gr.Textbox(label="Output (OCR)", lines=8, show_copy_button=True)
265
+ output_image = gr.Image(label="Layout Detection (If Any)", type="pil")
266
+
267
+ with gr.Accordion("Note", open=False):
268
+ gr.Markdown("Inference using Huggingface transformers on NVIDIA GPUs. This app is running with transformers version 4.57.1 and torch version 2.6.0.")
269
+
270
+ def toggle_ref_text_visibility(task):
271
+ return gr.Textbox(visible=True) if task == "Locate Object by Reference" else gr.Textbox(visible=False)
272
+
273
+ task_type.change(fn=toggle_ref_text_visibility, inputs=task_type, outputs=ref_text_input)
274
+ submit_btn.click(fn=process_ocr_task, inputs=[image_input, model_size, task_type, ref_text_input], outputs=[output_text, output_image])
275
+
276
+ if __name__ == "__main__":
277
+ demo.queue(max_size=20).launch(share=True)
278
+ ```
279
+
280
+ ---
281
+
282
+ ## **Implementation Example**
283
+
284
+ ![Screenshot 2025-10-29 at 19-35-59 DeepSeek OCR Experimental - a Hugging Face Space by prithivMLmods](https://cdn-uploads.huggingface.co/production/uploads/65bb837dbfb878f46c77de4c/yOY1-MPP2qlhaC-_nVr3z.png)
285
+
286
+ ![Screenshot 2025-10-29 at 19-34-45 DeepSeek OCR Experimental - a Hugging Face Space by prithivMLmods](https://cdn-uploads.huggingface.co/production/uploads/65bb837dbfb878f46c77de4c/x0RvOH7ZfNXk1K1h4AjTX.png)