prithivMLmods commited on
Commit
583c6f1
·
verified ·
1 Parent(s): 0e90140

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +210 -142
app.py CHANGED
@@ -1,195 +1,263 @@
1
- import gradio as gr
2
- import torch
3
  import requests
4
- from transformers import AutoModel, AutoProcessor, AutoTokenizer, GenerationConfig
 
 
5
  import spaces
6
- from typing import Iterable, List, Tuple
7
- import os
8
  from PIL import Image, ImageDraw
9
- import re
 
 
 
 
 
10
  from gradio.themes import Soft
11
  from gradio.themes.utils import colors, fonts, sizes
12
- import json
13
 
14
- # --- Environment and Device Setup ---
 
15
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
 
16
 
17
  print("CUDA_VISIBLE_DEVICES=", os.environ.get("CUDA_VISIBLE_DEVICES"))
18
  print("torch.__version__ =", torch.__version__)
19
- print("torch.version.cuda =", torch.version.cuda)
20
- print("cuda available:", torch.cuda.is_available())
21
- print("cuda device count:", torch.cuda.device_count())
22
- if torch.cuda.is_available():
23
- print("current device:", torch.cuda.current_device())
24
- print("device name:", torch.cuda.get_device_name(torch.cuda.current_device()))
25
- print(f"✅ Using device: {device}")
26
 
27
- # --- Post-processing Functions (Integrated from Nemotron-Parse) ---
28
- # NOTE: The following helper functions are adapted from the NVIDIA-Nemotron-Parse repository
29
- # to make this script self-contained and runnable.
30
-
31
- def extract_classes_bboxes(generated_text: str) -> Tuple[List[str], List[List[int]], List[str]]:
32
- """Extracts classes, bounding boxes, and associated text from the generated output."""
33
- classes, bboxes, texts = [], [], []
34
- # Regex to find <box>...</box> sections
35
- box_pattern = re.compile(r"<box>(.*?)</box>", re.DOTALL)
36
- # Regex to find <class>...</class> and [[...]] within each box
37
- class_pattern = re.compile(r"<class>(.*?)</class>")
38
- bbox_pattern = re.compile(r"\[\[(\d+,\d+,\d+,\d+)\]\]")
39
-
40
- for match in box_pattern.finditer(generated_text):
41
- box_content = match.group(1)
42
- class_match = class_pattern.search(box_content)
43
- bbox_match = bbox_pattern.search(box_content)
44
-
45
- if class_match and bbox_match:
46
- cls = class_match.group(1).strip()
47
- bbox_str = bbox_match.group(1).split(',')
48
- bbox = [int(coord) for coord in bbox_str]
49
-
50
- # Extract the text following the bbox
51
- text_content = box_content[bbox_match.end():].strip()
52
-
53
- classes.append(cls)
54
- bboxes.append(bbox)
55
- texts.append(text_content)
56
-
57
- return classes, bboxes, texts
58
-
59
- def transform_bbox_to_original(bbox: List[int], original_width: int, original_height: int,
60
- target_width: int = 1000, target_height: int = 1000) -> List[int]:
61
- """Transforms a bounding box from the model's coordinate system to the original image dimensions."""
62
- x1, y1, x2, y2 = bbox
63
- original_x1 = int(x1 / target_width * original_width)
64
- original_y1 = int(y1 / target_height * original_height)
65
- original_x2 = int(x2 / target_width * original_width)
66
- original_y2 = int(y2 / target_height * original_height)
67
- return [original_x1, original_y1, original_x2, original_y2]
68
-
69
- def postprocess_text(text: str, cls: str = 'text', table_format: str = 'markdown',
70
- text_format: str = 'markdown', blank_text_in_figures: bool = False) -> str:
71
- """Post-processes the extracted text based on its class and desired format."""
72
- if blank_text_in_figures and cls.lower() == 'picture':
73
- return ""
74
- if cls.lower() == 'table':
75
- if table_format == 'html':
76
- return f"<table>\n{text}\n</table>"
77
- elif table_format == 'latex':
78
- return f"\\begin{{tabular}}\n{text}\n\\end{{tabular}}"
79
- if text_format == 'markdown':
80
- return text.strip()
81
- return text
82
-
83
- # --- Theme and CSS (Unchanged) ---
84
- colors.steel_blue = colors.Color(name="steel_blue",c50="#EBF3F8",c100="#D3E5F0",c200="#A8CCE1",c300="#7DB3D2",c400="#529AC3",c500="#4682B4",c600="#3E72A0",c700="#36638C",c800="#2E5378",c900="#264364",c950="#1E3450")
85
  class SteelBlueTheme(Soft):
