Spaces:
Running on Zero
Running on Zero
Download app.py from hugging-apps/docseam: direct link, hf CLI and curl.
- Browser
- Download file 13.5 kB
-
https://huggingface.co/spaces/hugging-apps/docseam/resolve/main/app.py
- Command line
-
hf download hf://spaces/hugging-apps/docseam/app.py
-
curl -L -o app.py https://huggingface.co/spaces/hugging-apps/docseam/resolve/main/app.py
13.5 kB
| """DocSEAM: Bidirectional Cross-Page Encoding for Multi-Page Document Understanding. | |
| A Gradio demo for the mossbee/DocSEAM checkpoint (Qwen3.5-9B + injectable | |
| cross-page encoder). Upload one or more document pages in reading order, ask | |
| a question, and DocSEAM enriches each page's visual features with context | |
| from its immediate neighbors before answering. | |
| Reference implementation: https://github.com/mossbee/DocSEAM (infer.py, | |
| visualize_attention.py). | |
| """ | |
| import tempfile | |
| import threading | |
| import time | |
| from pathlib import Path | |
| import spaces # must precede any torch/CUDA-touching import | |
| import gradio as gr | |
| import matplotlib | |
| import numpy as np | |
| import torch | |
| from PIL import Image | |
| from qwen_vl_utils import process_vision_info | |
| from transformers import AutoModelForImageTextToText, AutoProcessor | |
| matplotlib.use("Agg") | |
| import matplotlib.pyplot as plt | |
| MODEL_ID = "mossbee/DocSEAM" | |
| HERE = Path(__file__).resolve().parent | |
| # --- Model load (module scope, eager .to("cuda")) ---------------------------- | |
| processor = AutoProcessor.from_pretrained(MODEL_ID) | |
| model = AutoModelForImageTextToText.from_pretrained( | |
| MODEL_ID, dtype=torch.bfloat16, trust_remote_code=True | |
| ) | |
| model = model.to("cuda").eval() | |
| processor.tokenizer.padding_side = "left" | |
| ENCODER = model.model.docseam | |
| SALIENCE_KEYS = ("s_send_to_next", "s_recv_from_prev", "s_send_to_prev", "s_recv_from_next") | |
| # record_salience + _last_salience_records are encoder-global state; serialize | |
| # them so concurrent requests don't leak records into each other's heatmaps. | |
| _SALIENCE_LOCK = threading.Lock() | |
| # --- Reference-path inference (ports docseam-repo/infer.py 1:1) -------------- | |
| def _build_content(image_paths, question): | |
| """Build chat content the way docseam-repo/infer.py::prepare_inputs does.""" | |
| pages = [ | |
| { | |
| "type": "image", | |
| "image": f"file://{Path(p).resolve()}", | |
| "min_pixels": 32768, | |
| "max_pixels": 524288, | |
| } | |
| for p in image_paths | |
| ] | |
| parts = question.split("<image>") | |
| if len(parts) == 1: | |
| return [*pages, {"type": "text", "text": question}] | |
| if len(parts) - 1 != len(pages): | |
| raise ValueError( | |
| f"The question contains {len(parts) - 1} '<image>' placeholder(s) " | |
| f"but {len(pages)} page image(s) were provided. Each '<image>' " | |
| "placeholder requires exactly one page image." | |
| ) | |
| content = [] | |
| for index, part in enumerate(parts): | |
| if part: | |
| content.append({"type": "text", "text": part}) | |
| if index < len(pages): | |
| content.append(pages[index]) | |
| return content | |
| def _decode_answer(text): | |
| """Trim generation at chat markers, like docseam-repo/infer.py::decode_answer.""" | |
| for marker in ("<|im_end|>", "<|im_start|>", "\nuser\n", "\nassistant\n", "\nUser\n", "\nAssistant\n"): | |
| if marker in text: | |
| return text.split(marker, 1)[0].rstrip("\n") | |
| return text.rstrip("\n") | |
| def _center_page_index(num_pages): | |
| """Index of the page whose triplet is shown in the salience heatmap.""" | |
| return min(max((num_pages - 1) // 2, 0), num_pages - 1) | |
| def _salience_heatmap(image_paths, page_grids, records, center_idx): | |
| """Overlay the averaged directional salience gates on the center triplet. | |
| Mirrors docseam-repo/visualize_attention.py: average the center page's | |
| records across DocSEAM layers, reshape each gate to its page grid, | |
| normalize 2-98 percentile, and paint a turbo heatmap over the pages. | |
| """ | |
| selected = [r for r in records if r["curr_page_index"] == center_idx] | |
| if not selected: | |
| return None | |
| n_prev, n_curr, n_next = selected[0]["n_prev"], selected[0]["n_curr"], selected[0]["n_next"] | |
| salience = { | |
| key: torch.stack([torch.sigmoid(r[key]).float() for r in selected]).mean(dim=0).numpy() | |
| for key in SALIENCE_KEYS | |
| } | |
| # Boundary pages fall back to themselves (self-fallback in DocSEAM.forward), | |
| # so prev/next grids equal the center grid there — same as the module does. | |
| h_prev, w_prev = page_grids[center_idx - 1] if center_idx > 0 else page_grids[center_idx] | |
| h_curr, w_curr = page_grids[center_idx] | |
| h_next, w_next = page_grids[center_idx + 1] if center_idx < len(page_grids) - 1 else page_grids[center_idx] | |
| prev_send = salience["s_send_to_next"][:n_prev].reshape(h_prev, w_prev) | |
| curr_recv_p = salience["s_recv_from_prev"][n_prev : n_prev + n_curr].reshape(h_curr, w_curr) | |
| curr_recv_n = salience["s_recv_from_next"][n_prev : n_prev + n_curr].reshape(h_curr, w_curr) | |
| next_send = salience["s_send_to_prev"][n_prev + n_curr : n_prev + n_curr + n_next].reshape(h_next, w_next) | |
| n_pages = len(image_paths) | |
| prev_idx = max(center_idx - 1, 0) | |
| next_idx = min(center_idx + 1, n_pages - 1) | |
| panels = [ | |
| (prev_idx, prev_send, f"Page {prev_idx + 1} → next", "what this page sends forward"), | |
| (center_idx, curr_recv_p, f"Page {center_idx + 1} ← prev", "what the center reads from previous"), | |
| (center_idx, curr_recv_n, f"Page {center_idx + 1} ← next", "what the center reads from next"), | |
| (next_idx, next_send, f"Page {next_idx + 1} → prev", "what this page sends back"), | |
| ] | |
| values = np.concatenate([p[1].reshape(-1) for p in panels]) | |
| vmin, vmax = np.percentile(values, [2, 98]) | |
| if vmax <= vmin: | |
| vmin, vmax = float(values.min()), float(values.max()) | |
| if vmax <= vmin: | |
| vmax = vmin + 1e-6 | |
| fig, axes = plt.subplots(2, len(panels), figsize=(5 * len(panels), 10), constrained_layout=True) | |
| if len(panels) == 1: | |
| axes = axes.reshape(2, 1) | |
| overlay = None | |
| for col, (img_idx, heatmap, title, subtitle) in enumerate(panels): | |
| img = Image.open(image_paths[img_idx]).convert("RGB") | |
| axes[0, col].imshow(img) | |
| axes[0, col].set_title(title, fontsize=11) | |
| axes[0, col].axis("off") | |
| axes[1, col].imshow(img) | |
| rel = np.clip((heatmap - vmin) / (vmax - vmin), 0.0, 1.0) | |
| hm = Image.fromarray(rel.astype(np.float32)).resize(img.size, Image.BILINEAR) | |
| overlay = axes[1, col].imshow(np.array(hm), cmap="turbo", alpha=0.62, vmin=0.0, vmax=1.0) | |
| axes[1, col].set_title(subtitle, fontsize=9) | |
| axes[1, col].axis("off") | |
| fig.colorbar( | |
| overlay, | |
| ax=axes[1, :].ravel().tolist(), | |
| fraction=0.025, | |
| pad=0.02, | |
| label="relative salience gate strength", | |
| ) | |
| out_dir = tempfile.mkdtemp(prefix="docseam_salience_") | |
| out_path = Path(out_dir) / "salience.png" | |
| fig.savefig(out_path, dpi=110) | |
| plt.close(fig) | |
| return str(out_path) | |
| # --- GPU inference ----------------------------------------------------------- | |
| def answer_question( | |
| pages, | |
| question, | |
| show_salience=True, | |
| max_new_tokens=256, | |
| progress=gr.Progress(track_tqdm=True), | |
| ): | |
| """Answer a question over an ordered list of document pages. | |
| Args: | |
| pages: one or more page images in document order (first = first page). | |
| question: the question; a literal "<image>" inside it places pages | |
| at that point in the prompt, otherwise pages come first. | |
| show_salience: also render the cross-page salience heatmap for the | |
| center page's triplet. | |
| max_new_tokens: generation budget for the answer. | |
| Returns: | |
| Tuple of (answer text, elapsed seconds, salience heatmap or None). | |
| """ | |
| if not pages: | |
| raise gr.Error("Please upload at least one page image.") | |
| if not question or not question.strip(): | |
| raise gr.Error("Please enter a question.") | |
| image_paths = [p if isinstance(p, str) else p.name for p in pages] | |
| messages = [{"role": "user", "content": _build_content(image_paths, question.strip())}] | |
| prompt = processor.apply_chat_template( | |
| messages, tokenize=False, add_generation_prompt=True, enable_thinking=False | |
| ) | |
| images, _ = process_vision_info(messages, image_patch_size=processor.image_processor.patch_size) | |
| inputs = processor(text=[prompt], images=images, padding=True, return_tensors="pt").to(model.device) | |
| tokenizer = processor.tokenizer | |
| _SALIENCE_LOCK.acquire() | |
| try: | |
| ENCODER.record_salience = bool(show_salience) | |
| t0 = time.perf_counter() | |
| with torch.inference_mode(): | |
| tokens = model.generate( | |
| **inputs, | |
| max_new_tokens=int(max_new_tokens), | |
| do_sample=False, | |
| eos_token_id=tokenizer.eos_token_id, | |
| pad_token_id=tokenizer.pad_token_id, | |
| ) | |
| elapsed = time.perf_counter() - t0 | |
| # Snapshot the records now; page grids/tensors are detached CPU tensors. | |
| records = list(ENCODER._last_salience_records) if show_salience else [] | |
| ENCODER.record_salience = False | |
| finally: | |
| _SALIENCE_LOCK.release() | |
| text = _decode_answer( | |
| processor.decode(tokens[0, inputs.input_ids.shape[1]:], skip_special_tokens=False, clean_up_tokenization_spaces=False) | |
| ) | |
| heatmap = None | |
| if records: | |
| try: | |
| merge = model.model.visual.spatial_merge_size | |
| page_grids = [ | |
| (int(h) // merge, int(w) // merge) for _, h, w in inputs.image_grid_thw.tolist() | |
| ] | |
| heatmap = _salience_heatmap(image_paths, page_grids, records, _center_page_index(len(image_paths))) | |
| except Exception as exc: # heatmap is best-effort; never fail the answer | |
| print(f"salience heatmap failed: {exc!r}") | |
| return text, round(elapsed, 2), heatmap | |
| # --- UI ---------------------------------------------------------------------- | |
| CSS = """ | |
| #col-container { max-width: 1200px; margin: 0 auto; } | |
| .dark .gradio-container { color: var(--body-text-color); } | |
| """ | |
| with gr.Blocks(title="DocSEAM") as demo: | |
| with gr.Column(elem_id="col-container"): | |
| gr.Markdown( | |
| """ | |
| # DocSEAM: Bidirectional Cross-Page Encoding for Multi-Page Document Understanding | |
| Ask questions across multi-page documents. DocSEAM enriches each page's visual | |
| features with context from its **neighboring pages** via center-anchored masked | |
| attention and directional salience gates — without inflating the visual token count. | |
| [Paper](https://arxiv.org/abs/2611.34420) · [Project page](https://mossbee.github.io/projects/DocSEAM/) · [Code](https://github.com/mossbee/DocSEAM) · [Model](https://huggingface.co/mossbee/DocSEAM) | |
| """ | |
| ) | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| pages_in = gr.Files( | |
| label="Document pages (in reading order)", | |
| file_count="multiple", | |
| file_types=["image"], | |
| type="filepath", | |
| ) | |
| question_in = gr.Textbox( | |
| label="Question", | |
| placeholder="e.g. How many parallel attention heads are used in the model?", | |
| lines=3, | |
| ) | |
| show_salience_in = gr.Checkbox( | |
| label="Show cross-page salience heatmap", | |
| value=True, | |
| ) | |
| run_btn = gr.Button("Ask", variant="primary") | |
| with gr.Accordion("Advanced settings", open=False): | |
| max_new_tokens_in = gr.Slider( | |
| minimum=16, maximum=1024, value=256, step=16, | |
| label="Max new tokens", | |
| ) | |
| with gr.Column(scale=1): | |
| answer_out = gr.Textbox(label="Answer", lines=4) | |
| elapsed_out = gr.Number(label="Inference time (s)", precision=2) | |
| salience_out = gr.Image( | |
| label="Cross-page salience gates (center triplet)", | |
| type="filepath", | |
| ) | |
| gr.Examples( | |
| examples=[ | |
| [ | |
| [ | |
| str(HERE / "examples/1706.03762v7_page-0004.jpg"), | |
| str(HERE / "examples/1706.03762v7_page-0005.jpg"), | |
| str(HERE / "examples/1706.03762v7_page-0006.jpg"), | |
| ], | |
| "How many parallel attention heads are used in the model? Answer with only the number.", | |
| True, | |
| 128, | |
| ], | |
| [ | |
| [ | |
| str(HERE / "examples/1706.03762v7_page-0004.jpg"), | |
| str(HERE / "examples/1706.03762v7_page-0005.jpg"), | |
| str(HERE / "examples/1706.03762v7_page-0006.jpg"), | |
| ], | |
| "Page 4:\n<image>\nPage 5:\n<image>\nPage 6:\n<image>\nRead the table continuously across the boundary from Page 4 into Page 5, then use Page 6 only as the following context page.", | |
| True, | |
| 256, | |
| ], | |
| ], | |
| inputs=[pages_in, question_in, show_salience_in, max_new_tokens_in], | |
| outputs=[answer_out, elapsed_out, salience_out], | |
| fn=answer_question, | |
| cache_examples=True, | |
| cache_mode="lazy", | |
| examples_per_page=2, | |
| ) | |
| run_btn.click( | |
| answer_question, | |
| inputs=[pages_in, question_in, show_salience_in, max_new_tokens_in], | |
| outputs=[answer_out, elapsed_out, salience_out], | |
| api_name="answer", | |
| ) | |
| demo.launch(theme=gr.themes.Citrus(), css=CSS, mcp_server=True) | |