Commit ·
aad164c
1
Parent(s): d28bb20
Add DeepSeek-OCR-2 vLLM script (rewrite from fixed v1 pattern)
Browse filesRewrites the broken draft (base64/llm.chat/resolution modes) to use the
proven v1 pattern: llm.generate() with PIL images + NGramPerReqLogitsProcessor.
Key v2 change: limit_mm_per_prompt={"image": 1} for the new architecture.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
23 unmodified lines24252627282930313233343536373 unmodified lines41424344454647484950515253542 unmodified lines57585960616263646566676869707172737475767778798013 unmodified lines9495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321334 unmodified lines13813914014114214314414514614729 unmodified lines1771781791801811821831841851861 unmodified line18818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721829 unmodified lines2482492502512522532542 unmodified lines2572582592602612622631 unmodified line26526626726826927027127227327427527619 unmodified lines29629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533625 unmodified lines3623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913925 unmodified lines3983994004014024034044054064074082 unmodified lines41141241341441541641726 unmodified lines4444454464474484494504514524533 unmodified lines45745845946046146246316 unmodified lines48048148248348448548648748848949049149249349449549649749811 unmodified lines5105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455467 unmodified lines5545555565575585595605615625635645655662 unmodified lines56957057157257357457557657757857958058158258358458558658758858959059159259359459559659715 unmodified lines61361461561661761861962062162262362462562662762862963063163263363463563663763863954 unmodified lines69469569669769869970070170270323 unmodified lineswith Visual Causal Flow architecture) to extract text and structure as markdown,using vLLM for efficient batch processing.Tested with vLLM 0.8.5+, PyTorch 2.6.0, Transformers 4.46.3+NOTE: Uses vLLM nightly wheels. First run may take a few minutes to downloadand install dependencies.Features:- Visual Causal Flow architecture for enhanced visual encoding- Multiple resolution modes (Tiny/Small/Base/Large/Gundam)- LaTeX equation recognition- Table extraction and formatting- Document structure preservation3 unmodified lines"""import argparseimport base64import ioimport jsonimport loggingimport osimport sysfrom typing import Any, Dict, List, Unionfrom datetime import datetimeimport torchfrom datasets import load_dataset2 unmodified linesfrom toolz import partition_allfrom tqdm.auto import tqdmfrom vllm import LLM, SamplingParamslogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)# Resolution mode presets - v2 optimized for 768×768 tilesRESOLUTION_MODES = {"tiny": {"base_size": 512, "image_size": 512, "crop_mode": False},"small": {"base_size": 640, "image_size": 640, "crop_mode": False},"base": {"base_size": 1024, "image_size": 768, "crop_mode": False}, # v2 optimized"large": {"base_size": 1280, "image_size": 1024, "crop_mode": False},"gundam": {"base_size": 1024,"image_size": 768, # v2 optimized"crop_mode": True,}, # Dynamic resolution}# Prompt mode presets (compatible with both v1 and v2)PROMPT_MODES = {"document": "<image>\n<|grounding|>Convert the document to markdown.","image": "<image>\n<|grounding|>OCR this image.",13 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def make_ocr_message(image: Union[Image.Image, Dict[str, Any], str],prompt: str = "<image>\n<|grounding|>Convert the document to markdown. ",) -> List[Dict]:"""Create chat message for OCR processing."""# Convert to PIL Image if neededif isinstance(image, Image.Image):pil_img = imageelif isinstance(image, dict) and "bytes" in image:pil_img = Image.open(io.BytesIO(image["bytes"]))elif isinstance(image, str):pil_img = Image.open(image)else:raise ValueError(f"Unsupported image type: {type(image)}")# Convert to RGBpil_img = pil_img.convert("RGB")# Convert to base64 data URIbuf = io.BytesIO()pil_img.save(buf, format="PNG")data_uri = f"data:image/png;base64,{base64.b64encode(buf.getvalue()).decode()}"# Return message in vLLM formatreturn [{"role": "user","content": [{"type": "image_url", "image_url": {"url": data_uri}},{"type": "text", "text": prompt},],}]def create_dataset_card(source_dataset: str,4 unmodified linesmax_model_len: int,max_tokens: int,gpu_memory_utilization: float,resolution_mode: str,base_size: int,image_size: int,crop_mode: bool,image_column: str = "image",split: str = "train",) -> str:29 unmodified lines- **Output Column**: `markdown`- **Dataset Split**: `{split}`- **Batch Size**: {batch_size}- **Resolution Mode**: {resolution_mode}- **Base Size**: {base_size}- **Image Size**: {image_size}- **Crop Mode**: {crop_mode}- **Max Model Length**: {max_model_len:,} tokens- **Max Output Tokens**: {max_tokens:,}- **GPU Memory Utilization**: {gpu_memory_utilization:.1%}1 unmodified line## Model InformationDeepSeek-OCR-2 is a 3B parameter vision-language model featuring Visual CausalFlow architecture for more human-like visual encoding. Building on DeepSeek-OCRv1, it offers enhanced document understanding with dynamic resolution up to(0-6)×768×768 + 1×1024×1024 patches.### Key Improvements (v2)- 🧠 **Visual Causal Flow** - More human-like visual encoding architecture- 🎯 **Enhanced multi-patch** - Better processing of 768×768 tiles- 📝 **Improved structure** - Superior document hierarchy preservation- 📐 **Better layouts** - Enhanced handling of complex multi-column documents### Capabilities- 📐 **LaTeX equations** - Mathematical formulas preserved in LaTeX format- 📊 **Tables** - Extracted and formatted as HTML/markdown- 📝 **Document structure** - Headers, lists, and formatting maintained- 🖼️ **Image grounding** - Spatial layout and bounding box information- 🔍 **Complex layouts** - Multi-column and hierarchical structures- 🌍 **Multilingual** - Supports multiple languages### Resolution Modes- **Tiny** (512×512): Fast processing, 64 vision tokens- **Small** (640×640): Balanced speed/quality, 100 vision tokens- **Base** (1024×768): High quality, ~192 vision tokens ⭐ v2 optimized- **Large** (1280×1024): Maximum quality, ~328 vision tokens- **Gundam** (dynamic): Adaptive multi-tile with 768×768 patches (default)## Dataset Structure29 unmodified linesuv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/deepseek-ocr2-vllm.py \\\\{source_dataset} \\\\<output-dataset> \\\\--resolution-mode {resolution_mode} \\\\--image-column {image_column}```2 unmodified lines- **Processing Speed**: ~{num_samples / (float(processing_time.split()[0]) * 60):.1f} images/second- **Processing Method**: Batch processing with vLLM (2-3x speedup over sequential)Generated with 🤖 [UV Scripts](https://huggingface.co/uv-scripts)"""1 unmodified lineinput_dataset: str,output_dataset: str,image_column: str = "image",batch_size: int = 8, # Smaller batch size to avoid potential memory issuesmodel: str = "deepseek-ai/DeepSeek-OCR-2",resolution_mode: str = "gundam",base_size: int = None,image_size: int = None,crop_mode: bool = None,max_model_len: int = 8192,max_tokens: int = 8192,gpu_memory_utilization: float = 0.8,19 unmodified linesif HF_TOKEN:login(token=HF_TOKEN)# Determine resolution settingsif resolution_mode in RESOLUTION_MODES:mode_config = RESOLUTION_MODES[resolution_mode]final_base_size = (base_size if base_size is not None else mode_config["base_size"])final_image_size = (image_size if image_size is not None else mode_config["image_size"])final_crop_mode = (crop_mode if crop_mode is not None else mode_config["crop_mode"])logger.info(f"Using resolution mode: {resolution_mode}")else:# Custom mode - require all parametersif base_size is None or image_size is None or crop_mode is None:raise ValueError(f"Invalid resolution mode '{resolution_mode}'. "f"Use one of {list(RESOLUTION_MODES.keys())} or specify "f"--base-size, --image-size, and --crop-mode manually.")final_base_size = base_sizefinal_image_size = image_sizefinal_crop_mode = crop_moderesolution_mode = "custom"logger.info(f"Resolution: base_size={final_base_size}, "f"image_size={final_image_size}, crop_mode={final_crop_mode}")# Determine promptif prompt is not None:final_prompt = promptlogger.info(f"Using custom prompt")elif prompt_mode in PROMPT_MODES:final_prompt = PROMPT_MODES[prompt_mode]logger.info(f"Using prompt mode: {prompt_mode}")25 unmodified linesdataset = dataset.select(range(min(max_samples, len(dataset))))logger.info(f"Limited to {len(dataset)} samples")# Initialize vLLMlogger.info(f"Initializing vLLM with model: {model}")logger.info("This may take a few minutes on first run...")# Add specific parameters for DeepSeek-OCR-2 compatibilityllm = LLM(model=model,trust_remote_code=True,max_model_len=max_model_len,gpu_memory_utilization=gpu_memory_utilization,limit_mm_per_prompt={"image": 1},enforce_eager=False, # Use torch.compile instead of eager execution)sampling_params = SamplingParams(temperature=0.0, # Deterministic for OCRmax_tokens=max_tokens,)logger.info(f"Processing {len(dataset)} images in batches of {batch_size}")logger.info("Using vLLM for batch processing - should be faster than sequential processing")# Process images in batchesall_markdown = []for batch_indices in tqdm(5 unmodified linesbatch_images = [dataset[i][image_column] for i in batch_indices]try:# Create messages for batchbatch_messages = [make_ocr_message(img, final_prompt) for img in batch_images]# Process with vLLMoutputs = llm.chat(batch_messages, sampling_params)# Extract outputsfor output in outputs:2 unmodified linesexcept Exception as e:logger.error(f"Error processing batch: {e}")# Add error placeholders for failed batchall_markdown.extend(["[OCR FAILED]"] * len(batch_images))# Calculate processing time26 unmodified lines"column_name": "markdown","model_id": model,"processing_date": datetime.now().isoformat(),"resolution_mode": resolution_mode,"base_size": final_base_size,"image_size": final_image_size,"crop_mode": final_crop_mode,"prompt": final_prompt,"prompt_mode": prompt_mode if prompt is None else "custom","batch_size": batch_size,3 unmodified lines"script": "deepseek-ocr2-vllm.py","script_version": "1.0.0","script_url": "https://huggingface.co/datasets/uv-scripts/ocr/raw/main/deepseek-ocr2-vllm.py","implementation": "vllm (batch processing)",}existing_info.append(new_info)16 unmodified linesmax_model_len=max_model_len,max_tokens=max_tokens,gpu_memory_utilization=gpu_memory_utilization,resolution_mode=resolution_mode,base_size=final_base_size,image_size=final_image_size,crop_mode=final_crop_mode,image_column=image_column,split=split,)card = DatasetCard(card_content)card.push_to_hub(output_dataset, token=HF_TOKEN)logger.info("✅ Dataset card created and pushed!")logger.info("✅ OCR conversion complete!")logger.info(f"Dataset available at: https://huggingface.co/datasets/{output_dataset}")11 unmodified linesprint("with vLLM for efficient batch processing.")print("\nFeatures:")print("- Visual Causal Flow architecture for enhanced encoding")print("- Multiple resolution modes (Tiny/Small/Base/Large/Gundam)")print("- LaTeX equation recognition")print("- Table extraction and formatting")print("- Document structure preservation")print("- Image grounding and spatial layout")print("- Multilingual support")print("- ⚡ Fast batch processing with vLLM (2-3x speedup)")print("\nExample usage:")print("\n1. Basic OCR conversion (Gundam mode - dynamic resolution):")print(" uv run deepseek-ocr2-vllm.py document-images markdown-docs")print("\n2. High quality mode (Large - 1280×1024):")print(" uv run deepseek-ocr2-vllm.py scanned-pdfs extracted-text --resolution-mode large")print("\n3. Fast processing (Tiny - 512×512):")print(" uv run deepseek-ocr2-vllm.py quick-test output --resolution-mode tiny")print("\n4. Parse figures from documents:")print(" uv run deepseek-ocr2-vllm.py scientific-papers figures --prompt-mode figure")print("\n5. Free OCR without layout:")print(" uv run deepseek-ocr2-vllm.py images text --prompt-mode free")print("\n6. Process a subset for testing:")print(" uv run deepseek-ocr2-vllm.py large-dataset test-output --max-samples 10")print("\n7. Custom resolution:")print(" uv run deepseek-ocr2-vllm.py dataset output \\")print(" --base-size 1024 --image-size 768 --crop-mode")print("\n8. Running on HF Jobs:")print(" hf jobs uv run --flavor l4x1 \\")print(" -s HF_TOKEN \\")print(" -e UV_TORCH_BACKEND=auto \\")print(" https://huggingface.co/datasets/uv-scripts/ocr/raw/main/deepseek-ocr2-vllm.py \\")7 unmodified linesdescription="OCR images to markdown using DeepSeek-OCR-2 (vLLM)",formatter_class=argparse.RawDescriptionHelpFormatter,epilog="""Resolution Modes:tiny 512×512 pixels, fast processing (64 vision tokens)small 640×640 pixels, balanced (100 vision tokens)base 1024×768 pixels, high quality (~192 vision tokens) ⭐ v2 optimizedlarge 1280×1024 pixels, maximum quality (~328 vision tokens)gundam Dynamic multi-tile with 768×768 patches (adaptive)Prompt Modes:document Convert document to markdown with grounding (default)image OCR any image with grounding2 unmodified linesdescribe Generate detailed image descriptionsExamples:# Basic usage with default Gundam modeuv run deepseek-ocr2-vllm.py my-images-dataset ocr-results# High quality processinguv run deepseek-ocr2-vllm.py documents extracted-text --resolution-mode large# Fast processing for testinguv run deepseek-ocr2-vllm.py dataset output --resolution-mode tiny --max-samples 100# Parse figures from a document datasetuv run deepseek-ocr2-vllm.py scientific-papers figures --prompt-mode figure# Free OCR without layout (fastest)uv run deepseek-ocr2-vllm.py images text --prompt-mode free# Custom prompt for specific taskuv run deepseek-ocr2-vllm.py dataset output --prompt "<image>\nExtract all table data."# Custom resolution settingsuv run deepseek-ocr2-vllm.py dataset output --base-size 1024 --image-size 768 --crop-mode# With custom batch size for performance tuninguv run deepseek-ocr2-vllm.py dataset output --batch-size 16 --max-model-len 16384""",)15 unmodified linesdefault="deepseek-ai/DeepSeek-OCR-2",help="Model to use (default: deepseek-ai/DeepSeek-OCR-2)",)parser.add_argument("--resolution-mode",default="gundam",choices=list(RESOLUTION_MODES.keys()) + ["custom"],help="Resolution mode preset (default: gundam)",)parser.add_argument("--base-size",type=int,help="Base resolution size (overrides resolution-mode)",)parser.add_argument("--image-size",type=int,help="Image tile size (overrides resolution-mode)",)parser.add_argument("--crop-mode",action="store_true",help="Enable dynamic multi-tile cropping (overrides resolution-mode)",)parser.add_argument("--max-model-len",type=int,54 unmodified linesimage_column=args.image_column,batch_size=args.batch_size,model=args.model,resolution_mode=args.resolution_mode,base_size=args.base_size,image_size=args.image_size,crop_mode=args.crop_mode if args.crop_mode else None,max_model_len=args.max_model_len,max_tokens=args.max_tokens,gpu_memory_utilization=args.gpu_memory_utilization,23 unmodified lines2425262728293031323334353637383 unmodified lines424344454647484950515253542 unmodified lines57585960616263646566676813 unmodified lines82838485868788899091929394959697984 unmodified lines10310410510610710829 unmodified lines1381391401411421431 unmodified line14514614714814915015115215315415515615715815916016129 unmodified lines1911921931941951962 unmodified lines1992002012022032042051 unmodified line20720820921021121221321419 unmodified lines23423523623723823924024124224325 unmodified lines2692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023035 unmodified lines3093103113123133143153163173183193203213223233242 unmodified lines32732832933033133226 unmodified lines3593603613623633643 unmodified lines36836937037137237337416 unmodified lines39139239339439539639739839940040140240340440511 unmodified lines4174184194204214224234244254264274284294304314324334344354364374384394404414424434447 unmodified lines4524534544554564572 unmodified lines46046146246346446546646746846947047147247347447547647747847948048148248348415 unmodified lines50050150250350450554 unmodified lines56056156256356456523 unmodified lineswith Visual Causal Flow architecture) to extract text and structure as markdown,using vLLM for efficient batch processing.Uses the official vLLM offline pattern: llm.generate() with PIL imagesand NGramPerReqLogitsProcessor to prevent repetition on complex documents.See: https://docs.vllm.ai/projects/recipes/en/latest/DeepSeek/DeepSeek-OCR.htmlNOTE: Uses vLLM nightly wheels. First run may take a few minutes to downloadand install dependencies.Features:- Visual Causal Flow architecture for enhanced visual encoding- LaTeX equation recognition- Table extraction and formatting- Document structure preservation3 unmodified lines"""import argparseimport ioimport jsonimport loggingimport osimport sysfrom datetime import datetimefrom typing import Any, Dict, Unionimport torchfrom datasets import load_dataset2 unmodified linesfrom toolz import partition_allfrom tqdm.auto import tqdmfrom vllm import LLM, SamplingParamsfrom vllm.model_executor.models.deepseek_ocr import NGramPerReqLogitsProcessorlogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)# Prompt mode presets (from DeepSeek-OCR GitHub)PROMPT_MODES = {"document": "<image>\n<|grounding|>Convert the document to markdown.","image": "<image>\n<|grounding|>OCR this image.",13 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def to_pil(image: Union[Image.Image, Dict[str, Any], str]) -> Image.Image:"""Convert various image formats to PIL Image."""if isinstance(image, Image.Image):return imageelif isinstance(image, dict) and "bytes" in image:return Image.open(io.BytesIO(image["bytes"]))elif isinstance(image, str):return Image.open(image)else:raise ValueError(f"Unsupported image type: {type(image)}")def create_dataset_card(source_dataset: str,4 unmodified linesmax_model_len: int,max_tokens: int,gpu_memory_utilization: float,image_column: str = "image",split: str = "train",) -> str:29 unmodified lines- **Output Column**: `markdown`- **Dataset Split**: `{split}`- **Batch Size**: {batch_size}- **Max Model Length**: {max_model_len:,} tokens- **Max Output Tokens**: {max_tokens:,}- **GPU Memory Utilization**: {gpu_memory_utilization:.1%}1 unmodified line## Model InformationDeepSeek-OCR-2 is a 3B parameter vision-language model featuring Visual CausalFlow architecture for more human-like visual encoding. Building on DeepSeek-OCR v1,it offers enhanced document understanding with dynamic resolution up to(0-6)x768x768 + 1x1024x1024 patches.### Capabilities- LaTeX equations - Mathematical formulas preserved in LaTeX format- Tables - Extracted and formatted as HTML/markdown- Document structure - Headers, lists, and formatting maintained- Image grounding - Spatial layout and bounding box information- Complex layouts - Multi-column and hierarchical structures- Multilingual - Supports multiple languages## Dataset Structure29 unmodified linesuv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/deepseek-ocr2-vllm.py \\\\{source_dataset} \\\\<output-dataset> \\\\--image-column {image_column}```2 unmodified lines- **Processing Speed**: ~{num_samples / (float(processing_time.split()[0]) * 60):.1f} images/second- **Processing Method**: Batch processing with vLLM (2-3x speedup over sequential)Generated with [UV Scripts](https://huggingface.co/uv-scripts)"""1 unmodified lineinput_dataset: str,output_dataset: str,image_column: str = "image",batch_size: int = 8,model: str = "deepseek-ai/DeepSeek-OCR-2",max_model_len: int = 8192,max_tokens: int = 8192,gpu_memory_utilization: float = 0.8,19 unmodified linesif HF_TOKEN:login(token=HF_TOKEN)# Determine promptif prompt is not None:final_prompt = promptlogger.info("Using custom prompt")elif prompt_mode in PROMPT_MODES:final_prompt = PROMPT_MODES[prompt_mode]logger.info(f"Using prompt mode: {prompt_mode}")25 unmodified linesdataset = dataset.select(range(min(max_samples, len(dataset))))logger.info(f"Limited to {len(dataset)} samples")# Initialize vLLM (matches official DeepSeek-OCR vLLM recipe)logger.info(f"Initializing vLLM with model: {model}")logger.info("This may take a few minutes on first run...")llm = LLM(model=model,trust_remote_code=True,max_model_len=max_model_len,gpu_memory_utilization=gpu_memory_utilization,enable_prefix_caching=False,mm_processor_cache_gb=0,limit_mm_per_prompt={"image": 1},logits_processors=[NGramPerReqLogitsProcessor],)sampling_params = SamplingParams(temperature=0.0,max_tokens=max_tokens,skip_special_tokens=False,extra_args=dict(ngram_size=30,window_size=90,whitelist_token_ids={128821, 128822},),)logger.info(f"Processing {len(dataset)} images in batches of {batch_size}")# Process images in batches using llm.generate() with PIL imagesall_markdown = []for batch_indices in tqdm(5 unmodified linesbatch_images = [dataset[i][image_column] for i in batch_indices]try:# Build model inputs with PIL images (official vLLM pattern)model_inputs = []for img in batch_images:pil_img = to_pil(img).convert("RGB")model_inputs.append({"prompt": final_prompt, "multi_modal_data": {"image": pil_img}})# Process with vLLM generate APIoutputs = llm.generate(model_inputs, sampling_params)# Extract outputsfor output in outputs:2 unmodified linesexcept Exception as e:logger.error(f"Error processing batch: {e}")all_markdown.extend(["[OCR FAILED]"] * len(batch_images))# Calculate processing time26 unmodified lines"column_name": "markdown","model_id": model,"processing_date": datetime.now().isoformat(),"prompt": final_prompt,"prompt_mode": prompt_mode if prompt is None else "custom","batch_size": batch_size,3 unmodified lines"script": "deepseek-ocr2-vllm.py","script_version": "1.0.0","script_url": "https://huggingface.co/datasets/uv-scripts/ocr/raw/main/deepseek-ocr2-vllm.py","implementation": "vllm (batch processing, llm.generate + NGramPerReqLogitsProcessor)",}existing_info.append(new_info)16 unmodified linesmax_model_len=max_model_len,max_tokens=max_tokens,gpu_memory_utilization=gpu_memory_utilization,image_column=image_column,split=split,)card = DatasetCard(card_content)card.push_to_hub(output_dataset, token=HF_TOKEN)logger.info("Dataset card created and pushed!")logger.info("OCR conversion complete!")logger.info(f"Dataset available at: https://huggingface.co/datasets/{output_dataset}")11 unmodified linesprint("with vLLM for efficient batch processing.")print("\nFeatures:")print("- Visual Causal Flow architecture for enhanced encoding")print("- LaTeX equation recognition")print("- Table extraction and formatting")print("- Document structure preservation")print("- Image grounding and spatial layout")print("- Multilingual support")print("- Fast batch processing with vLLM")print("\nExample usage:")print("\n1. Basic OCR conversion (document mode with grounding):")print(" uv run deepseek-ocr2-vllm.py document-images markdown-docs")print("\n2. Parse figures from documents:")print(" uv run deepseek-ocr2-vllm.py scientific-papers figures --prompt-mode figure")print("\n3. Free OCR without layout:")print(" uv run deepseek-ocr2-vllm.py images text --prompt-mode free")print("\n4. Process a subset for testing:")print(" uv run deepseek-ocr2-vllm.py large-dataset test-output --max-samples 10")print("\n5. Running on HF Jobs:")print(" hf jobs uv run --flavor l4x1 \\")print(" -s HF_TOKEN \\")print(" https://huggingface.co/datasets/uv-scripts/ocr/raw/main/deepseek-ocr2-vllm.py \\")7 unmodified linesdescription="OCR images to markdown using DeepSeek-OCR-2 (vLLM)",formatter_class=argparse.RawDescriptionHelpFormatter,epilog="""Prompt Modes:document Convert document to markdown with grounding (default)image OCR any image with grounding2 unmodified linesdescribe Generate detailed image descriptionsExamples:# Basic usageuv run deepseek-ocr2-vllm.py my-images-dataset ocr-results# Parse figures from a document datasetuv run deepseek-ocr2-vllm.py scientific-papers figures --prompt-mode figure# Free OCR without layoutuv run deepseek-ocr2-vllm.py images text --prompt-mode free# Custom prompt for specific taskuv run deepseek-ocr2-vllm.py dataset output --prompt "<image>\\nExtract all table data."# With custom batch size for performance tuninguv run deepseek-ocr2-vllm.py dataset output --batch-size 16 --max-model-len 16384# Running on HF Jobshf jobs uv run --flavor l4x1 -s HF_TOKEN \\https://huggingface.co/datasets/uv-scripts/ocr/raw/main/deepseek-ocr2-vllm.py \\my-dataset my-output --max-samples 10""",)15 unmodified linesdefault="deepseek-ai/DeepSeek-OCR-2",help="Model to use (default: deepseek-ai/DeepSeek-OCR-2)",)parser.add_argument("--max-model-len",type=int,54 unmodified linesimage_column=args.image_column,batch_size=args.batch_size,model=args.model,max_model_len=args.max_model_len,max_tokens=args.max_tokens,gpu_memory_utilization=args.gpu_memory_utilization,
deepseek-ocr2-vllm.py+62-200