86
- def __init__(self,*,primary_hue: colors.Color | str = colors.gray,secondary_hue: colors.Color | str = colors.steel_blue,neutral_hue: colors.Color | str = colors.slate,text_size: sizes.Size | str = sizes.text_lg,font: fonts.Font | str | Iterable[fonts.Font | str] = (fonts.GoogleFont("Outfit"), "Arial", "sans-serif",),font_mono: fonts.Font | str | Iterable[fonts.Font | str] = (fonts.GoogleFont("IBM Plex Mono"), "ui-monospace", "monospace",),):
87
- super().__init__(primary_hue=primary_hue,secondary_hue=secondary_hue,neutral_hue=neutral_hue,text_size=text_size,font=font,font_mono=font_mono,)
88
- super().set(background_fill_primary="*primary_50",background_fill_primary_dark="*primary_900",body_background_fill="linear-gradient(135deg, *primary_200, *primary_100)",body_background_fill_dark="linear-gradient(135deg, *primary_900, *primary_800)",button_primary_text_color="white",button_primary_text_color_hover="white",button_primary_background_fill="linear-gradient(90deg, *secondary_500, *secondary_600)",button_primary_background_fill_hover="linear-gradient(90deg, *secondary_600, *secondary_700)",button_primary_background_fill_dark="linear-gradient(90deg, *secondary_600, *secondary_700)",button_primary_background_fill_hover_dark="linear-gradient(90deg, *secondary_500, *secondary_600)",slider_color="*secondary_500",slider_color_dark="*secondary_600",block_title_text_weight="600",block_border_width="3px",block_shadow="*shadow_drop_lg",button_primary_shadow="*shadow_drop_lg",button_large_padding="11px",color_accent_soft="*primary_100",block_label_background_fill="*primary_200",)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  steel_blue_theme = SteelBlueTheme()
 
90
  css = """
91
- #main-title h1 { font-size: 2.3em !important; }
92
- #output-title h2 { font-size: 2.1em !important; }
 
 
 
 
93
  """
94
 
95
  # --- Model Loading ---
96
- print("Loading model, tokenizer, and processor...")
97
- model_path = "nvidia/NVIDIA-Nemotron-Parse-v1.1"
 
 
 
98
 
99
  model = AutoModel.from_pretrained(
100
- model_path,
101
  trust_remote_code=True,
102
- torch_dtype=torch.bfloat16
 
103
  ).to(device).eval()
104
- tokenizer = AutoTokenizer.from_pretrained(model_path)
105
- processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True)
106
- generation_config = GenerationConfig.from_pretrained(model_path, trust_remote_code=True)
107
- print("✅ Model loaded successfully.")
108
 
 
 
109
 
110
- # --- Main Processing Function ---
111
  @spaces.GPU
112
- def process_document(image: Image.Image, task_type: str):
113
- """
114
- Processes an image with NVIDIA-Nemotron-Parse-v1.1.
115
- """
116
  if image is None:
117
- return "Please upload an image first.", None
118
-
119
- print(f"🏃 Running inference with task: {task_type}")
120
-
121
- # Define task prompts based on user selection
122
- task_prompts = {
123
- "Markdown + BBoxes + Classes": "</s><s><predict_bbox><predict_classes><output_markdown>",
124
- "Markdown Only": "</s><s><output_markdown>",
125
- "Plain Text + BBoxes + Classes": "</s><s><predict_bbox><predict_classes><output_text>",
126
- "Plain Text Only": "</s><s><output_text>",
127
- }
128
- task_prompt = task_prompts.get(task_type, "</s><s><output_markdown>")
129
 
130
- # Process image and generate output
131
- inputs = processor(images=[image], text=task_prompt, return_tensors="pt").to(device)
132
- outputs = model.generate(**inputs, generation_config=generation_config)
133
- generated_text = processor.batch_decode(outputs, skip_special_tokens=True)[0]
 
 
 
 
134
 
135
- print("✅ Inference complete. Starting post-processing...")
 
 
 
 
 
 
 
 
 
 
 
136
 
137
- # Post-process the generated text
138
- classes, bboxes, texts = extract_classes_bboxes(generated_text)
139
 
140
- # Combine all text for the main output textbox
141
- full_text_output = generated_text.split("<s>")[-1]
142
-
143
- # If bounding boxes were predicted, draw them on the image
144
- result_image_pil = None
145
- if bboxes:
146
- print(f"✅ Found {len(bboxes)} bounding box(es). Drawing on the original image.")
147
- bboxes_original = [transform_bbox_to_original(bbox, image.width, image.height) for bbox in bboxes]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
 
