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

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -404
app.py DELETED
@@ -1,404 +0,0 @@
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="auto",
116
- )
117
- tokenizer_md = AutoTokenizer.from_pretrained(MODEL_ID_MD, revision=REVISION_MD)
118
-
119
- # --- SmolVLM2 Model Loading ---
120
- MODEL_ID_S2 = "HuggingFaceTB/SmolVLM2-2.2B-Instruct"
121
- processor_s2 = AutoProcessor.from_pretrained(MODEL_ID_S2, trust_remote_code=True)
122
- model_s2 = AutoModelForImageTextToText.from_pretrained(
123
- MODEL_ID_S2,
124
- torch_dtype=torch.float16,
125
- trust_remote_code=True,
126
- device_map="auto"
127
- ).eval()
128
-
129
-
130
- # --- PDF Generation and Preview Utility Function ---
131
- def generate_and_preview_pdf(image: Image.Image, text_content: str, font_size: int, line_spacing: float, alignment: str, image_size: str):
132
- """
133
- Generates a PDF, saves it, and then creates image previews of its pages.
134
- Returns the path to the PDF and a list of paths to the preview images.
135
- """
136
- if image is None or not text_content or not text_content.strip():
137
- raise gr.Error("Cannot generate PDF. Image or text content is missing.")
138
-
139
- # --- 1. Generate the PDF ---
140
- temp_dir = tempfile.gettempdir()
141
- pdf_filename = os.path.join(temp_dir, f"output_{uuid.uuid4()}.pdf")
142
- doc = SimpleDocTemplate(
143
- pdf_filename,
144
- pagesize=A4,
145
- rightMargin=inch, leftMargin=inch,
146
- topMargin=inch, bottomMargin=inch
147
- )
148
- styles = getSampleStyleSheet()
149
- style_normal = styles["Normal"]
150
- style_normal.fontSize = int(font_size)
151
- style_normal.leading = int(font_size) * line_spacing
152
- style_normal.alignment = {"Left": 0, "Center": 1, "Right": 2, "Justified": 4}[alignment]
153
-
154
- story = []
155
-
156
- img_buffer = BytesIO()
157
- image.save(img_buffer, format='PNG')
158
- img_buffer.seek(0)
159
-
160
- page_width, _ = A4
161
- available_width = page_width - 2 * inch
162
- image_widths = {
163
- "Small": available_width * 0.3,
164
- "Medium": available_width * 0.6,
165
- "Large": available_width * 0.9,
166
- }
167
- img_width = image_widths[image_size]
168
- img = RLImage(img_buffer, width=img_width, height=image.height * (img_width / image.width))
169
- story.append(img)
170
- story.append(Spacer(1, 12))
171
-
172
- cleaned_text = re.sub(r'#+\s*', '', text_content).replace("*", "")
173
- text_paragraphs = cleaned_text.split('\n')
174
-
175
- for para in text_paragraphs:
176
- if para.strip():
177
- story.append(Paragraph(para, style_normal))
178
-
179
- doc.build(story)
180
-
181
- # --- 2. Render PDF pages as images for preview ---
182
- preview_images = []
183
- try:
184
- pdf_doc = fitz.open(pdf_filename)
185
- for page_num in range(len(pdf_doc)):
186
- page = pdf_doc.load_page(page_num)
187
- pix = page.get_pixmap(dpi=150)
188
- preview_img_path = os.path.join(temp_dir, f"preview_{uuid.uuid4()}_p{page_num}.png")
189
- pix.save(preview_img_path)
190
- preview_images.append(preview_img_path)
191
- pdf_doc.close()
192
- except Exception as e:
193
- print(f"Error generating PDF preview: {e}")
194
-
195
- return pdf_filename, preview_images
196
-
197
-
198
- # --- Core Application Logic ---
199
- @spaces.GPU
200
- def process_document_stream(
201
- model_name: str,
202
- image: Image.Image,
203
- prompt_input: str,
204
- max_new_tokens: int,
205
- temperature: float,
206
- top_p: float,
207
- top_k: int,
208
- repetition_penalty: float
209
- ):
210
- """
211
- Main generator function that handles model inference tasks with advanced generation parameters.
212
- """
213
- if image is None:
214
- yield "Please upload an image.", ""
215
- return
216
- if not prompt_input or not prompt_input.strip():
217
- yield "Please enter a prompt.", ""
218
- return
219
-
220
- if model_name == "Moondream2(vision)":
221
- image_embeds = moondream.encode_image(image)
222
- answer = moondream.answer_question(
223
- image_embeds=image_embeds,
224
- question=prompt_input,
225
- tokenizer=tokenizer_md,
226
- max_new_tokens=max_new_tokens,
227
- temperature=temperature,
228
- top_p=top_p,
229
- top_k=top_k,
230
- )
231
- yield answer, answer
232
- return
233
-
234
- elif model_name == "SmolVLM2-2.2B-Instruct(smol)":
235
- processor, model = processor_s2, model_s2
236
- messages = [{
237
- "role": "user",
238
- "content": [
239
- {"type": "text", "text": prompt_input},
240
- {"type": "image"},
241
- ]
242
- }]
243
- inputs = processor.apply_chat_template(
244
- messages,
245
- images=[image],
246
- add_generation_prompt=True,
247
- tokenize=True,
248
- return_dict=True,
249
- return_tensors="pt",
250
- ).to(model.device)
251
-
252
- # Convert float32 tensors to float16 if necessary
253
- for k, v in inputs.items():
254
- if v.dtype == torch.float32:
255
- inputs[k] = v.to(torch.float16)
256
-
257
- generated_ids = model.generate(
258
- **inputs,
259
- do_sample=True,
260
- max_new_tokens=max_new_tokens,
261
- temperature=temperature,
262
- top_p=top_p,
263
- repetition_penalty=repetition_penalty,
264
- )
265
- generated_texts = processor.batch_decode(generated_ids, skip_special_tokens=True)
266
- final_output = generated_texts[0].split("Assistant:")[-1].strip()
267
- yield final_output, final_output
268
- return
269
-
270
- # Assign processor and model for other models
271
- if model_name == "LFM2-VL-450M(fast)": processor, model = processor_m, model_m
272
- elif model_name == "LFM2-VL-1.6B(fast)": processor, model = processor_t, model_t
273
- elif model_name == "ShotVL-3B(cinematic)": processor, model = processor_z, model_z
274
- elif model_name == "SmolVLM-Instruct-250M(smol)": processor, model = processor_c, model_c
275
- elif model_name == "MonkeyOCR-pro-1.2B(ocr)": processor, model = processor_g, model_g
276
- elif model_name == "VLAA-Thinker-Qwen2VL-2B(reason)": processor, model = processor_i, model_i
277
- elif model_name == "Nanonets-OCR-s(ocr)": processor, model = processor_a, model_a
278
- elif model_name == "Megalodon-OCR-Sync-0713(ocr)": processor, model = processor_x, model_x
279
- else:
280
- yield "Invalid model selected.", ""
281
- return
282
-
283
- # Common streaming logic for the rest of the models
284
- messages = [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": prompt_input}]}]
285
- prompt_full = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
286
- inputs = processor(text=[prompt_full], images=[image], return_tensors="pt", padding=True, truncation=True, max_length=MAX_INPUT_TOKEN_LENGTH).to(device)
287
- streamer = TextIteratorStreamer(processor, skip_prompt=True, skip_special_tokens=True)
288
-
289
- generation_kwargs = {
290
- **inputs,
291
- "streamer": streamer,
292
- "max_new_tokens": max_new_tokens,
293
- "temperature": temperature,
294
- "top_p": top_p,
295
- "top_k": top_k,
296
- "repetition_penalty": repetition_penalty,
297
- "do_sample": True
298
- }
299
-
300
- thread = Thread(target=model.generate, kwargs=generation_kwargs)
301
- thread.start()
302
-
303
- buffer = ""
304
- for new_text in streamer:
305
- buffer += new_text
306
- buffer = buffer.replace("<|im_end|>", "")
307
- time.sleep(0.01)
308
- yield buffer , buffer
309
-
310
- yield buffer, buffer
311
-
312
-
313
- # --- Gradio UI Definition ---
314
- def create_gradio_interface():
315
- """Builds and returns the Gradio web interface."""
316
- css = """
317
- .main-container { max-width: 1400px; margin: 0 auto; }
318
- .process-button { border: none !important; color: white !important; font-weight: bold !important; background-color: blue !important;}
319
- .process-button:hover { background-color: darkblue !important; transform: translateY(-2px) !important; box-shadow: 0 4px 8px rgba(0,0,0,0.2) !important; }
320
- #gallery { min-height: 400px; }
321
- """
322
- with gr.Blocks(theme="bethecloud/storj_theme", css=css) as demo:
323
- gr.HTML("""
324
- <div class="title" style="text-align: center">
325
- <h1>Tiny VLMs Lab🧪</h1>
326
- <p style="font-size: 1.1em; color: #6b7280; margin-bottom: 0.6em;">
327
- Advanced Vision-Language Model for Image Content and Layout Extraction
328
- </p>
329
- </div>
330
- """)
331
-
332
- with gr.Row():
333
- # Left Column (Inputs)
334
- with gr.Column(scale=1):
335
- model_choice = gr.Dropdown(
336
- choices=["SmolVLM2-2.2B-Instruct(smol)", "LFM2-VL-450M(fast)", "LFM2-VL-1.6B(fast)", "SmolVLM-Instruct-250M(smol)", "Moondream2(vision)", "ShotVL-3B(cinematic)", "Megalodon-OCR-Sync-0713(ocr)",
337
- "VLAA-Thinker-Qwen2VL-2B(reason)", "MonkeyOCR-pro-1.2B(ocr)", "Nanonets-OCR-s(ocr)"],
338
- label="Select Model", value= "SmolVLM2-2.2B-Instruct(smol)"
339
- )
340
- prompt_input = gr.Textbox(label="Query Input", placeholder="✦︎ Enter your query", value="Describe the image!")
341
- image_input = gr.Image(label="Upload Image", type="pil", sources=['upload'])
342
-
343
- with gr.Accordion("Advanced Settings", open=False):
344
- max_new_tokens = gr.Slider(minimum=512, maximum=8192, value=4096, step=256, label="Max New Tokens")
345
- temperature = gr.Slider(label="Temperature", minimum=0.1, maximum=4.0, step=0.1, value=0.6)
346
- top_p = gr.Slider(label="Top-p (nucleus sampling)", minimum=0.05, maximum=1.0, step=0.05, value=0.9)
347
- top_k = gr.Slider(label="Top-k", minimum=1, maximum=1000, step=1, value=50)
348
- repetition_penalty = gr.Slider(label="Repetition penalty", minimum=1.0, maximum=2.0, step=0.05, value=1.2)
349
-
350
- gr.Markdown("### PDF Export Settings")
351
- font_size = gr.Dropdown(choices=["8", "10", "12", "14", "16", "18"], value="12", label="Font Size")
352
- line_spacing = gr.Dropdown(choices=[1.0, 1.15, 1.5, 2.0], value=1.15, label="Line Spacing")
353
- alignment = gr.Dropdown(choices=["Left", "Center", "Right", "Justified"], value="Justified", label="Text Alignment")
354
- image_size = gr.Dropdown(choices=["Small", "Medium", "Large"], value="Medium", label="Image Size in PDF")
355
-
356
- process_btn = gr.Button("🚀 Process Image", variant="primary", elem_classes=["process-button"], size="lg")
357
- clear_btn = gr.Button("🗑️ Clear All", variant="secondary")
358
-
359
- # Right Column (Outputs)
360
- with gr.Column(scale=2):
361
- with gr.Tabs() as tabs:
362
- with gr.Tab("📝 Extracted Content"):
363
- raw_output_stream = gr.Textbox(label="Raw Model Output Stream", interactive=False, lines=15, show_copy_button=True)
364
- with gr.Row():
365
- examples = gr.Examples(
366
- examples=["examples/1.png", "examples/2.png", "examples/3.png", "examples/4.png", "examples/5.png"],
367
- inputs=image_input, label="Examples"
368
- )
369
- gr.Markdown("[Report-Bug💻](https://huggingface.co/spaces/prithivMLmods/OCR-Comparator/discussions)")
370
-
371
- with gr.Tab("📰 README.md"):
372
- with gr.Accordion("(Result.md)", open=True):
373
- markdown_output = gr.Markdown()
374
-
375
- with gr.Tab("📋 PDF Preview"):
376
- generate_pdf_btn = gr.Button("📄 Generate PDF & Render", variant="primary")
377
- pdf_output_file = gr.File(label="Download Generated PDF", interactive=False)
378
- pdf_preview_gallery = gr.Gallery(label="PDF Page Preview", show_label=True, elem_id="gallery", columns=2, object_fit="contain", height="auto")
379
-
380
- # Event Handlers
381
- def clear_all_outputs():
382
- return None, "", "Raw output will appear here.", "", None, None
383
-
384
- process_btn.click(
385
- fn=process_document_stream,
386
- inputs=[model_choice, image_input, prompt_input, max_new_tokens, temperature, top_p, top_k, repetition_penalty],
387
- outputs=[raw_output_stream, markdown_output]
388
- )
389
-
390
- generate_pdf_btn.click(
391
- fn=generate_and_preview_pdf,
392
- inputs=[image_input, raw_output_stream, font_size, line_spacing, alignment, image_size],
393
- outputs=[pdf_output_file, pdf_preview_gallery]
394
- )
395
-
396
- clear_btn.click(
397
- clear_all_outputs,
398
- outputs=[image_input, prompt_input, raw_output_stream, markdown_output, pdf_output_file, pdf_preview_gallery]
399
- )
400
- return demo
401
-
402
- if __name__ == "__main__":
403
- demo = create_gradio_interface()
404
- demo.queue(max_size=50).launch(share=True, ssr_mode=False, show_error=True)