prithivMLmods commited on
Commit
cc1c84d
Β·
verified Β·
1 Parent(s): ec1722d
Files changed (1) hide show
  1. app.py +328 -0
app.py ADDED
@@ -0,0 +1,328 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ from typing import Iterable, Optional, Tuple, Dict, Any, List
4
+ import time
5
+ import spaces
6
+ import gradio as gr
7
+ from io import BytesIO
8
+ from PIL import Image
9
+ from loguru import logger
10
+ from pathlib import Path
11
+ import torch
12
+ from transformers import AutoProcessor, Qwen2_5_VLForConditionalGeneration
13
+ import fitz # PyMuPDF
14
+ import html2text
15
+ import markdown
16
+ import tempfile
17
+
18
+ from gradio.themes import Soft
19
+ from gradio.themes.utils import colors, fonts, sizes
20
+
21
+ # --- Theme and CSS Definition ---
22
+
23
+ colors.steel_blue = colors.Color(
24
+ name="steel_blue",
25
+ c50="#EBF3F8", c100="#D3E5F0", c200="#A8CCE1", c300="#7DB3D2",
26
+ c400="#529AC3", c500="#4682B4", c600="#3E72A0", c700="#36638C",
27
+ c800="#2E5378", c900="#264364", c950="#1E3450",
28
+ )
29
+
30
+ class SteelBlueTheme(Soft):
31
+ def __init__(
32
+ self,
33
+ *,
34
+ primary_hue: colors.Color | str = colors.gray,
35
+ secondary_hue: colors.Color | str = colors.steel_blue,
36
+ neutral_hue: colors.Color | str = colors.slate,
37
+ text_size: sizes.Size | str = sizes.text_lg,
38
+ font: fonts.Font | str | Iterable[fonts.Font | str] = (
39
+ fonts.GoogleFont("Outfit"), "Arial", "sans-serif",
40
+ ),
41
+ font_mono: fonts.Font | str | Iterable[fonts.Font | str] = (
42
+ fonts.GoogleFont("IBM Plex Mono"), "ui-monospace", "monospace",
43
+ ),
44
+ ):
45
+ super().__init__(
46
+ primary_hue=primary_hue, secondary_hue=secondary_hue, neutral_hue=neutral_hue,
47
+ text_size=text_size, font=font, font_mono=font_mono,
48
+ )
49
+ super().set(
50
+ background_fill_primary="*primary_50",
51
+ background_fill_primary_dark="*primary_900",
52
+ body_background_fill="linear-gradient(135deg, *primary_200, *primary_100)",
53
+ body_background_fill_dark="linear-gradient(135deg, *primary_900, *primary_800)",
54
+ button_primary_text_color="white",
55
+ button_primary_text_color_hover="white",
56
+ button_primary_background_fill="linear-gradient(90deg, *secondary_500, *secondary_600)",
57
+ button_primary_background_fill_hover="linear-gradient(90deg, *secondary_600, *secondary_700)",
58
+ button_primary_background_fill_dark="linear-gradient(90deg, *secondary_600, *secondary_700)",
59
+ button_primary_background_fill_hover_dark="linear-gradient(90deg, *secondary_500, *secondary_600)",
60
+ slider_color="*secondary_500",
61
+ slider_color_dark="*secondary_600",
62
+ block_title_text_weight="600",
63
+ block_border_width="3px",
64
+ block_shadow="*shadow_drop_lg",
65
+ button_primary_shadow="*shadow_drop_lg",
66
+ button_large_padding="11px",
67
+ color_accent_soft="*primary_100",
68
+ block_label_background_fill="*primary_200",
69
+ )
70
+
71
+ steel_blue_theme = SteelBlueTheme()
72
+
73
+ # --- Model and App Logic ---
74
+
75
+ pdf_suffixes = [".pdf"]
76
+ image_suffixes = [".png", ".jpeg", ".jpg"]
77
+ device = "cuda" if torch.cuda.is_available() else "cpu"
78
+
79
+ logger.info(f"Using device: {device}")
80
+
81
+ # Model 1: Logics-Parsing
82
+ MODEL_ID_1 = "Logics-MLLM/Logics-Parsing"
83
+ logger.info(f"Loading model 1: {MODEL_ID_1}")
84
+ processor_1 = AutoProcessor.from_pretrained(MODEL_ID_1, trust_remote_code=True)
85
+ model_1 = Qwen2_5_VLForConditionalGeneration.from_pretrained(
86
+ MODEL_ID_1,
87
+ trust_remote_code=True,
88
+ torch_dtype=torch.float16 if device == "cuda" else torch.float32
89
+ ).to(device).eval()
90
+ logger.info(f"Model '{MODEL_ID_1}' loaded successfully.")
91
+
92
+ # Model 2: Gliese-OCR-7B-Post1.0
93
+ MODEL_ID_2 = "prithivMLmods/Gliese-OCR-7B-Post1.0"
94
+ logger.info(f"Loading model 2: {MODEL_ID_2}")
95
+ processor_2 = AutoProcessor.from_pretrained(MODEL_ID_2, trust_remote_code=True)
96
+ model_2 = Qwen2_5_VLForConditionalGeneration.from_pretrained(
97
+ MODEL_ID_2,
98
+ trust_remote_code=True,
99
+ torch_dtype=torch.float16 if device == "cuda" else torch.float32
100
+ ).to(device).eval()
101
+ logger.info(f"Model '{MODEL_ID_2}' loaded successfully.")
102
+
103
+ # Model 3: olmOCR-7B-0825
104
+ MODEL_ID_3 = "allenai/olmOCR-7B-0825"
105
+ logger.info(f"Loading model 3: {MODEL_ID_3}")
106
+ processor_3 = AutoProcessor.from_pretrained(MODEL_ID_3, trust_remote_code=True)
107
+ model_3 = Qwen2_5_VLForConditionalGeneration.from_pretrained(
108
+ MODEL_ID_3,
109
+ trust_remote_code=True,
110
+ torch_dtype=torch.float16 if device == "cuda" else torch.float32
111
+ ).to(device).eval()
112
+ logger.info(f"Model '{MODEL_ID_3}' loaded successfully.")
113
+
114
+ @spaces.GPU
115
+ def parse_page(image: Image.Image, model_name: str) -> str:
116
+ if model_name == "Logics-Parsing":
117
+ current_processor, current_model = processor_1, model_1
118
+ elif model_name == "Gliese-OCR-7B-Post1.0":
119
+ current_processor, current_model = processor_2, model_2
120
+ elif model_name == "olmOCR-7B-0825":
121
+ current_processor, current_model = processor_3, model_3
122
+ else:
123
+ raise ValueError(f"Unknown model choice: {model_name}")
124
+
125
+ # Standard Qwen2-VL format
126
+ messages = [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "Parse this document page into a clean, structured HTML representation. Preserve the logical structure with appropriate tags for content blocks such as paragraphs (<p>), headings (<h1>-<h6>), tables (<table>), figures (<figure>), formulas (<formula>), and others. Include category tags, and filter out irrelevant elements like headers and footers."}]}]
127
+
128
+ prompt_full = current_processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
129
+ inputs = current_processor(text=prompt_full, images=[image.convert("RGB")], return_tensors="pt").to(device)
130
+
131
+ with torch.no_grad():
132
+ generated_ids = current_model.generate(**inputs, max_new_tokens=2048, do_sample=False)
133
+
134
+ generated_ids = generated_ids[:, inputs['input_ids'].shape[1]:]
135
+ output_text = current_processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
136
+ return output_text
137
+
138
+ def convert_file_to_images(file_path: str, dpi: int = 200) -> List[Image.Image]:
139
+ images = []
140
+ file_ext = Path(file_path).suffix.lower()
141
+
142
+ if file_ext in image_suffixes:
143
+ images.append(Image.open(file_path).convert("RGB"))
144
+ return images
145
+
146
+ if file_ext not in pdf_suffixes:
147
+ raise ValueError(f"Unsupported file type: {file_ext}")
148
+
149
+ try:
150
+ pdf_document = fitz.open(file_path)
151
+ zoom = dpi / 72.0
152
+ mat = fitz.Matrix(zoom, zoom)
153
+ for page_num in range(len(pdf_document)):
154
+ page = pdf_document.load_page(page_num)
155
+ pix = page.get_pixmap(matrix=mat)
156
+ img_data = pix.tobytes("png")
157
+ images.append(Image.open(BytesIO(img_data)).convert("RGB"))
158
+ pdf_document.close()
159
+ except Exception as e:
160
+ logger.error(f"Failed to convert PDF using PyMuPDF: {e}")
161
+ raise
162
+ return images
163
+
164
+ def get_initial_state() -> Dict[str, Any]:
165
+ return {"pages": [], "total_pages": 0, "current_page_index": 0, "page_results": []}
166
+
167
+ def load_and_preview_file(file_path: Optional[str]) -> Tuple[Optional[Image.Image], str, Dict[str, Any]]:
168
+ state = get_initial_state()
169
+ if not file_path:
170
+ return None, '<div class="page-info">No file loaded</div>', state
171
+
172
+ try:
173
+ pages = convert_file_to_images(file_path)
174
+ if not pages:
175
+ return None, '<div class="page-info">Could not load file</div>', state
176
+
177
+ state["pages"] = pages
178
+ state["total_pages"] = len(pages)
179
+ page_info_html = f'<div class="page-info">Page 1 / {state["total_pages"]}</div>'
180
+ return pages[0], page_info_html, state
181
+ except Exception as e:
182
+ logger.error(f"Failed to load and preview file: {e}")
183
+ return None, '<div class="page-info">Failed to load preview</div>', state
184
+
185
+ async def process_all_pages(state: Dict[str, Any], model_choice: str, progress=gr.Progress(track_tqdm=True)):
186
+ if not state or not state["pages"]:
187
+ error_msg = "<h3>Please upload a file first.</h3>"
188
+ return error_msg, "", "", None, "Error: No file to process", state
189
+
190
+ logger.info(f'Processing {state["total_pages"]} pages with model: {model_choice}')
191
+ start_time = time.time()
192
+
193
+ try:
194
+ page_results = []
195
+ for i, page_img in progress.tqdm(enumerate(state["pages"]), desc="Processing Pages"):
196
+ html_result = parse_page(page_img, model_choice)
197
+ page_results.append({'raw_html': html_result})
198
+
199
+ state["page_results"] = page_results
200
+
201
+ full_html_content = "\n\n".join([f'<!-- Page {i+1} -->\n{res["raw_html"]}' for i, res in enumerate(page_results)])
202
+ full_markdown = html2text.html2text(full_html_content)
203
+ with tempfile.NamedTemporaryFile(mode='w', suffix='.md', delete=False, encoding='utf-8') as f:
204
+ f.write(full_markdown)
205
+ md_path = f.name
206
+
207
+ parsing_time = time.time() - start_time
208
+ cost_time_str = f'Total processing time: {parsing_time:.2f}s'
209
+
210
+ current_page_results = get_page_outputs(state)
211
+
212
+ return *current_page_results, md_path, cost_time_str, state
213
+
214
+ except Exception as e:
215
+ logger.error(f"Parsing failed: {e}", exc_info=True)
216
+ error_html = f"<h3>An error occurred during processing:</h3><p>{str(e)}</p>"
217
+ return error_html, "", "", None, f"Error: {str(e)}", state
218
+
219
+ def navigate_page(direction: str, state: Dict[str, Any]):
220
+ if not state or not state["pages"]:
221
+ return None, '<div class="page-info">No file loaded</div>', *get_page_outputs(state), state
222
+
223
+ current_index = state["current_page_index"]
224
+ total_pages = state["total_pages"]
225
+
226
+ if direction == "prev":
227
+ new_index = max(0, current_index - 1)
228
+ elif direction == "next":
229
+ new_index = min(total_pages - 1, current_index + 1)
230
+ else:
231
+ new_index = current_index
232
+
233
+ state["current_page_index"] = new_index
234
+
235
+ image_preview = state["pages"][new_index]
236
+ page_info_html = f'<div class="page-info">Page {new_index + 1} / {total_pages}</div>'
237
+
238
+ page_outputs = get_page_outputs(state)
239
+
240
+ return image_preview, page_info_html, *page_outputs, state
241
+
242
+ def get_page_outputs(state: Dict[str, Any]) -> Tuple[str, str, str]:
243
+ if not state or not state.get("page_results"):
244
+ return "<h3>Process the document to see results.</h3>", "", ""
245
+
246
+ index = state["current_page_index"]
247
+ if index >= len(state["page_results"]):
248
+ return "<h3>Result not available for this page.</h3>", "", ""
249
+
250
+ result = state["page_results"][index]
251
+ raw_html = result['raw_html']
252
+
253
+ md_source = html2text.html2text(raw_html)
254
+ md_render = markdown.markdown(md_source, extensions=['fenced_code', 'tables'])
255
+
256
+ return md_render, md_source, raw_html
257
+
258
+ def clear_all():
259
+ return None, None, "<h3>Results will be displayed here after processing.</h3>", "", "", None, "", '<div class="page-info">No file loaded</div>', get_initial_state()
260
+
261
+ css = """
262
+ .main-container { max-width: 1400px; margin: 0 auto; }
263
+ .header-text { text-align: center; margin-bottom: 20px; }
264
+ .page-info { text-align: center; padding: 8px 16px; font-weight: bold; margin: 10px 0; }
265
+ """
266
+
267
+ with gr.Blocks() as demo:
268
+ app_state = gr.State(value=get_initial_state())
269
+
270
+ gr.HTML("""
271
+ <div class="header-text">
272
+ <h1>πŸ“„ Multimodal: VLM Parsing</h1>
273
+ <p style="font-size: 1.1em;">An advanced Vision Language Model to parse documents and images into clean Markdown (html)</p>
274
+ <div style="display: flex; justify-content: center; gap: 20px; margin: 15px 0;">
275
+ <a href="https://huggingface.co/collections/prithivMLmods/mm-vlm-parsing-68e33e52bfb9ae60b50602dc" target="_blank" style="text-decoration: none; font-weight: 500;">πŸ€— Model Info</a>
276
+ <a href="https://github.com/PRITHIVSAKTHIUR/VLM-Parsing" target="_blank" style="text-decoration: none; font-weight: 500;">πŸ’» GitHub</a>
277
+ <a href="https://huggingface.co/models?pipeline_tag=image-text-to-text&sort=trending" target="_blank" style="text-decoration: none; font-weight: 500;">πŸ“ Multimodal VLMs</a>
278
+ </div>
279
+ </div>
280
+ """)
281
+
282
+ with gr.Row(elem_classes=["main-container"]):
283
+ with gr.Column(scale=1):
284
+ model_choice = gr.Dropdown(choices=["Logics-Parsing", "Gliese-OCR-7B-Post1.0", "olmOCR-7B-0825"], label="Select Model", value="Logics-Parsing")
285
+ file_input = gr.File(label="Upload PDF or Image", file_types=[".pdf", ".jpg", ".jpeg", ".png"], type="filepath")
286
+
287
+ image_preview = gr.Image(label="Preview", type="pil", interactive=False, height=320)
288
+
289
+ with gr.Row():
290
+ prev_page_btn = gr.Button("β—€ Previous")
291
+ page_info = gr.HTML('<div class="page-info">No file loaded</div>')
292
+ next_page_btn = gr.Button("Next β–Ά")
293
+
294
+ with gr.Accordion("Download & Details", open=False):
295
+ output_file = gr.File(label='Download Markdown Result', interactive=False)
296
+ cost_time = gr.Textbox(label='Time Cost', interactive=False)
297
+
298
+ example_root = "examples"
299
+ if os.path.exists(example_root) and os.path.isdir(example_root):
300
+ example_files = [os.path.join(example_root, f) for f in os.listdir(example_root) if f.endswith(tuple(pdf_suffixes + image_suffixes))]
301
+ if example_files:
302
+ gr.Examples(examples=example_files, inputs=file_input, label="Examples")
303
+
304
+ process_btn = gr.Button("πŸš€ Process Document", variant="primary", size="lg")
305
+ clear_btn = gr.Button("πŸ—‘οΈ Clear All", variant="secondary")
306
+
307
+ with gr.Column(scale=2):
308
+ with gr.Tabs():
309
+ with gr.Tab("Markdown Source"):
310
+ md_source_output = gr.Code(language="markdown", label="Markdown Source")
311
+ with gr.Tab("Rendered Markdown"):
312
+ md_render_output = gr.Markdown(label='Markdown Rendering')
313
+ with gr.Tab("Generated HTML"):
314
+ raw_html_output = gr.Code(language="html", label="Generated HTML")
315
+
316
+ file_input.change(fn=load_and_preview_file, inputs=file_input, outputs=[image_preview, page_info, app_state], show_progress="full")
317
+
318
+ process_btn.click(fn=process_all_pages, inputs=[app_state, model_choice], outputs=[md_render_output, md_source_output, raw_html_output, output_file, cost_time, app_state], show_progress="full")
319
+
320
+ prev_page_btn.click(fn=lambda s: navigate_page("prev", s), inputs=app_state, outputs=[image_preview, page_info, md_render_output, md_source_output, raw_html_output, app_state])
321
+
322
+ next_page_btn.click(fn=lambda s: navigate_page("next", s), inputs=app_state, outputs=[image_preview, page_info, md_render_output, md_source_output, raw_html_output, app_state])
323
+
324
+ clear_btn.click(fn=clear_all, outputs=[file_input, image_preview, md_render_output, md_source_output, raw_html_output, output_file, cost_time, page_info, app_state])
325
+
326
+ if __name__ == '__main__':
327
+ demo.queue()
328
+ demo.launch(theme=steel_blue_theme, css=css, mcp_server=True, ssr_mode=False, show_error=True)