149
- image_with_bboxes = image.copy().convert("RGB")
150
- draw = ImageDraw.Draw(image_with_bboxes)
 
151
 
152
- for bbox in bboxes_original:
153
- draw.rectangle(tuple(bbox), outline="red", width=3)
154
- result_image_pil = image_with_bboxes
155
- else:
156
- print("⚠️ No bounding boxes were predicted or found.")
157
- result_image_pil = image.copy() # Return original image if no bboxes
 
 
 
 
 
 
 
 
158
 
159
- return full_text_output, result_image_pil
 
 
160
 
161
  # --- Gradio UI ---
162
  with gr.Blocks(css=css, theme=steel_blue_theme) as demo:
163
  gr.Markdown("# **NVIDIA Nemotron Parse v1.1**", elem_id="main-title")
164
- gr.Markdown("### An advanced model for document layout analysis and text extraction.")
165
 
166
  with gr.Row():
167
  with gr.Column(scale=1):
168
- image_input = gr.Image(type="pil", label="Upload Document Image", sources=["upload", "clipboard"])
169
- task_type = gr.Dropdown(
170
- choices=["Markdown + BBoxes + Classes", "Markdown Only", "Plain Text + BBoxes + Classes", "Plain Text Only"],
171
- value="Markdown + BBoxes + Classes",
172
- label="Task Type"
173
  )
174
  submit_btn = gr.Button("Process Document", variant="primary")
175
- gr.Examples(
 
176
  examples=["examples/1.jpg", "examples/2.jpg", "examples/3.jpg"],
177
- inputs=image_input,
178
  label="Examples"
179
  )
180
 
181
  with gr.Column(scale=2):
182
- output_text = gr.Textbox(label="Extracted Text", lines=12, show_copy_button=True)
183
- output_image = gr.Image(label="Layout Detection (If Task Includes BBoxes)", type="pil")
184
 
185
- with gr.Accordion("Note", open=False):
186
- gr.Markdown("Inference is performed using Hugging Face transformers on available hardware. This app demonstrates the capabilities of the NVIDIA-Nemotron-Parse-v1.1 model.")
187
 
188
  submit_btn.click(
189
- fn=process_document,
190
- inputs=[image_input, task_type],
191
  outputs=[output_text, output_image]
192
  )
193
 
194
  if __name__ == "__main__":
195
- demo.queue(max_size=20).launch(share=True, ssr_mode=False)
 
1
+ import os
2
+ import sys
3
  import requests
4
+ import shutil
5
+ from typing import Iterable
6
+ import gradio as gr
7
  import spaces
8
+ import torch
 
9
  from PIL import Image, ImageDraw
10
+ from transformers import (
11
+ AutoModel,
12
+ AutoProcessor,
13
+ AutoTokenizer,
14
+ GenerationConfig
15
+ )
16
  from gradio.themes import Soft
17
  from gradio.themes.utils import colors, fonts, sizes
 
18
 
19
+ # --- Device Setup ---
20
+ print("Determining device...")
21
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
22
+ print(f"✅ Using device: {device}")
23
 
24
  print("CUDA_VISIBLE_DEVICES=", os.environ.get("CUDA_VISIBLE_DEVICES"))
25
  print("torch.__version__ =", torch.__version__)
 
 
 
 
 
 
 
26
 
27
+ # --- Helper File Download ---
28
+ # The specific postprocessing logic for Nemotron is contained in a file
29
+ # hosted in the huggingface repo. We need to fetch it to import it.
30
+ def setup_helper_scripts():
31
+ file_name = "postprocessing.py"
32
+ url = "https://huggingface.co/nvidia/NVIDIA-Nemotron-Parse-v1.1/resolve/main/postprocessing.py"
33
+
34
+ if not os.path.exists(file_name):
35
+ print(f"Downloading {file_name} from {url}...")
36
+ try:
37
+ r = requests.get(url)
38
+ if r.status_code == 200:
39
+ with open(file_name, "wb") as f:
40
+ f.write(r.content)
41
+ print(f"✅ {file_name} downloaded successfully.")
42
+ else:
43
+ print(f"❌ Failed to download {file_name}. Status: {r.status_code}")
44
+ except Exception as e:
45
+ print(f"❌ Error downloading {file_name}: {str(e)}")
46
+
47
+ setup_helper_scripts()
48
+
49
+ # Now we can import from the downloaded file
50
+ try:
51
+ from postprocessing import extract_classes_bboxes, transform_bbox_to_original, postprocess_text
52
+ print("✅ Postprocessing modules imported successfully.")
53
+ except ImportError as e:
54
+ print(f"❌ Could not import postprocessing functions: {e}")
55
+ # Fallback definitions to prevent crash if download failed
56
+ def extract_classes_bboxes(text): return [], [], []
57
+ def transform_bbox_to_original(bbox, w, h): return bbox
58
+ def postprocess_text(text, **kwargs): return text
59
+
60
+ # --- Theme Setup ---
61
+ colors.steel_blue = colors.Color(
62
+ name="steel_blue",
63
+ c50="#EBF3F8",
64
+ c100="#D3E5F0",
65
+ c200="#A8CCE1",
66
+ c300="#7DB3D2",
67
+ c400="#529AC3",
68
+ c500="#4682B4",
69
+ c600="#3E72A0",
70
+ c700="#36638C",
71
+ c800="#2E5378",
72
+ c900="#264364",
73
+ c950="#1E3450",
74
+ )
75
+
 
 
 
 
 
 
 
 
 
