Spaces:
Running
on
Zero
Running
on
Zero
Update app.py
Browse files
app.py
CHANGED
|
@@ -44,7 +44,6 @@ DEFAULT_PROMPT = (
|
|
| 44 |
print("Loading models, this will take some time and VRAM...")
|
| 45 |
try:
|
| 46 |
# WARNING: Loading two 3B models without quantization requires a large amount of VRAM (>12 GB).
|
| 47 |
-
# This may fail on hardware with insufficient memory.
|
| 48 |
print(f"Loading {MODEL_BASE_NAME}...")
|
| 49 |
model_base = Qwen2_5_VLForConditionalGeneration.from_pretrained(
|
| 50 |
MODEL_BASE_ID,
|
|
@@ -59,7 +58,6 @@ try:
|
|
| 59 |
device_map="auto"
|
| 60 |
)
|
| 61 |
|
| 62 |
-
# Processor is the same for both models
|
| 63 |
processor = AutoProcessor.from_pretrained(MODEL_BASE_ID)
|
| 64 |
print("All models loaded successfully!")
|
| 65 |
except Exception as e:
|
|
@@ -68,7 +66,7 @@ except Exception as e:
|
|
| 68 |
|
| 69 |
# --- 3. Core Inference and Visualization Function ---
|
| 70 |
@GPU
|
| 71 |
-
def analyze_and_visualize_layout(input_image: Image.Image, selected_model_name: str, prompt: str, progress=gr.Progress(track_tqdm=True)):
|
| 72 |
"""
|
| 73 |
Takes an image and model parameters, runs inference, and returns a visualized image and raw text output.
|
| 74 |
"""
|
|
@@ -76,39 +74,31 @@ def analyze_and_visualize_layout(input_image: Image.Image, selected_model_name:
|
|
| 76 |
return None, "Please upload an image first."
|
| 77 |
|
| 78 |
# Select the model based on user's choice
|
| 79 |
-
if selected_model_name == MODEL_BASE_NAME
|
| 80 |
-
model = model_base
|
| 81 |
-
else:
|
| 82 |
-
model = model_enhanced
|
| 83 |
|
| 84 |
progress(0, desc=f"Resizing image for {selected_model_name}...")
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
messages = [
|
| 90 |
-
{"role": "user", "content": [
|
| 91 |
-
{"type": "image", "image": image},
|
| 92 |
-
{"type": "text", "text": prompt}
|
| 93 |
-
]}
|
| 94 |
-
]
|
| 95 |
|
| 96 |
progress(0.2, desc="Preparing model inputs...")
|
| 97 |
text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 98 |
inputs = processor(text=[text], images=[image], padding=True, return_tensors="pt").to(model.device)
|
| 99 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
progress(0.5, desc="Generating layout data...")
|
| 101 |
with torch.no_grad():
|
| 102 |
-
|
| 103 |
-
output_ids = model.generate(
|
| 104 |
-
**inputs,
|
| 105 |
-
max_new_tokens=4096,
|
| 106 |
-
do_sample=False
|
| 107 |
-
)
|
| 108 |
|
| 109 |
-
output_text = processor.batch_decode(
|
| 110 |
-
output_ids[:, inputs.input_ids.shape[1]:], skip_special_tokens=True
|
| 111 |
-
)[0]
|
| 112 |
|
| 113 |
progress(0.8, desc="Parsing and visualizing results...")
|
| 114 |
try:
|
|
@@ -127,41 +117,34 @@ def analyze_and_visualize_layout(input_image: Image.Image, selected_model_name:
|
|
| 127 |
font = ImageFont.load_default()
|
| 128 |
|
| 129 |
for item in sorted(results, key=lambda x: x.get("order", 999)):
|
| 130 |
-
bbox = item.get("bbox_2d")
|
| 131 |
-
label = item.get("label", "other")
|
| 132 |
-
order = item.get("order", "")
|
| 133 |
-
|
| 134 |
if not bbox or len(bbox) != 4: continue
|
| 135 |
|
| 136 |
fill_color_rgba = LABEL_COLORS.get(label, LABEL_COLORS["other"])
|
| 137 |
solid_color_rgb = fill_color_rgba[:3]
|
| 138 |
-
|
| 139 |
draw.rectangle(bbox, fill=fill_color_rgba, outline=solid_color_rgb, width=OUTLINE_WIDTH)
|
| 140 |
|
| 141 |
tag_text = f"{order}: {label}"
|
| 142 |
tag_bbox = draw.textbbox((0, 0), tag_text, font=font)
|
| 143 |
tag_w, tag_h = tag_bbox[2] - tag_bbox[0], tag_bbox[3] - tag_bbox[1]
|
| 144 |
-
|
| 145 |
tag_bg_box = [bbox[0], bbox[1], bbox[0] + tag_w + 10, bbox[1] + tag_h + 6]
|
| 146 |
draw.rectangle(tag_bg_box, fill=solid_color_rgb)
|
| 147 |
draw.text((bbox[0] + 5, bbox[1] + 3), tag_text, font=font, fill="white")
|
| 148 |
|
| 149 |
-
|
| 150 |
-
return visualized_image, output_text
|
| 151 |
|
| 152 |
def clear_outputs():
|
| 153 |
-
"""Helper function to clear the output fields."""
|
| 154 |
return None, None
|
| 155 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
# --- 4. Gradio User Interface ---
|
| 157 |
with gr.Blocks(theme=gr.themes.Glass(), title="Academic Paper Layout Detection") as demo:
|
| 158 |
-
|
| 159 |
gr.Markdown("# 📄 Academic Paper Layout Detection")
|
| 160 |
-
gr.Markdown(
|
| 161 |
-
"Welcome! This tool uses a Qwen2.5-VL-3B-Instruct model fine-tuned on our Latex2Layout annotated layout dataset to identify layout regions in academic papers. "
|
| 162 |
-
"Upload a document image to begin."
|
| 163 |
-
"\n> **Please note:** All uploaded images are automatically resized to 924x1204 pixels to meet the model's input requirements."
|
| 164 |
-
)
|
| 165 |
gr.Markdown("<hr>")
|
| 166 |
|
| 167 |
with gr.Row():
|
|
@@ -173,40 +156,38 @@ with gr.Blocks(theme=gr.themes.Glass(), title="Academic Paper Layout Detection")
|
|
| 173 |
with gr.Row():
|
| 174 |
analyze_btn = gr.Button("✨ Analyze Layout", variant="primary", scale=1)
|
| 175 |
|
| 176 |
-
# --- Advanced Settings Panel ---
|
| 177 |
with gr.Accordion("Advanced Settings", open=False):
|
| 178 |
-
model_selector = gr.Radio(
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
value=
|
| 187 |
-
|
| 188 |
-
info="The prompt used to instruct the model."
|
| 189 |
-
)
|
| 190 |
|
| 191 |
output_text = gr.Textbox(label="Model Raw Output", lines=8, interactive=False, visible=True)
|
| 192 |
-
|
| 193 |
-
gr.
|
| 194 |
-
examples=[["1.png"], ["2.png"], ["12.png"], ["13.png"], ["14.png"], ["11.png"], ["3.png"], ["7.png"], ["8.png"]],
|
| 195 |
-
inputs=[input_image],
|
| 196 |
-
label="Examples (Click to Run)",
|
| 197 |
-
)
|
| 198 |
-
|
| 199 |
-
gr.Markdown("<p style='text-align:center; color:grey;'>Powered by the Latex2Layout dataset generated by Feijiang Han</p>")
|
| 200 |
|
| 201 |
# --- Event Handlers ---
|
| 202 |
analyze_btn.click(
|
| 203 |
fn=analyze_and_visualize_layout,
|
| 204 |
-
inputs=[input_image, model_selector, prompt_textbox],
|
| 205 |
outputs=[output_image, output_text]
|
| 206 |
)
|
| 207 |
|
| 208 |
input_image.upload(fn=clear_outputs, inputs=None, outputs=[output_image, output_text])
|
| 209 |
input_image.clear(fn=clear_outputs, inputs=None, outputs=[output_image, output_text])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
|
| 211 |
# --- 5. Launch the Application ---
|
| 212 |
if __name__ == "__main__":
|
|
|
|
| 44 |
print("Loading models, this will take some time and VRAM...")
|
| 45 |
try:
|
| 46 |
# WARNING: Loading two 3B models without quantization requires a large amount of VRAM (>12 GB).
|
|
|
|
| 47 |
print(f"Loading {MODEL_BASE_NAME}...")
|
| 48 |
model_base = Qwen2_5_VLForConditionalGeneration.from_pretrained(
|
| 49 |
MODEL_BASE_ID,
|
|
|
|
| 58 |
device_map="auto"
|
| 59 |
)
|
| 60 |
|
|
|
|
| 61 |
processor = AutoProcessor.from_pretrained(MODEL_BASE_ID)
|
| 62 |
print("All models loaded successfully!")
|
| 63 |
except Exception as e:
|
|
|
|
| 66 |
|
| 67 |
# --- 3. Core Inference and Visualization Function ---
|
| 68 |
@GPU
|
| 69 |
+
def analyze_and_visualize_layout(input_image: Image.Image, selected_model_name: str, prompt: str, use_greedy: bool, temperature: float, top_p: float, progress=gr.Progress(track_tqdm=True)):
|
| 70 |
"""
|
| 71 |
Takes an image and model parameters, runs inference, and returns a visualized image and raw text output.
|
| 72 |
"""
|
|
|
|
| 74 |
return None, "Please upload an image first."
|
| 75 |
|
| 76 |
# Select the model based on user's choice
|
| 77 |
+
model = model_base if selected_model_name == MODEL_BASE_NAME else model_enhanced
|
|
|
|
|
|
|
|
|
|
| 78 |
|
| 79 |
progress(0, desc=f"Resizing image for {selected_model_name}...")
|
| 80 |
+
image = input_image.resize(TARGET_SIZE).convert("RGBA")
|
| 81 |
+
|
| 82 |
+
messages = [{"role": "user", "content": [{"type": "image", "image": image}, {"type": "text", "text": prompt}]}]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
|
| 84 |
progress(0.2, desc="Preparing model inputs...")
|
| 85 |
text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 86 |
inputs = processor(text=[text], images=[image], padding=True, return_tensors="pt").to(model.device)
|
| 87 |
|
| 88 |
+
# Dynamically build generation arguments based on user's choice
|
| 89 |
+
gen_kwargs = {"max_new_tokens": 4096}
|
| 90 |
+
if use_greedy:
|
| 91 |
+
gen_kwargs["do_sample"] = False
|
| 92 |
+
else:
|
| 93 |
+
gen_kwargs["do_sample"] = True
|
| 94 |
+
gen_kwargs["temperature"] = temperature
|
| 95 |
+
gen_kwargs["top_p"] = top_p
|
| 96 |
+
|
| 97 |
progress(0.5, desc="Generating layout data...")
|
| 98 |
with torch.no_grad():
|
| 99 |
+
output_ids = model.generate(**inputs, **gen_kwargs)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
|
| 101 |
+
output_text = processor.batch_decode(output_ids[:, inputs.input_ids.shape[1]:], skip_special_tokens=True)[0]
|
|
|
|
|
|
|
| 102 |
|
| 103 |
progress(0.8, desc="Parsing and visualizing results...")
|
| 104 |
try:
|
|
|
|
| 117 |
font = ImageFont.load_default()
|
| 118 |
|
| 119 |
for item in sorted(results, key=lambda x: x.get("order", 999)):
|
| 120 |
+
bbox, label, order = item.get("bbox_2d"), item.get("label", "other"), item.get("order", "")
|
|
|
|
|
|
|
|
|
|
| 121 |
if not bbox or len(bbox) != 4: continue
|
| 122 |
|
| 123 |
fill_color_rgba = LABEL_COLORS.get(label, LABEL_COLORS["other"])
|
| 124 |
solid_color_rgb = fill_color_rgba[:3]
|
|
|
|
| 125 |
draw.rectangle(bbox, fill=fill_color_rgba, outline=solid_color_rgb, width=OUTLINE_WIDTH)
|
| 126 |
|
| 127 |
tag_text = f"{order}: {label}"
|
| 128 |
tag_bbox = draw.textbbox((0, 0), tag_text, font=font)
|
| 129 |
tag_w, tag_h = tag_bbox[2] - tag_bbox[0], tag_bbox[3] - tag_bbox[1]
|
|
|
|
| 130 |
tag_bg_box = [bbox[0], bbox[1], bbox[0] + tag_w + 10, bbox[1] + tag_h + 6]
|
| 131 |
draw.rectangle(tag_bg_box, fill=solid_color_rgb)
|
| 132 |
draw.text((bbox[0] + 5, bbox[1] + 3), tag_text, font=font, fill="white")
|
| 133 |
|
| 134 |
+
return Image.alpha_composite(image, overlay).convert("RGB"), output_text
|
|
|
|
| 135 |
|
| 136 |
def clear_outputs():
|
|
|
|
| 137 |
return None, None
|
| 138 |
|
| 139 |
+
def toggle_sampling_params(use_greedy):
|
| 140 |
+
"""Updates visibility of temperature and top-p sliders."""
|
| 141 |
+
is_visible = not use_greedy
|
| 142 |
+
return gr.update(visible=is_visible), gr.update(visible=is_visible)
|
| 143 |
+
|
| 144 |
# --- 4. Gradio User Interface ---
|
| 145 |
with gr.Blocks(theme=gr.themes.Glass(), title="Academic Paper Layout Detection") as demo:
|
|
|
|
| 146 |
gr.Markdown("# 📄 Academic Paper Layout Detection")
|
| 147 |
+
gr.Markdown("Welcome! This tool uses a Qwen2.5-VL-3B-Instruct model...") # Truncated for brevity
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
gr.Markdown("<hr>")
|
| 149 |
|
| 150 |
with gr.Row():
|
|
|
|
| 156 |
with gr.Row():
|
| 157 |
analyze_btn = gr.Button("✨ Analyze Layout", variant="primary", scale=1)
|
| 158 |
|
|
|
|
| 159 |
with gr.Accordion("Advanced Settings", open=False):
|
| 160 |
+
model_selector = gr.Radio(choices=MODEL_CHOICES, value=MODEL_BASE_NAME, label="Select Model")
|
| 161 |
+
prompt_textbox = gr.Textbox(label="Prompt", value=DEFAULT_PROMPT, lines=5)
|
| 162 |
+
|
| 163 |
+
# NEW: Checkbox to toggle between greedy and sampling
|
| 164 |
+
greedy_checkbox = gr.Checkbox(label="Use Greedy Decoding", value=True, info="Faster and deterministic. Uncheck to enable Temperature and Top-p.")
|
| 165 |
+
|
| 166 |
+
# NEW: Sliders are initially hidden
|
| 167 |
+
with gr.Row(visible=False) as sampling_params:
|
| 168 |
+
temp_slider = gr.Slider(minimum=0.0, maximum=2.0, step=0.05, value=0.7, label="Temperature")
|
| 169 |
+
top_p_slider = gr.Slider(minimum=0.0, maximum=1.0, step=0.05, value=0.9, label="Top-p")
|
|
|
|
|
|
|
| 170 |
|
| 171 |
output_text = gr.Textbox(label="Model Raw Output", lines=8, interactive=False, visible=True)
|
| 172 |
+
gr.Examples(examples=[["1.png"], ["2.png"], ["10.png"]], inputs=[input_image], label="Examples (Click to Run)")
|
| 173 |
+
gr.Markdown("<p style='text-align:center; color:grey;'>Powered by the Latex2Layout dataset by Feijiang Han</p>")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
|
| 175 |
# --- Event Handlers ---
|
| 176 |
analyze_btn.click(
|
| 177 |
fn=analyze_and_visualize_layout,
|
| 178 |
+
inputs=[input_image, model_selector, prompt_textbox, greedy_checkbox, temp_slider, top_p_slider],
|
| 179 |
outputs=[output_image, output_text]
|
| 180 |
)
|
| 181 |
|
| 182 |
input_image.upload(fn=clear_outputs, inputs=None, outputs=[output_image, output_text])
|
| 183 |
input_image.clear(fn=clear_outputs, inputs=None, outputs=[output_image, output_text])
|
| 184 |
+
|
| 185 |
+
# NEW: Event handler to show/hide sliders
|
| 186 |
+
greedy_checkbox.change(
|
| 187 |
+
fn=toggle_sampling_params,
|
| 188 |
+
inputs=greedy_checkbox,
|
| 189 |
+
outputs=[sampling_params]
|
| 190 |
+
)
|
| 191 |
|
| 192 |
# --- 5. Launch the Application ---
|
| 193 |
if __name__ == "__main__":
|