Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,195 +1,263 @@
|
|
| 1 |
-
import
|
| 2 |
-
import
|
| 3 |
import requests
|
| 4 |
-
|
|
|
|
|
|
|
| 5 |
import spaces
|
| 6 |
-
|
| 7 |
-
import os
|
| 8 |
from PIL import Image, ImageDraw
|
| 9 |
-
import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
from gradio.themes import Soft
|
| 11 |
from gradio.themes.utils import colors, fonts, sizes
|
| 12 |
-
import json
|
| 13 |
|
| 14 |
-
# ---
|
|
|
|
| 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 |
-
# ---
|
| 28 |
-
#
|
| 29 |
-
#
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
""
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 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__(
|
| 87 |
-
|
| 88 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
steel_blue_theme = SteelBlueTheme()
|
|
|
|
| 90 |
css = """
|
| 91 |
-
#main-title h1 {
|
| 92 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
"""
|
| 94 |
|
| 95 |
# --- Model Loading ---
|
| 96 |
-
print("Loading
|
| 97 |
-
|
|
|
|
|
|
|
|
|
|
| 98 |
|
| 99 |
model = AutoModel.from_pretrained(
|
| 100 |
-
|
| 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
|
| 113 |
-
"""
|
| 114 |
-
Processes an image with NVIDIA-Nemotron-Parse-v1.1.
|
| 115 |
-
"""
|
| 116 |
if image is None:
|
| 117 |
-
return "Please upload an image
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 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 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
|
| 135 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
|
| 137 |
-
#
|
| 138 |
-
|
| 139 |
|
| 140 |
-
#
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
|
| 149 |
-
|
| 150 |
-
|
|
|
|
| 151 |
|
| 152 |
-
for
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
|
| 159 |
-
|
|
|
|
|
|
|
| 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("
|
| 165 |
|
| 166 |
with gr.Row():
|
| 167 |
with gr.Column(scale=1):
|
| 168 |
-
image_input = gr.Image(
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
label="Task Type"
|
| 173 |
)
|
| 174 |
submit_btn = gr.Button("Process Document", variant="primary")
|
| 175 |
-
|
|
|
|
| 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.
|
| 183 |
-
output_image = gr.Image(label="Layout Detection
|
| 184 |
|
| 185 |
-
with gr.Accordion("
|
| 186 |
-
gr.Markdown("
|
| 187 |
|
| 188 |
submit_btn.click(
|
| 189 |
-
fn=
|
| 190 |
-
inputs=[image_input
|
| 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)
|