# Copyright (c) 2026 Niyredra. All rights reserved. """MinerU-Diffusion 文档图片识别演示。""" import spaces import torch import gradio as gr from pathlib import Path from PIL import Image from transformers import AutoModel, AutoProcessor, AutoTokenizer MODEL_ID = "opendatalab/MinerU-Diffusion-V1-0320-2.5B" MODEL_REVISION = "c1a5a0c17288bb0623b00d6bbfed17428e597acd" TASK_PROMPTS = { "text": "\nText Recognition:", "table": "\nTable Recognition:", "formula": "\nFormula Recognition:", "layout": "\nLayout Analysis:", } STOP_STRINGS = ("<|endoftext|>", "<|im_end|>") MODEL_OPTIONS = {"revision": MODEL_REVISION, "trust_remote_code": True} # 在 ZeroGPU 主进程中加载,推理请求到达时再分配显卡。 tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, **MODEL_OPTIONS) processor = AutoProcessor.from_pretrained(MODEL_ID, use_fast=False, **MODEL_OPTIONS) model = AutoModel.from_pretrained( MODEL_ID, torch_dtype=torch.bfloat16, low_cpu_mem_usage=True, **MODEL_OPTIONS, ).eval().to("cuda") @spaces.GPU(duration=180) def recognize(image: str, task: str) -> str: """按 task 识别 image 路径中的文档图片,返回模型原文;无图片或类型无效时提示错误。""" if not image: raise gr.Error("请先上传图片,或选择下方示例。") if task not in TASK_PROMPTS: raise gr.Error("请选择有效的识别类型。") # 版面识别沿用作者演示的 1036×1036 输入预处理。 model_image = image if task == "layout": with Image.open(image) as source: model_image = source.convert("RGB").resize((1036, 1036), Image.Resampling.LANCZOS) messages = [ {"role": "system", "content": [{"type": "text", "text": "You are a helpful assistant."}]}, {"role": "user", "content": [ {"type": "image", "image": image}, {"type": "text", "text": TASK_PROMPTS[task]}, ]}, ] prompt = processor.apply_chat_template(messages, add_generation_prompt=True) if isinstance(prompt, tuple): prompt = prompt[0] inputs = processor( images=[model_image], text=prompt, truncation=True, max_length=4096, return_tensors="pt" ) grid = inputs.get("image_grid_thw") if grid is not None: grid = grid.to(torch.long).to("cuda") with torch.no_grad(): output = model.generate( pixel_values=inputs["pixel_values"].to(torch.bfloat16).to("cuda"), image_grid_thw=grid, input_ids=inputs["input_ids"].to(torch.long).to("cuda"), mask_token_id=tokenizer.convert_tokens_to_ids("<|MASK|>"), denoising_steps=32, gen_length=1024, block_length=32, temperature=1.0, remasking_strategy="low_confidence_dynamic", dynamic_threshold=0.95, tokenizer=tokenizer, stopping_criteria=list(STOP_STRINGS), ) output_ids = output[0] if isinstance(output, tuple) else output text = tokenizer.decode(output_ids[0], skip_special_tokens=False) for stop in STOP_STRINGS: text = text.split(stop, 1)[0] return text.strip() sample_dir = Path(__file__).parent / "examples" with gr.Blocks(title="MinerU Diffusion OCR") as demo: gr.Markdown( "# MinerU Diffusion OCR\n" "上传一张文档图片,识别文字、表格、公式或页面布局。长页面可以裁剪后分次识别。 " "版面识别输出 0–1000 的归一化坐标。 " "[模型说明](https://huggingface.co/opendatalab/MinerU-Diffusion-V1-0320-2.5B)" ) with gr.Row(): with gr.Column(): image_input = gr.Image(label="文档图片", type="filepath", sources=["upload", "clipboard"]) task_input = gr.Radio( choices=[("文字", "text"), ("表格", "table"), ("公式", "formula"), ("版面", "layout")], value="text", label="识别类型", ) run_button = gr.Button("开始识别", variant="primary") with gr.Column(): result = gr.Textbox(label="识别结果", lines=20, show_copy_button=True) gr.Examples( examples=[ [str(sample_dir / "text.png"), "text"], [str(sample_dir / "table.png"), "table"], [str(sample_dir / "formula.png"), "formula"], ], inputs=[image_input, task_input], label="试用示例", ) run_button.click(fn=recognize, inputs=[image_input, task_input], outputs=result) if __name__ == "__main__": demo.queue().launch(mcp_server=True, show_error=True)