76
  class SteelBlueTheme(Soft):
77
+ def __init__(
78
+ self,
79
+ *,
80
+ primary_hue: colors.Color | str = colors.gray,
81
+ secondary_hue: colors.Color | str = colors.steel_blue,
82
+ neutral_hue: colors.Color | str = colors.slate,
83
+ text_size: sizes.Size | str = sizes.text_lg,
84
+ font: fonts.Font | str | Iterable[fonts.Font | str] = (
85
+ fonts.GoogleFont("Outfit"), "Arial", "sans-serif",
86
+ ),
87
+ font_mono: fonts.Font | str | Iterable[fonts.Font | str] = (
88
+ fonts.GoogleFont("IBM Plex Mono"), "ui-monospace", "monospace",
89
+ ),
90
+ ):
91
+ super().__init__(
92
+ primary_hue=primary_hue,
93
+ secondary_hue=secondary_hue,
94
+ neutral_hue=neutral_hue,
95
+ text_size=text_size,
96
+ font=font,
97
+ font_mono=font_mono,
98
+ )
99
+ super().set(
100
+ background_fill_primary="*primary_50",
101
+ background_fill_primary_dark="*primary_900",
102
+ body_background_fill="linear-gradient(135deg, *primary_200, *primary_100)",
103
+ body_background_fill_dark="linear-gradient(135deg, *primary_900, *primary_800)",
104
+ button_primary_text_color="white",
105
+ button_primary_text_color_hover="white",
106
+ button_primary_background_fill="linear-gradient(90deg, *secondary_500, *secondary_600)",
107
+ button_primary_background_fill_hover="linear-gradient(90deg, *secondary_600, *secondary_700)",
108
+ button_primary_background_fill_dark="linear-gradient(90deg, *secondary_600, *secondary_700)",
109
+ button_primary_background_fill_hover_dark="linear-gradient(90deg, *secondary_500, *secondary_600)",
110
+ slider_color="*secondary_500",
111
+ slider_color_dark="*secondary_600",
112
+ block_title_text_weight="600",
113
+ block_border_width="3px",
114
+ block_shadow="*shadow_drop_lg",
115
+ button_primary_shadow="*shadow_drop_lg",
116
+ button_large_padding="11px",
117
+ color_accent_soft="*primary_100",
118
+ block_label_background_fill="*primary_200",
119
+ )
120
+
121
  steel_blue_theme = SteelBlueTheme()
122
+
123
  css = """
124
+ #main-title h1 {
125
+ font-size: 2.3em !important;
126
+ }
127
+ #output-title h2 {
128
+ font-size: 2.1em !important;
129
+ }
130
  """
131
 
132
  # --- Model Loading ---
133
+ print("Loading NVIDIA-Nemotron-Parse-v1.1...")
134
+ MODEL_ID = "nvidia/NVIDIA-Nemotron-Parse-v1.1"
135
+
136
+ processor = AutoProcessor.from_pretrained(MODEL_ID, trust_remote_code=True)
137
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
138
 
139
  model = AutoModel.from_pretrained(
140
+ MODEL_ID,
141
  trust_remote_code=True,
142
+ torch_dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32,
143
+ low_cpu_mem_usage=True,
144
  ).to(device).eval()
 
 
 
 
145
 
146
+ generation_config = GenerationConfig.from_pretrained(MODEL_ID, trust_remote_code=True)
147
+ print("✅ Model loaded successfully.")
148
 
 
149
  @spaces.GPU
150
+ def process_image(image):
 
 
 
151
  if image is None:
