Instructions to use anusoft/OpenThai2.2-OCR-Markdown-20261127-mlx-rocm-pascal with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- MLX
How to use anusoft/OpenThai2.2-OCR-Markdown-20261127-mlx-rocm-pascal with MLX:
# Make sure mlx-vlm is installed # pip install --upgrade mlx-vlm from mlx_vlm import load, generate from mlx_vlm.prompt_utils import apply_chat_template from mlx_vlm.utils import load_config # Load the model model, processor = load("anusoft/OpenThai2.2-OCR-Markdown-20261127-mlx-rocm-pascal") config = load_config("anusoft/OpenThai2.2-OCR-Markdown-20261127-mlx-rocm-pascal") # Prepare input image = ["http://images.cocodataset.org/val2017/000000039769.jpg"] prompt = "Describe this image." # Apply chat template formatted_prompt = apply_chat_template( processor, config, prompt, num_images=1 ) # Generate output output = generate(model, processor, formatted_prompt, image) print(output) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- LM Studio
- Atomic Chat
Download runtime/pascal/ocr.py from anusoft/OpenThai2.2-OCR-Markdown-20261127-mlx-rocm-pascal: direct link, hf CLI and curl.
- Browser
- Download file 5.29 kB
-
https://huggingface.co/anusoft/OpenThai2.2-OCR-Markdown-20261127-mlx-rocm-pascal/resolve/main/runtime/pascal/ocr.py
- Command line
-
hf download hf://anusoft/OpenThai2.2-OCR-Markdown-20261127-mlx-rocm-pascal/runtime/pascal/ocr.py
-
curl -L -o ocr.py https://huggingface.co/anusoft/OpenThai2.2-OCR-Markdown-20261127-mlx-rocm-pascal/resolve/main/runtime/pascal/ocr.py
5.29 kB
| """Run OpenThai 2.2 Markdown OCR on local images.""" | |
| from __future__ import annotations | |
| import argparse | |
| from functools import partial | |
| import os | |
| import sys | |
| from pathlib import Path | |
| from threading import Lock | |
| MODEL_DIR = Path(__file__).resolve().parents[2] / "models" / "original" | |
| ENGINES = ("fast", "balanced", "mixed", "accurate", "graph", "stock") | |
| class GraphBackend: | |
| def __init__(self, model, processor, decoder, generate): | |
| self.model = model | |
| self.processor = processor | |
| self.decoder = decoder | |
| self.generate = generate | |
| self.lock = Lock() | |
| def __call__(self, image, *, prompt, stage, settings): | |
| from graph_step import EOS | |
| if settings.temperature != 0: | |
| raise ValueError("The CUDA graph backend requires greedy decoding") | |
| with self.lock: | |
| inputs = self.processor( | |
| images=[image], text=prompt, return_tensors="pt", add_special_tokens=False | |
| ).to(self.model.device) | |
| ids = self.generate( | |
| self.decoder, self.model, inputs, settings.max_tokens, settings.repetition_penalty | |
| ).cpu() | |
| count = ids.shape[-1] - inputs["input_ids"].shape[-1] | |
| return { | |
| "raw_out": self.processor.batch_decode(ids, skip_special_tokens=False)[0], | |
| "finish_reason": "stop" if count < settings.max_tokens and ids[0, -1] == EOS else "length", | |
| "usage": {"completion_tokens": count}, | |
| } | |
| def open_parser(model_dir: Path, engine: str = "fast"): | |
| import torch | |
| from transformers import AutoModel, AutoProcessor | |
| if engine not in ENGINES: | |
| raise ValueError(f"Unknown OCR engine: {engine}") | |
| if not torch.cuda.is_available(): | |
| raise RuntimeError("CUDA is unavailable in the selected Python environment") | |
| if engine != "stock" and torch.cuda.get_device_capability() != (6, 1): | |
| raise RuntimeError("The Pascal CUDA graph engine requires a compute capability 6.1 GPU") | |
| model_dir = Path(model_dir).expanduser().resolve() | |
| if not (model_dir / "model.safetensors").is_file(): | |
| raise RuntimeError(f"OpenThai 2.2 model weights were not found in {model_dir}") | |
| if str(model_dir) not in sys.path: | |
| sys.path.insert(0, str(model_dir)) | |
| from nemotron_parse.inference import DocumentParser, GenerationSettings, TransformersBackend | |
| model = AutoModel.from_pretrained( | |
| model_dir, trust_remote_code=True, dtype=torch.float32, local_files_only=True | |
| ).cuda().eval() | |
| processor = AutoProcessor.from_pretrained(model_dir, trust_remote_code=True, local_files_only=True) | |
| if engine == "stock": | |
| backend = TransformersBackend(model, processor) | |
| else: | |
| from graph_step import AdaptiveDecoder, generate_adaptive | |
| from int8_gemv import install as install_int8 | |
| if engine in ("fast", "balanced", "mixed", "accurate"): | |
| from pascal_decode import PascalStep, generate_chunked, kernels | |
| if engine == "mixed": | |
| from dense_gemv import install as install_dense | |
| install_dense(model) | |
| elif engine != "accurate": | |
| install_int8( | |
| model, gemv=kernels().vectorized_gemv, original_prefill=engine == "balanced" | |
| ) | |
| cache_dtype = torch.float32 if engine == "accurate" else torch.float16 | |
| decoder = AdaptiveDecoder( | |
| model, buckets=(1024, 2048, 4096, 8192), | |
| step_factory=partial(PascalStep, kv_dtype=cache_dtype), overflow_bucket=12288, | |
| ) | |
| backend = GraphBackend(model, processor, decoder, generate_chunked) | |
| else: | |
| install_int8(model) | |
| decoder = AdaptiveDecoder(model, overflow_bucket=12288) | |
| backend = GraphBackend(model, processor, decoder, generate_adaptive) | |
| return DocumentParser( | |
| backend=backend, | |
| fullpage=GenerationSettings(temperature=0.0, repetition_penalty=1.05, max_tokens=8744), | |
| ) | |
| def main() -> None: | |
| cli = argparse.ArgumentParser(description=__doc__) | |
| cli.add_argument("images", type=Path, nargs="+", help="page images in reading order") | |
| cli.add_argument("-o", "--output", type=Path, help="write Markdown to this file") | |
| cli.add_argument("--model-dir", type=Path, default=os.environ.get("OPENTHAI_MODEL_DIR", MODEL_DIR)) | |
| cli.add_argument("--engine", choices=ENGINES, default="fast") | |
| args = cli.parse_args() | |
| for image in args.images: | |
| if not image.is_file(): | |
| cli.error(f"image does not exist: {image}") | |
| if args.output is not None and args.output.exists(): | |
| if any(args.output.samefile(image) for image in args.images): | |
| cli.error("the output file must differ from the input images") | |
| try: | |
| with open_parser(args.model_dir, args.engine) as parser: | |
| pages = [parser.parse(image, mode="single")["markdown"] for image in args.images] | |
| markdown = "\n\n---\n\n".join(pages) | |
| if args.output: | |
| args.output.write_text(markdown, encoding="utf-8") | |
| else: | |
| sys.stdout.write(markdown) | |
| except (OSError, RuntimeError) as error: | |
| cli.exit(1, f"OpenThai OCR: {error}\n") | |
| if __name__ == "__main__": | |
| main() | |