prithivMLmods commited on
Commit
5670384
·
verified ·
1 Parent(s): 3349ae3

Upload app(2).py

Browse files
Files changed (1) hide show
  1. app(2).py +352 -0
app(2).py ADDED
@@ -0,0 +1,352 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import spaces
2
+ import json
3
+ import math
4
+ import os
5
+ import traceback
6
+ from io import BytesIO
7
+ from typing import Any, Dict, List, Optional, Tuple
8
+ import re
9
+ import time
10
+ from threading import Thread
11
+ from io import BytesIO
12
+ import uuid
13
+ import tempfile
14
+
15
+ import gradio as gr
16
+ import requests
17
+ import torch
18
+ from PIL import Image
19
+ import fitz
20
+
21
+ from transformers import (
22
+ Qwen2_5_VLForConditionalGeneration,
23
+ Qwen2VLForConditionalGeneration,
24
+ AutoModelForCausalLM,
25
+ AutoModelForVision2Seq,
26
+ AutoModelForImageTextToText,
27
+ AutoModel,
28
+ AutoProcessor,
29
+ TextIteratorStreamer,
30
+ AutoTokenizer,
31
+ )
32
+
33
+ from transformers.image_utils import load_image
34
+
35
+ from reportlab.lib.pagesizes import A4
36
+ from reportlab.lib.styles import getSampleStyleSheet
37
+ from reportlab.platypus import SimpleDocTemplate, Image as RLImage, Paragraph, Spacer
38
+ from reportlab.lib.units import inch
39
+
40
+ # --- Constants and Model Setup ---
41
+ MAX_INPUT_TOKEN_LENGTH = 4096
42
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
43
+
44
+ print("CUDA_VISIBLE_DEVICES=", os.environ.get("CUDA_VISIBLE_DEVICES"))
45
+ print("torch.__version__ =", torch.__version__)
46
+ print("torch.version.cuda =", torch.version.cuda)
47
+ print("cuda available:", torch.cuda.is_available())
48
+ print("cuda device count:", torch.cuda.device_count())
49
+ if torch.cuda.is_available():
50
+ print("current device:", torch.cuda.current_device())
51
+ print("device name:", torch.cuda.get_device_name(torch.cuda.current_device()))
52
+
53
+ print("Using device:", device)
54
+
55
+ # --- Model Loading ---
56
+ MODEL_ID_M = "LiquidAI/LFM2-VL-450M"
57
+ processor_m = AutoProcessor.from_pretrained(MODEL_ID_M, trust_remote_code=True)
58
+ model_m = AutoModelForImageTextToText.from_pretrained(
59
+ MODEL_ID_M, trust_remote_code=True, torch_dtype=torch.float16
60
+ ).to(device).eval()
61
+
62
+ MODEL_ID_T = "LiquidAI/LFM2-VL-1.6B"
63
+ processor_t = AutoProcessor.from_pretrained(MODEL_ID_T, trust_remote_code=True)
64
+ model_t = AutoModelForImageTextToText.from_pretrained(
65
+ MODEL_ID_T, trust_remote_code=True, torch_dtype=torch.float16
66
+ ).to(device).eval()
67
+
68
+ MODEL_ID_C = "HuggingFaceTB/SmolVLM-Instruct-250M"
69
+ processor_c = AutoProcessor.from_pretrained(MODEL_ID_C, trust_remote_code=True)
70
+ model_c = AutoModelForVision2Seq.from_pretrained(
71
+ MODEL_ID_C, trust_remote_code=True, torch_dtype=torch.float16, _attn_implementation="flash_attention_2"
72
+ ).to(device).eval()
73
+
74
+ MODEL_ID_G = "echo840/MonkeyOCR-pro-1.2B"
75
+ SUBFOLDER = "Recognition"
76
+ processor_g = AutoProcessor.from_pretrained(
77
+ MODEL_ID_G, trust_remote_code=True, subfolder=SUBFOLDER
78
+ )
79
+ model_g = Qwen2_5_VLForConditionalGeneration.from_pretrained(
80
+ MODEL_ID_G, trust_remote_code=True, subfolder=SUBFOLDER, torch_dtype=torch.float16
81
+ ).to(device).eval()
82
+
83
+ MODEL_ID_I = "UCSC-VLAA/VLAA-Thinker-Qwen2VL-2B"
84
+ processor_i = AutoProcessor.from_pretrained(MODEL_ID_I, trust_remote_code=True)
85
+ model_i = Qwen2VLForConditionalGeneration.from_pretrained(
86
+ MODEL_ID_I, trust_remote_code=True, torch_dtype=torch.float16
87
+ ).to(device).eval()
88
+
89
+ MODEL_ID_A = "nanonets/Nanonets-OCR-s"
90
+ processor_a = AutoProcessor.from_pretrained(MODEL_ID_A, trust_remote_code=True)
91
+ model_a = Qwen2_5_VLForConditionalGeneration.from_pretrained(
92
+ MODEL_ID_A, trust_remote_code=True, torch_dtype=torch.float16
93
+ ).to(device).eval()
94
+
95
+ MODEL_ID_X = "prithivMLmods/Megalodon-OCR-Sync-0713"
96
+ processor_x = AutoProcessor.from_pretrained(MODEL_ID_X, trust_remote_code=True)
97
+ model_x = Qwen2_5_VLForConditionalGeneration.from_pretrained(
98
+ MODEL_ID_X, trust_remote_code=True, torch_dtype=torch.float16
99
+ ).to(device).eval()
100
+
101
+ MODEL_ID_Z = "Vchitect/ShotVL-3B"
102
+ processor_z = AutoProcessor.from_pretrained(MODEL_ID_Z, trust_remote_code=True)
103
+ model_z = Qwen2_5_VLForConditionalGeneration.from_pretrained(
104
+ MODEL_ID_Z, trust_remote_code=True, torch_dtype=torch.float16
105
+ ).to(device).eval()
106
+
107
+ # --- Moondream2 Model Loading ---
108
+ MODEL_ID_MD = "vikhyatk/moondream2"
109
+ REVISION_MD = "2025-06-21"
110
+ moondream = AutoModelForCausalLM.from_pretrained(
111
+ MODEL_ID_MD,
112
+ revision=REVISION_MD,
113
+ trust_remote_code=True,
114
+ torch_dtype=torch.float16,
115
+ device_map={"": "cuda"},
116
+ )
117
+ tokenizer_md = AutoTokenizer.from_pretrained(MODEL_ID_MD, revision=REVISION_MD)
118
+
119
+
120
+ # --- PDF Generation and Preview Utility Function ---
121
+ def generate_and_preview_pdf(image: Image.Image, text_content: str, font_size: int, line_spacing: float, alignment: str, image_size: str):
122
+ """
123
+ Generates a PDF, saves it, and then creates image previews of its pages.
124
+ Returns the path to the PDF and a list of paths to the preview images.
125
+ """
126
+ if image is None or not text_content or not text_content.strip():
127
+ raise gr.Error("Cannot generate PDF. Image or text content is missing.")
128
+
129
+ # --- 1. Generate the PDF ---
130
+ temp_dir = tempfile.gettempdir()
131
+ pdf_filename = os.path.join(temp_dir, f"output_{uuid.uuid4()}.pdf")
132
+ doc = SimpleDocTemplate(
133
+ pdf_filename,
134
+ pagesize=A4,
135
+ rightMargin=inch, leftMargin=inch,
136
+ topMargin=inch, bottomMargin=inch
137
+ )
138
+ styles = getSampleStyleSheet()
139
+ style_normal = styles["Normal"]
140
+ style_normal.fontSize = int(font_size)
141
+ style_normal.leading = int(font_size) * line_spacing
142
+ style_normal.alignment = {"Left": 0, "Center": 1, "Right": 2, "Justified": 4}[alignment]
143
+
144
+ story = []
145
+
146
+ img_buffer = BytesIO()
147
+ image.save(img_buffer, format='PNG')
148
+ img_buffer.seek(0)
149
+
150
+ page_width, _ = A4
151
+ available_width = page_width - 2 * inch
152
+ image_widths = {
153
+ "Small": available_width * 0.3,
154
+ "Medium": available_width * 0.6,
155
+ "Large": available_width * 0.9,
156
+ }
157
+ img_width = image_widths[image_size]
158
+ img = RLImage(img_buffer, width=img_width, height=image.height * (img_width / image.width))
159
+ story.append(img)
160
+ story.append(Spacer(1, 12))
161
+
162
+ cleaned_text = re.sub(r'#+\s*', '', text_content).replace("*", "")
163
+ text_paragraphs = cleaned_text.split('\n')
164
+
165
+ for para in text_paragraphs:
166
+ if para.strip():
167
+ story.append(Paragraph(para, style_normal))
168
+
169
+ doc.build(story)
170
+
171
+ # --- 2. Render PDF pages as images for preview ---
172
+ preview_images = []
173
+ try:
174
+ pdf_doc = fitz.open(pdf_filename)
175
+ for page_num in range(len(pdf_doc)):
176
+ page = pdf_doc.load_page(page_num)
177
+ pix = page.get_pixmap(dpi=150)
178
+ preview_img_path = os.path.join(temp_dir, f"preview_{uuid.uuid4()}_p{page_num}.png")
179
+ pix.save(preview_img_path)
180
+ preview_images.append(preview_img_path)
181
+ pdf_doc.close()
182
+ except Exception as e:
183
+ print(f"Error generating PDF preview: {e}")
184
+
185
+ return pdf_filename, preview_images
186
+
187
+
188
+ # --- Core Application Logic ---
189
+ @spaces.GPU
190
+ def process_document_stream(
191
+ model_name: str,
192
+ image: Image.Image,
193
+ prompt_input: str,
194
+ max_new_tokens: int,
195
+ temperature: float,
196
+ top_p: float,
197
+ top_k: int,
198
+ repetition_penalty: float
199
+ ):
200
+ """
201
+ Main generator function that handles model inference tasks with advanced generation parameters.
202
+ """
203
+ if image is None:
204
+ yield "Please upload an image.", ""
205
+ return
206
+ if not prompt_input or not prompt_input.strip():
207
+ yield "Please enter a prompt.", ""
208
+ return
209
+
210
+ if model_name == "Moondream2(vision)":
211
+ image_embeds = moondream.encode_image(image)
212
+ answer = moondream.answer_question(
213
+ image_embeds=image_embeds,
214
+ question=prompt_input,
215
+ tokenizer=tokenizer_md
216
+ )
217
+ yield answer, answer
218
+ return
219
+
220
+ if model_name == "LFM2-VL-450M(fast)": processor, model = processor_m, model_m
221
+ elif model_name == "LFM2-VL-1.6B(fast)": processor, model = processor_t, model_t
222
+ elif model_name == "ShotVL-3B(cinematic)": processor, model = processor_z, model_z
223
+ elif model_name == "SmolVLM-Instruct-250M(smol)": processor, model = processor_c, model_c
224
+ elif model_name == "MonkeyOCR-pro-1.2B(ocr)": processor, model = processor_g, model_g
225
+ elif model_name == "VLAA-Thinker-Qwen2VL-2B(reason)": processor, model = processor_i, model_i
226
+ elif model_name == "Nanonets-OCR-s(ocr)": processor, model = processor_a, model_a
227
+ elif model_name == "Megalodon-OCR-Sync-0713(ocr)": processor, model = processor_x, model_x
228
+ else:
229
+ yield "Invalid model selected.", ""
230
+ return
231
+
232
+ messages = [{"role": "user", "content": [{"type": "image", "image": image}, {"type": "text", "text": prompt_input}]}]
233
+ prompt_full = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
234
+ inputs = processor(text=[prompt_full], images=[image], return_tensors="pt", padding=True, truncation=True, max_length=MAX_INPUT_TOKEN_LENGTH).to(device)
235
+ streamer = TextIteratorStreamer(processor, skip_prompt=True, skip_special_tokens=True)
236
+
237
+ generation_kwargs = {
238
+ **inputs,
239
+ "streamer": streamer,
240
+ "max_new_tokens": max_new_tokens,
241
+ "temperature": temperature,
242
+ "top_p": top_p,
243
+ "top_k": top_k,
244
+ "repetition_penalty": repetition_penalty,
245
+ "do_sample": True
246
+ }
247
+
248
+ thread = Thread(target=model.generate, kwargs=generation_kwargs)
249
+ thread.start()
250
+
251
+ buffer = ""
252
+ for new_text in streamer:
253
+ buffer += new_text
254
+ buffer = buffer.replace("<|im_end|>", "")
255
+ time.sleep(0.01)
256
+ yield buffer , buffer
257
+
258
+ yield buffer, buffer
259
+
260
+
261
+ # --- Gradio UI Definition ---
262
+ def create_gradio_interface():
263
+ """Builds and returns the Gradio web interface."""
264
+ css = """
265
+ .main-container { max-width: 1400px; margin: 0 auto; }
266
+ .process-button { border: none !important; color: white !important; font-weight: bold !important; background-color: blue !important;}
267
+ .process-button:hover { background-color: darkblue !important; transform: translateY(-2px) !important; box-shadow: 0 4px 8px rgba(0,0,0,0.2) !important; }
268
+ #gallery { min-height: 400px; }
269
+ """
270
+ with gr.Blocks(theme="bethecloud/storj_theme", css=css) as demo:
271
+ gr.HTML("""
272
+ <div class="title" style="text-align: center">
273
+ <h1>Tiny VLMs Lab🧪</h1>
274
+ <p style="font-size: 1.1em; color: #6b7280; margin-bottom: 0.6em;">
275
+ Advanced Vision-Language Model for Image Content and Layout Extraction
276
+ </p>
277
+ </div>
278
+ """)
279
+
280
+ with gr.Row():
281
+ # Left Column (Inputs)
282
+ with gr.Column(scale=1):
283
+ model_choice = gr.Dropdown(
284
+ choices=["LFM2-VL-450M(fast)", "LFM2-VL-1.6B(fast)", "SmolVLM-Instruct-250M(smol)", "Moondream2(vision)", "ShotVL-3B(cinematic)", "Megalodon-OCR-Sync-0713(ocr)",
285
+ "VLAA-Thinker-Qwen2VL-2B(reason)", "MonkeyOCR-pro-1.2B(ocr)", "Nanonets-OCR-s(ocr)"],
286
+ label="Select Model", value= "LFM2-VL-450M(fast)"
287
+ )
288
+ prompt_input = gr.Textbox(label="Query Input", placeholder="✦︎ Enter your query", value="Describe the image!")
289
+ image_input = gr.Image(label="Upload Image", type="pil", sources=['upload'])
290
+
291
+ with gr.Accordion("Advanced Settings", open=False):
292
+ max_new_tokens = gr.Slider(minimum=512, maximum=8192, value=4096, step=256, label="Max New Tokens")
293
+ temperature = gr.Slider(label="Temperature", minimum=0.1, maximum=4.0, step=0.1, value=0.6)
294
+ top_p = gr.Slider(label="Top-p (nucleus sampling)", minimum=0.05, maximum=1.0, step=0.05, value=0.9)
295
+ top_k = gr.Slider(label="Top-k", minimum=1, maximum=1000, step=1, value=50)
296
+ repetition_penalty = gr.Slider(label="Repetition penalty", minimum=1.0, maximum=2.0, step=0.05, value=1.2)
297
+
298
+ gr.Markdown("### PDF Export Settings")
299
+ font_size = gr.Dropdown(choices=["8", "10", "12", "14", "16", "18"], value="12", label="Font Size")
300
+ line_spacing = gr.Dropdown(choices=[1.0, 1.15, 1.5, 2.0], value=1.15, label="Line Spacing")
301
+ alignment = gr.Dropdown(choices=["Left", "Center", "Right", "Justified"], value="Justified", label="Text Alignment")
302
+ image_size = gr.Dropdown(choices=["Small", "Medium", "Large"], value="Medium", label="Image Size in PDF")
303
+
304
+ process_btn = gr.Button("🚀 Process Image", variant="primary", elem_classes=["process-button"], size="lg")
305
+ clear_btn = gr.Button("🗑️ Clear All", variant="secondary")
306
+
307
+ # Right Column (Outputs)
308
+ with gr.Column(scale=2):
309
+ with gr.Tabs() as tabs:
310
+ with gr.Tab("📝 Extracted Content"):
311
+ raw_output_stream = gr.Textbox(label="Raw Model Output Stream", interactive=False, lines=15, show_copy_button=True)
312
+ with gr.Row():
313
+ examples = gr.Examples(
314
+ examples=["examples/1.png", "examples/2.png", "examples/3.png", "examples/4.png", "examples/5.png"],
315
+ inputs=image_input, label="Examples"
316
+ )
317
+ gr.Markdown("[Report-Bug💻](https://huggingface.co/spaces/prithivMLmods/OCR-Comparator/discussions)")
318
+
319
+ with gr.Tab("📰 README.md"):
320
+ with gr.Accordion("(Result.md)", open=True):
321
+ markdown_output = gr.Markdown()
322
+
323
+ with gr.Tab("📋 PDF Preview"):
324
+ generate_pdf_btn = gr.Button("📄 Generate PDF & Render", variant="primary")
325
+ pdf_output_file = gr.File(label="Download Generated PDF", interactive=False)
326
+ pdf_preview_gallery = gr.Gallery(label="PDF Page Preview", show_label=True, elem_id="gallery", columns=2, object_fit="contain", height="auto")
327
+
328
+ # Event Handlers
329
+ def clear_all_outputs():
330
+ return None, "", "Raw output will appear here.", "", None, None
331
+
332
+ process_btn.click(
333
+ fn=process_document_stream,
334
+ inputs=[model_choice, image_input, prompt_input, max_new_tokens, temperature, top_p, top_k, repetition_penalty],
335
+ outputs=[raw_output_stream, markdown_output]
336
+ )
337
+
338
+ generate_pdf_btn.click(
339
+ fn=generate_and_preview_pdf,
340
+ inputs=[image_input, raw_output_stream, font_size, line_spacing, alignment, image_size],
341
+ outputs=[pdf_output_file, pdf_preview_gallery]
342
+ )
343
+
344
+ clear_btn.click(
345
+ clear_all_outputs,
346
+ outputs=[image_input, prompt_input, raw_output_stream, markdown_output, pdf_output_file, pdf_preview_gallery]
347
+ )
348
+ return demo
349
+
350
+ if __name__ == "__main__":
351
+ demo = create_gradio_interface()
352
+ demo.queue(max_size=50).launch(share=True, ssr_mode=False, show_error=True)