prithivMLmods commited on
Commit
e61a1ff
·
verified ·
1 Parent(s): e66f44f

Delete app.py

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