
2026/06/23 20:35
無制限 OCR:ワンショット・ロングホライズン解析
RSS: https://news.ycombinator.com/rss
要約▶
Japanese Translation:
論文集「Unlimited-OCR Works」は、Deepseek-OCR を凌駕し、単一画像と複雑なマルチページ PDF 両方をサポートする ModelScope 上にホストされたモデルを発表しています。同プロジェクトは Deepseek-OCR、Deepseek-OCR-2、PaddleOCR の基礎技術をAcknowledgments に明記し、arXiv(eprint: 2606.23050)に参照リストを公開しています。推論は厳密にバージョン管理されており、Python 3.12.3、CUDA 12.9、および torch==2.10.0、transformers==4.57.1 など特定のパッケージのバージョンが必要となります。実装オプションとしては、Huggingface AutoModels が
gundam(base_size=1024)および base モードの両方で torch.bfloat16 をサポートするか、32k コンテキスト長とファサイト注意力機構を備えた SGLang サーバー上で動作し、カスタムログイットプロセッサを使用して DeepSeek OCR の制約を管理するものがあります。本システムは OpenAI 互換エンドポイント 0.0.0.0:10000 を介してストリーミング API を提供し、ngram ウィンドウの構成、および画像と PDF の同時処理のための並列推論機能を提供します。高度なドキュメント知能の全潜力を発揮するには、これらの厳格な前提条件に対するハードウェアを慎重に検証する必要があります。
Text to translate:
The paper "Unlimited-OCR Works" introduces a model hosted on ModelScope that pushes beyond Deepseek-OCR to support both single images and complex multi-page PDFs, specifically targeting one-shot long-horizon parsing tasks. The project, contributed by teams including Deepseek-OCR, acknowledges foundations in Deepseek-OCR, Deepseek-OCR-2, and PaddleOCR, with a citation list provided on arXiv (eprint: 2606.23050). Inference is strictly versioned, requiring Python 3.12.3, CUDA 12.9, and specific package versions such as torch==2.10.0 and transformers==4.57.1. Implementation options include Huggingface AutoModels supporting
torch.bfloat16 in both gundam (base_size=1024) and base modes, or an SGLang server running on fa3 attention with 32k context length and custom logit processors to manage DeepSeek OCR constraints. The system offers a streaming API via OpenAI-compatible endpoints at 0.0.0.0:10000, configurable ngram windows, and batch inference capabilities via infer.py for concurrent processing of images and PDFs. Successful deployment requires careful validation of hardware against these strict prerequisites to leverage the full potential of advanced document intelligence.本文
ワンショット・長文脈解読の時代へようこそ
リリース日: 2026 年 6 月 23 日
- 📄 論文: arXiv で利用可能
- 🤝 モデル: ModelScope コミュニティにて公開済み(支援に感謝)
- 🚀 進化: Deepseek-OCR の性能向上を目指し、Unlimited-OCR を発表
推論(Inference)
Transformers
NVIDIA GPU 上で Huggingface Transformers を使用した推論方法です。
検証環境:Python 3.12.3 + CUDA 12.9
必要なパッケージは以下の通りです:
torch==2.10.0torchvision==0.25.0transformers==4.57.1Pillow==12.1.1matplotlib==3.10.8einops==0.8.2addict==2.4.0easydict==1.13pymupdf==1.27.2.2psutil==7.2.2
実装例
import os import torch from transformers import AutoModel, AutoTokenizer model_name = 'baidu/Unlimited-OCR' # トークネライザーとモデルの読み込み tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True) model = AutoModel.from_pretrained( model_name, trust_remote_code=True, use_safetensors=True, torch_dtype=torch.bfloat16, ) # モデルを評価モードに設定し、GPU へ移します model = model.eval().cuda() # ── シングル画像処理(2 つの構成をサポート) ── # gundam: base_size=1024, image_size=640, crop_mode=True # base: base_size=1024, image_size=1024, crop_mode=False model.infer( tokenizer, prompt='<image>document parsing.', # プロンプト image_file='your_image.jpg', # 入力画像ファイル output_path='your/output/dir', # 出力ディレクトリ base_size=1024, image_size=640, crop_mode=True, # gundam モードの場合:True max_length=32768, no_repeat_ngram_size=35, ngram_window=128, save_results=True, # 結果を保存するか ) # ── マルチページ/PDF は base 構成(image_size=1024)のみを使用します ── model.infer_multi( tokenizer, prompt='<image>Multi page parsing.', image_files=['page1.png', 'page2.png', 'page3.png'], # ページリスト output_path='your/output/dir', image_size=1024, # base モード:1024 max_length=32768, no_repeat_ngram_size=35, ngram_window=1024, save_results=True, ) # ── PDF 処理(ページを画像に変換してからマルチページ推論) ── import tempfile, fitz # PyMuPDF ライブラリを使用 def pdf_to_images(pdf_path, dpi=300): doc = fitz.open(pdf_path) tmp_dir = tempfile.mkdtemp(prefix='pdf_ocr_') mat = fitz.Matrix(dpi / 72, dpi / 72) # DPI に基づく変換行列 paths = [] for i, page in enumerate(doc): out = os.path.join(tmp_dir, f'page_{i+1:04d}.png') page.get_pixmap(matrix=mat).save(out) paths.append(out) doc.close() return paths # PDF を画像リストに変換して推論を実行 model.infer_multi( tokenizer, prompt='<image>Multi page parsing.', image_files=pdf_to_images('your_doc.pdf', dpi=300), output_path='your/output/dir', image_size=1024, max_length=32768, no_repeat_ngram_size=35, ngram_window=1024, save_results=True, )
SGLang
SGLang 環境を準備します。推奨手法として
uv を用いた仮想環境の構築と、以下のパッケージインストールを行ってください:
- ローカルの SGLang wheel パッケージ
(バージョンは環境に合わせて調整必要)kernels==0.11.7- PDF 変換に使用する
pymupdf==1.27.2.2
インストール手順
# 仮想環境の作成とアクティベーション(Python 3.12 推奨) uv venv --python 3.12 source .venv/bin/activate # SGLang ウィールのインストール uv pip install wheel/sglang-0.0.0.dev11416+g92e8bb79e-py3-none-any.whl # Kernels パッケージの固定 uv pip install kernels==0.11.7 # PDF 変換ライブラリのインストール uv pip install pymupdf==1.27.2.2
サーバー起動と API リクエスト
SGLang サーバーを起動します:
python -m sglang.launch_server \ --model baidu/Unlimited-OCR \ --served-model-name Unlimited-OCR \ --attention-backend fa3 \ --page-size 1 \ --mem-fraction-static 0.8 \ --context-length 32768 \ --enable-custom-logit-processor \ --disable-overlap-schedule \ --skip-server-warmup \ --host 0.0.0.0 \ --port 10000
OpenAI 互換 API を使用してストリーミングリクエストを送信する Python スクリプト例:
import base64 import json import os import tempfile import fitz import requests from sglang.srt.sampling.custom_logit_processor import DeepseekOCRNoRepeatNGramLogitProcessor server_url = "http://127.0.0.1:10000" session = requests.Session() session.trust_env = False # PDF から画像を抽出するヘルパー関数(Transformers 版と同等のロジック) def pdf_to_images(pdf_path, dpi=300): doc = fitz.open(pdf_path) tmp_dir = tempfile.mkdtemp(prefix="pdf_ocr_") mat = fitz.Matrix(dpi / 72, dpi / 72) image_paths = [] for i, page in enumerate(doc): image_path = os.path.join(tmp_dir, f"page_{i + 1:04d}.png") page.get_pixmap(matrix=mat).save(image_path) image_paths.append(image_path) doc.close() return image_paths # 画像を base64 エンコードして API 形式に変換する関数 def encode_image(image_path): ext = os.path.splitext(image_path)[1].lower() mime = "image/jpeg" if ext in (".jpg", ".jpeg") else f"image/{ext.lstrip('.')}" with open(image_path, "rb") as f: data = base64.b64encode(f.read()).decode("utf-8") return {"type": "image_url", "image_url": {"url": f"data:{mime};base64,{data}"}} # プロンプトと画像リストを組み合わせたメッセージ構造を構築する関数 def build_content(prompt, image_paths): return [{"type": "text", "text": prompt}] + [encode_image(path) for path in image_paths] # メインの推論処理を実行する関数 def generate(prompt, image_paths, image_mode, ngram_window): payload = { "model": "Unlimited-OCR", "messages": [{"role": "user", "content": build_content(prompt, image_paths)}], "temperature": 0, "skip_special_tokens": False, "images_config": {"image_mode": image_mode}, # 画像処理モード(gundam / base) "custom_logit_processor": DeepseekOCRNoRepeatNGramLogitProcessor.to_str(), "custom_params": { "ngram_size": 35, "window_size": ngram_window, }, "stream": True, # ストリーミング出力を有効化 } response = session.post( f"{server_url}/v1/chat/completions", headers={"Content-Type": "application/json"}, data=json.dumps(payload), timeout=1200, stream=True, ) response.raise_for_status() chunks = [] # ストリーミング応答の逐次処理 for line in response.iter_lines(chunk_size=1, decode_unicode=True): if not line or not line.startswith("data: "): continue data = line[len("data: "):] if data == "[DONE]": break event = json.loads(data) delta = event["choices"][0].get("delta", {}).get("content", "") if delta: print(delta, end="", flush=True) chunks.append(delta) print() return "".join(chunks) # シングル画像処理:gundam モードの例 generate("document parsing.", ["your_image.jpg"], image_mode="gundam", ngram_window=128) # マルチ画像処理:base モードのみ対応 generate("Multi page parsing.", ["page1.png", "page2.png"], image_mode="base", ngram_window=1024) # PDF 処理:base モードのみ対応(事前に変換) generate("Multi page parsing.", pdf_to_images("your_doc.pdf", dpi=300), image_mode="base", ngram_window=1024)
バッチ推論
infer.py を使用して、SGLang サーバーを自動的に起動し、画像ディレクトリまたは PDF ファイルに対して並列(コンカレント)リクエストを送信します。
画像ディレクトリの処理:
python infer.py \ --image_dir ./examples/images \ --output_dir ./outputs \ --concurrency 8 \ --image_mode gundam
PDF ページの処理:
python infer.py \ --pdf ./examples/document.pdf \ --output_dir ./outputs \ --concurrency 8 \ --image_mode gundam
有用なオプション:
:ローカルのパスまたは Hugging Face モデル ID--model_dir baidu/Unlimited-OCR
:使用したい CUDA デバイス(例:--gpu 0
の設定用)CUDA_VISIBLE_DEVICES--server_log ./log/sglang_server.log
引用文献
@misc{yin26unlimitedocrworks, title={Unlimited OCR Works}, author={Youyang Yin and Huanhuan Liu and YY and Qunyi Xie and Chaorun Liu and Shiqi Yang and Shaohua Wang and Zhanlong Liu and Hao Zou and Jinyue Chen and Shu Wei and Jingjing Wu and Mingxin Huang and Zhen Wu and Guibin Wang and Tengyu Du and Lei Jia}, year={2026}, eprint={2606.23050}, archivePrefix={arXiv}, primaryClass={cs.CV}, url={https://arxiv.org/abs/2606.23050} }