152
+ return "Please upload an image.", None
153
+
154
+ # 1. Prepare Prompt
155
+ # The standard prompt for extracting bounding boxes, classes, and markdown
156
+ task_prompt = "</s><s><predict_bbox><predict_classes><output_markdown>"
 
 
 
 
 
 
 
157
 
158
+ print("Processing image...")
159
+
160
+ # 2. Process Inputs
161
+ inputs = processor(
162
+ images=[image],
163
+ text=task_prompt,
164
+ return_tensors="pt"
165
+ )
166
 
167
+ # Move inputs to device
168
+ inputs = {k: v.to(device) for k, v in inputs.items()}
169
+ if "pixel_values" in inputs and torch.cuda.is_available():
170
+ inputs["pixel_values"] = inputs["pixel_values"].to(torch.bfloat16)
171
+
172
+ # 3. Generate
173
+ with torch.no_grad():
174
+ outputs = model.generate(
175
+ **inputs,
176
+ generation_config=generation_config,
177
+ max_new_tokens=4096
178
+ )
179
 
180
+ # 4. Decode
181
+ generated_text = processor.batch_decode(outputs, skip_special_tokens=True)[0]
182
 
183
+ # 5. Post-processing (Using the imported functions)
184
+ try:
185
+ classes, bboxes, texts = extract_classes_bboxes(generated_text)
186
+
187
+ # Transform bboxes to original image size
188
+ bboxes = [transform_bbox_to_original(bbox, image.width, image.height) for bbox in bboxes]
189
+
190
+ # Configure text formatting
191
+ table_format = 'markdown' # options: latex, HTML, markdown
192
+ text_format = 'markdown' # options: markdown, plain
193
+ blank_text_in_figures = False
194
+
195
+ cleaned_texts = [
196
+ postprocess_text(
197
+ text,
198
+ cls=cls,
199
+ table_format=table_format,
200
+ text_format=text_format,
201
+ blank_text_in_figures=blank_text_in_figures
202
+ )
203
+ for text, cls in zip(texts, classes)
204
+ ]
205
 
206
+ # 6. Draw Bounding Boxes
207
+ annotated_image = image.copy()
208
+ draw = ImageDraw.Draw(annotated_image)
209
 
210
+ # Define colors for different classes if desired, currently using red for all
211
+ for bbox, cls in zip(bboxes, classes):
212
+ # bbox is [x1, y1, x2, y2]
213
+ draw.rectangle([bbox[0], bbox[1], bbox[2], bbox[3]], outline="red", width=3)
214
+ # Optional: Draw label
215
+ # draw.text((bbox[0], bbox[1]), cls, fill="red")
216
+
217
+ # 7. Assemble Final Markdown
218
+ final_markdown = "\n\n".join(cleaned_texts)
219
+
220
+ if not final_markdown.strip():
221
+ final_markdown = generated_text # Fallback if postprocessing strips everything
222
+
223
+ return final_markdown, annotated_image
224
 
225
+ except Exception as e:
226
+ print(f"Error during post-processing: {e}")
227
+ return f"Error parsing output: {str(e)}\n\nRaw Output:\n{generated_text}", image
228
 
229
  # --- Gradio UI ---
230
  with gr.Blocks(css=css, theme=steel_blue_theme) as demo:
231
  gr.Markdown("# **NVIDIA Nemotron Parse v1.1**", elem_id="main-title")
232
+ gr.Markdown("Upload a document to parse structure, extract text, and visualize layout detection.", elem_id="sub-title")
233
 
234
  with gr.Row():
235
  with gr.Column(scale=1):
236
+ image_input = gr.Image(
237
+ type="pil",
238
+ label="Upload Image",
239
+ sources=["upload", "clipboard"]
 
240
  )
241
  submit_btn = gr.Button("Process Document", variant="primary")
242
+
243
+ examples = gr.Examples(
244
  examples=["examples/1.jpg", "examples/2.jpg", "examples/3.jpg"],
245
+ inputs=image_input,
246
  label="Examples"
247
  )
248
 
249
  with gr.Column(scale=2):
250
+ output_text = gr.Markdown(label="Parsed Content (Markdown)")
251
+ output_image = gr.Image(label="Layout Detection", type="pil")
252
 
253
+ with gr.Accordion("Raw Output Details", open=False):
254
+ gr.Markdown("This model uses `<predict_bbox><predict_classes><output_markdown>` prompt strategy.")
255
 
256
  submit_btn.click(
257
+ fn=process_image,
258
+ inputs=[image_input],
259
  outputs=[output_text, output_image]
260
  )
261
 
262
  if __name__ == "__main__":
263
+ demo.queue(max_size=20).launch(share=True, mcp_server=True, ssr_mode=False)