Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,40 +6,35 @@ import json
|
|
| 6 |
import re
|
| 7 |
from spaces import GPU
|
| 8 |
|
| 9 |
-
|
| 10 |
# --- 1. Configurations and Constants ---
|
| 11 |
-
|
| 12 |
-
# Hugging Face model repository
|
| 13 |
MODEL_ID = "ChaseHan/Latex2Layout-2000-sync"
|
| 14 |
|
| 15 |
-
#
|
| 16 |
TARGET_SIZE = (924, 1204)
|
| 17 |
|
| 18 |
-
# Visualization
|
| 19 |
OUTLINE_WIDTH = 3
|
| 20 |
-
#
|
| 21 |
LABEL_COLORS = {
|
| 22 |
-
"title": (255, 82, 82, 90),
|
| 23 |
-
"abstract": (46, 204, 113, 90),
|
| 24 |
-
"heading": (52, 152, 219, 90),
|
| 25 |
-
"footnote": (241, 196, 15, 90),
|
| 26 |
"figure": (155, 89, 182, 90), # Purple
|
| 27 |
-
"figure caption": (26, 188, 156, 90)
|
| 28 |
-
"table": (230, 126, 34, 90),
|
| 29 |
-
"table caption": (44, 62, 80, 90),
|
| 30 |
-
"math": (231, 76, 60, 90),
|
| 31 |
"text": (149, 165, 166, 90), # Gray
|
| 32 |
"other": (127, 140, 141, 90) # Light Gray
|
| 33 |
}
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
"""<image>Please carefully observe the document and detect the following regions: "title", "abstract", "heading", "footnote", "figure", "figure caption", "table", "table caption", "math", "text". Output each detected region's bbox coordinates in JSON format. The format of the output is:
|
| 38 |
-
<answer>```json[{"bbox_2d": [x1, y1, x2, y2], "label": "region name", "order": "reading order"}]</answer>```"""
|
| 39 |
)
|
| 40 |
|
| 41 |
# --- 2. Load Model and Processor ---
|
| 42 |
-
|
| 43 |
print("Loading model and processor, this may take a moment...")
|
| 44 |
try:
|
| 45 |
model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
|
|
@@ -53,50 +48,48 @@ except Exception as e:
|
|
| 53 |
print(f"Error loading model: {e}")
|
| 54 |
exit()
|
| 55 |
|
| 56 |
-
|
| 57 |
# --- 3. Core Inference and Visualization Function ---
|
| 58 |
-
|
| 59 |
@GPU
|
| 60 |
def analyze_and_visualize_layout(input_image: Image.Image, prompt: str, temperature: float, top_p: float, progress=gr.Progress(track_tqdm=True)):
|
| 61 |
"""
|
| 62 |
-
|
| 63 |
"""
|
| 64 |
if input_image is None:
|
| 65 |
return None, "Please upload an image first."
|
| 66 |
|
| 67 |
progress(0, desc="Resizing image...")
|
| 68 |
-
# BUG FIX: Use fixed-size scaling
|
| 69 |
image = input_image.resize(TARGET_SIZE)
|
| 70 |
-
image = image.convert("RGBA")
|
| 71 |
|
| 72 |
messages = [
|
| 73 |
{"role": "user", "content": [
|
| 74 |
{"type": "image", "image": image},
|
| 75 |
-
{"type": "text", "text": prompt}
|
| 76 |
]}
|
| 77 |
]
|
| 78 |
-
|
| 79 |
progress(0.2, desc="Preparing model inputs...")
|
| 80 |
text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 81 |
inputs = processor(text=[text], images=[image], padding=True, return_tensors="pt").to(model.device)
|
| 82 |
|
| 83 |
progress(0.5, desc="Generating layout data...")
|
| 84 |
with torch.no_grad():
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
|
|
|
| 93 |
output_text = processor.batch_decode(
|
| 94 |
output_ids[:, inputs.input_ids.shape[1]:], skip_special_tokens=True
|
| 95 |
)[0]
|
| 96 |
|
| 97 |
progress(0.8, desc="Parsing and visualizing results...")
|
| 98 |
try:
|
| 99 |
-
json_match = re.search(r"json(.*?)", output_text, re.DOTALL)
|
| 100 |
json_str = json_match.group(1).strip() if json_match else output_text.strip()
|
| 101 |
results = json.loads(json_str)
|
| 102 |
except (json.JSONDecodeError, AttributeError):
|
|
@@ -115,8 +108,7 @@ def analyze_and_visualize_layout(input_image: Image.Image, prompt: str, temperat
|
|
| 115 |
label = item.get("label", "other")
|
| 116 |
order = item.get("order", "")
|
| 117 |
|
| 118 |
-
if not bbox or len(bbox) != 4:
|
| 119 |
-
continue
|
| 120 |
|
| 121 |
fill_color_rgba = LABEL_COLORS.get(label, LABEL_COLORS["other"])
|
| 122 |
solid_color_rgb = fill_color_rgba[:3]
|
|
@@ -126,29 +118,25 @@ def analyze_and_visualize_layout(input_image: Image.Image, prompt: str, temperat
|
|
| 126 |
tag_text = f"{order}: {label}"
|
| 127 |
tag_bbox = draw.textbbox((0, 0), tag_text, font=font)
|
| 128 |
tag_w, tag_h = tag_bbox[2] - tag_bbox[0], tag_bbox[3] - tag_bbox[1]
|
| 129 |
-
|
| 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 |
visualized_image = Image.alpha_composite(image, overlay).convert("RGB")
|
| 135 |
-
|
| 136 |
return visualized_image, output_text
|
| 137 |
|
| 138 |
-
|
| 139 |
def clear_outputs():
|
| 140 |
-
"""
|
| 141 |
return None, None
|
| 142 |
|
| 143 |
-
|
| 144 |
# --- 4. Gradio User Interface ---
|
| 145 |
-
|
| 146 |
with gr.Blocks(theme=gr.themes.Glass(), title="Academic Paper Layout Detection") as demo:
|
|
|
|
| 147 |
gr.Markdown("# 📄 Academic Paper Layout Detection")
|
| 148 |
gr.Markdown(
|
| 149 |
"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. "
|
| 150 |
"Upload a document image to begin."
|
| 151 |
-
# BUG FIX: Updated description to reflect fixed-size scaling
|
| 152 |
"\n> **Please note:** All uploaded images are automatically resized to 924x1204 pixels to meet the model's input requirements."
|
| 153 |
)
|
| 154 |
gr.Markdown("<hr>")
|
|
@@ -156,61 +144,58 @@ with gr.Blocks(theme=gr.themes.Glass(), title="Academic Paper Layout Detection")
|
|
| 156 |
with gr.Row():
|
| 157 |
with gr.Column(scale=4):
|
| 158 |
input_image = gr.Image(type="pil", label="Upload Document Image", height=700)
|
| 159 |
-
with gr.Accordion("Advanced Settings", open=False):
|
| 160 |
-
prompt_input = gr.Textbox(
|
| 161 |
-
value=PROMPT_GROUNDING,
|
| 162 |
-
label="Custom Prompt",
|
| 163 |
-
lines=5,
|
| 164 |
-
info="Edit the prompt sent to the model. Changes may affect output format."
|
| 165 |
-
)
|
| 166 |
-
temperature_input = gr.Slider(
|
| 167 |
-
minimum=0.0,
|
| 168 |
-
maximum=2.0,
|
| 169 |
-
value=1.0,
|
| 170 |
-
step=0.1,
|
| 171 |
-
label="Temperature",
|
| 172 |
-
info="Controls randomness (higher = more creative, 0 = deterministic)."
|
| 173 |
-
)
|
| 174 |
-
top_p_input = gr.Slider(
|
| 175 |
-
minimum=0.0,
|
| 176 |
-
maximum=1.0,
|
| 177 |
-
value=0.95,
|
| 178 |
-
step=0.05,
|
| 179 |
-
label="Top-P",
|
| 180 |
-
info="Nucleus sampling: considers the top p% probability mass."
|
| 181 |
-
)
|
| 182 |
with gr.Column(scale=5):
|
| 183 |
output_image = gr.Image(type="pil", label="Analyzed Layout", interactive=False, height=700)
|
| 184 |
-
|
| 185 |
with gr.Row():
|
| 186 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 187 |
|
| 188 |
output_text = gr.Textbox(label="Model Raw Output", lines=8, interactive=False, visible=True)
|
| 189 |
|
| 190 |
-
# fix
|
| 191 |
gr.Examples(
|
| 192 |
-
examples=[["
|
| 193 |
-
inputs=[input_image
|
| 194 |
-
outputs=[output_image, output_text],
|
| 195 |
-
fn=analyze_and_visualize_layout,
|
| 196 |
label="Examples (Click to Run)",
|
| 197 |
-
|
| 198 |
)
|
| 199 |
-
|
| 200 |
gr.Markdown("<p style='text-align:center; color:grey;'>Powered by the Latex2Layout dataset generated by Feijiang Han</p>")
|
| 201 |
|
| 202 |
# --- Event Handlers ---
|
| 203 |
analyze_btn.click(
|
| 204 |
fn=analyze_and_visualize_layout,
|
| 205 |
-
inputs=[input_image,
|
| 206 |
outputs=[output_image, output_text]
|
| 207 |
)
|
| 208 |
-
|
| 209 |
input_image.upload(fn=clear_outputs, inputs=None, outputs=[output_image, output_text])
|
| 210 |
input_image.clear(fn=clear_outputs, inputs=None, outputs=[output_image, output_text])
|
| 211 |
|
| 212 |
-
|
| 213 |
# --- 5. Launch the Application ---
|
| 214 |
-
|
| 215 |
if __name__ == "__main__":
|
| 216 |
demo.launch()
|
|
|
|
| 6 |
import re
|
| 7 |
from spaces import GPU
|
| 8 |
|
|
|
|
| 9 |
# --- 1. Configurations and Constants ---
|
| 10 |
+
# Model repository on Hugging Face
|
|
|
|
| 11 |
MODEL_ID = "ChaseHan/Latex2Layout-2000-sync"
|
| 12 |
|
| 13 |
+
# Target image size for model input
|
| 14 |
TARGET_SIZE = (924, 1204)
|
| 15 |
|
| 16 |
+
# Visualization Style Constants
|
| 17 |
OUTLINE_WIDTH = 3
|
| 18 |
+
# Color mapping for different layout regions (RGBA for transparency)
|
| 19 |
LABEL_COLORS = {
|
| 20 |
+
"title": (255, 82, 82, 90), # Red
|
| 21 |
+
"abstract": (46, 204, 113, 90), # Green
|
| 22 |
+
"heading": (52, 152, 219, 90), # Blue
|
| 23 |
+
"footnote": (241, 196, 15, 90), # Yellow
|
| 24 |
"figure": (155, 89, 182, 90), # Purple
|
| 25 |
+
"figure caption": (26, 188, 156, 90),# Teal
|
| 26 |
+
"table": (230, 126, 34, 90), # Orange
|
| 27 |
+
"table caption": (44, 62, 80, 90), # Dark Blue/Gray
|
| 28 |
+
"math": (231, 76, 60, 90), # Pomegranate
|
| 29 |
"text": (149, 165, 166, 90), # Gray
|
| 30 |
"other": (127, 140, 141, 90) # Light Gray
|
| 31 |
}
|
| 32 |
+
# The default prompt sent to the model for layout detection
|
| 33 |
+
DEFAULT_PROMPT = (
|
| 34 |
+
"""<image>Please carefully observe the document and detect the following regions: "title", "abstract", "heading", "footnote", "figure", "figure caption", "table", "table caption", "math", "text". Output each detected region's bbox coordinates in JSON format. The format of the output is: <answer>```json[{"bbox_2d": [x1, y1, x2, y2], "label": "region name", "order": "reading order"}]```</answer>."""
|
|
|
|
|
|
|
| 35 |
)
|
| 36 |
|
| 37 |
# --- 2. Load Model and Processor ---
|
|
|
|
| 38 |
print("Loading model and processor, this may take a moment...")
|
| 39 |
try:
|
| 40 |
model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
|
|
|
|
| 48 |
print(f"Error loading model: {e}")
|
| 49 |
exit()
|
| 50 |
|
|
|
|
| 51 |
# --- 3. Core Inference and Visualization Function ---
|
|
|
|
| 52 |
@GPU
|
| 53 |
def analyze_and_visualize_layout(input_image: Image.Image, prompt: str, temperature: float, top_p: float, progress=gr.Progress(track_tqdm=True)):
|
| 54 |
"""
|
| 55 |
+
Takes an image and model parameters, runs inference, and returns a visualized image and raw text output.
|
| 56 |
"""
|
| 57 |
if input_image is None:
|
| 58 |
return None, "Please upload an image first."
|
| 59 |
|
| 60 |
progress(0, desc="Resizing image...")
|
|
|
|
| 61 |
image = input_image.resize(TARGET_SIZE)
|
| 62 |
+
image = image.convert("RGBA")
|
| 63 |
|
| 64 |
messages = [
|
| 65 |
{"role": "user", "content": [
|
| 66 |
{"type": "image", "image": image},
|
| 67 |
+
{"type": "text", "text": prompt} # Use the configurable prompt
|
| 68 |
]}
|
| 69 |
]
|
| 70 |
+
|
| 71 |
progress(0.2, desc="Preparing model inputs...")
|
| 72 |
text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 73 |
inputs = processor(text=[text], images=[image], padding=True, return_tensors="pt").to(model.device)
|
| 74 |
|
| 75 |
progress(0.5, desc="Generating layout data...")
|
| 76 |
with torch.no_grad():
|
| 77 |
+
# Pass new parameters to the model generation
|
| 78 |
+
output_ids = model.generate(
|
| 79 |
+
**inputs,
|
| 80 |
+
max_new_tokens=4096,
|
| 81 |
+
do_sample=True, # Must be True for temperature/top_p to have an effect
|
| 82 |
+
temperature=temperature,
|
| 83 |
+
top_p=top_p
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
output_text = processor.batch_decode(
|
| 87 |
output_ids[:, inputs.input_ids.shape[1]:], skip_special_tokens=True
|
| 88 |
)[0]
|
| 89 |
|
| 90 |
progress(0.8, desc="Parsing and visualizing results...")
|
| 91 |
try:
|
| 92 |
+
json_match = re.search(r"```json(.*?)```", output_text, re.DOTALL)
|
| 93 |
json_str = json_match.group(1).strip() if json_match else output_text.strip()
|
| 94 |
results = json.loads(json_str)
|
| 95 |
except (json.JSONDecodeError, AttributeError):
|
|
|
|
| 108 |
label = item.get("label", "other")
|
| 109 |
order = item.get("order", "")
|
| 110 |
|
| 111 |
+
if not bbox or len(bbox) != 4: continue
|
|
|
|
| 112 |
|
| 113 |
fill_color_rgba = LABEL_COLORS.get(label, LABEL_COLORS["other"])
|
| 114 |
solid_color_rgb = fill_color_rgba[:3]
|
|
|
|
| 118 |
tag_text = f"{order}: {label}"
|
| 119 |
tag_bbox = draw.textbbox((0, 0), tag_text, font=font)
|
| 120 |
tag_w, tag_h = tag_bbox[2] - tag_bbox[0], tag_bbox[3] - tag_bbox[1]
|
| 121 |
+
|
| 122 |
tag_bg_box = [bbox[0], bbox[1], bbox[0] + tag_w + 10, bbox[1] + tag_h + 6]
|
| 123 |
draw.rectangle(tag_bg_box, fill=solid_color_rgb)
|
| 124 |
draw.text((bbox[0] + 5, bbox[1] + 3), tag_text, font=font, fill="white")
|
| 125 |
|
| 126 |
visualized_image = Image.alpha_composite(image, overlay).convert("RGB")
|
|
|
|
| 127 |
return visualized_image, output_text
|
| 128 |
|
|
|
|
| 129 |
def clear_outputs():
|
| 130 |
+
"""Helper function to clear the output fields."""
|
| 131 |
return None, None
|
| 132 |
|
|
|
|
| 133 |
# --- 4. Gradio User Interface ---
|
|
|
|
| 134 |
with gr.Blocks(theme=gr.themes.Glass(), title="Academic Paper Layout Detection") as demo:
|
| 135 |
+
|
| 136 |
gr.Markdown("# 📄 Academic Paper Layout Detection")
|
| 137 |
gr.Markdown(
|
| 138 |
"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. "
|
| 139 |
"Upload a document image to begin."
|
|
|
|
| 140 |
"\n> **Please note:** All uploaded images are automatically resized to 924x1204 pixels to meet the model's input requirements."
|
| 141 |
)
|
| 142 |
gr.Markdown("<hr>")
|
|
|
|
| 144 |
with gr.Row():
|
| 145 |
with gr.Column(scale=4):
|
| 146 |
input_image = gr.Image(type="pil", label="Upload Document Image", height=700)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
with gr.Column(scale=5):
|
| 148 |
output_image = gr.Image(type="pil", label="Analyzed Layout", interactive=False, height=700)
|
| 149 |
+
|
| 150 |
with gr.Row():
|
| 151 |
+
analyze_btn = gr.Button("✨ Analyze Layout", variant="primary", scale=1)
|
| 152 |
+
|
| 153 |
+
# --- NEW: Advanced Settings Panel ---
|
| 154 |
+
with gr.Accordion("Advanced Settings", open=False):
|
| 155 |
+
prompt_textbox = gr.Textbox(
|
| 156 |
+
label="Prompt",
|
| 157 |
+
value=DEFAULT_PROMPT,
|
| 158 |
+
lines=5,
|
| 159 |
+
info="The prompt used to instruct the model."
|
| 160 |
+
)
|
| 161 |
+
temp_slider = gr.Slider(
|
| 162 |
+
minimum=0.0,
|
| 163 |
+
maximum=2.0,
|
| 164 |
+
step=0.05,
|
| 165 |
+
value=0.7,
|
| 166 |
+
label="Temperature",
|
| 167 |
+
info="Controls randomness. Higher values mean more random outputs."
|
| 168 |
+
)
|
| 169 |
+
top_p_slider = gr.Slider(
|
| 170 |
+
minimum=0.0,
|
| 171 |
+
maximum=1.0,
|
| 172 |
+
step=0.05,
|
| 173 |
+
value=0.9,
|
| 174 |
+
label="Top-p (Nucleus Sampling)",
|
| 175 |
+
info="Filters a cumulative probability mass. Lower values are less random."
|
| 176 |
+
)
|
| 177 |
|
| 178 |
output_text = gr.Textbox(label="Model Raw Output", lines=8, interactive=False, visible=True)
|
| 179 |
|
|
|
|
| 180 |
gr.Examples(
|
| 181 |
+
examples=[["page_2.png"], ["page_3.png"], ["page_5.png"], ["page_13.png"]],
|
| 182 |
+
inputs=[input_image],
|
|
|
|
|
|
|
| 183 |
label="Examples (Click to Run)",
|
| 184 |
+
# Examples now only populate the image input. The user clicks "Analyze" to run with current settings.
|
| 185 |
)
|
| 186 |
+
|
| 187 |
gr.Markdown("<p style='text-align:center; color:grey;'>Powered by the Latex2Layout dataset generated by Feijiang Han</p>")
|
| 188 |
|
| 189 |
# --- Event Handlers ---
|
| 190 |
analyze_btn.click(
|
| 191 |
fn=analyze_and_visualize_layout,
|
| 192 |
+
inputs=[input_image, prompt_textbox, temp_slider, top_p_slider], # Add new inputs
|
| 193 |
outputs=[output_image, output_text]
|
| 194 |
)
|
| 195 |
+
|
| 196 |
input_image.upload(fn=clear_outputs, inputs=None, outputs=[output_image, output_text])
|
| 197 |
input_image.clear(fn=clear_outputs, inputs=None, outputs=[output_image, output_text])
|
| 198 |
|
|
|
|
| 199 |
# --- 5. Launch the Application ---
|
|
|
|
| 200 |
if __name__ == "__main__":
|
| 201 |
demo.launch()
|