如何在 Windows、Mac 和 Linux 上运行 OpenThai 2.1 OCR Text 与 OCR Markdown
iApp 的两个泰文 OCR 模型均可免费下载:OpenThai 2.1 OCR Text 和 OpenThai 2.1 OCR Markdown。本指南介绍如何在 Windows、macOS 或 Linux 上运行它们,从安装 Python 到把 PDF 转成文本或 Markdown。文档始终留在你的电脑上。
本指南最初于 2026 年 11 月 12 日为 2.0 版编写。现在改用名称中带有发布日期的 2.1 版仓库,并新增了在 Mac 或 CPU 上用 llama.cpp 运行 OCR Markdown 的方法。旧名称仍然可用,会自动跳转到 2.1 版。2.1 版的新内容。
选择哪个模型
| OpenThai 2.1 OCR Text | OpenThai 2.1 OCR Markdown | |
|---|---|---|
| 输出 | 按阅读顺序排列的页面文本,每行带位置框和置信度 | Markdown,表格以 HTML 输出(含 rowspan 与 colspan),每个区块带位置框和类别 |
| 下载大小 | 6.6 MB | 2.5 GB(llama.cpp 用的 GGUF 为 1.1 GB) |
| 运行环境 | 任何 CPU,无需 GPU | NVIDIA GPU(最快)、Apple 芯片的 Mac,或 CPU |
| 速度 | 在 M3 Max 的 Mac 上约 0.5 秒一页 | 单张 NVIDIA H100 上 1.5 秒一页;M3 Max 的 Mac 上用 PyTorch 约 20 至 33 秒一页,用 llama.cpp 5 至 9 秒 |
| 许可 | Apache-2.0 | OpenMDW-1.1 |
需要文字本身时用 OCR Text,例如搜索、从扫描件中取出文字或交给聊天机器人。版面重要时用 OCR Markdown,尤其是表格,数字必须留在原来的行和列中。
Mac 上的数据是为本指南在 M3 Max 的 MacBook Pro 上测得的,测试页为一页泰国政府公文和一页表格;H100 和 llama.cpp 的数据来自模型卡和 GGUF 说明。
不写代码:Chinda Bot
我们的免费桌面助手 Chinda Bot 已内置 OCR Text(2.0 版)。用回形针按钮附加 PDF,或把它拖进对话,每一页都在你的电脑上读取;点击文件名即可查看并复制读出的文字。Chinda Bot 支持 Apple 芯片的 Mac、Windows 电脑(Intel 或 AMD,以及 Windows on Arm)和 Linux arm64。
Chinda Bot 只输出文本行。若要让表格保持表格,请使用下文的 OCR Markdown。
开始之前:安装 Python
两个模型都需要 Python 3.10 或更高版本。本指南在 macOS 上用 Python 3.13、在 Ubuntu 24.04 上用 Python 3.12 测试;2.1 版的步骤已在 macOS 上重新测试。
- Windows
- Mac
- Linux
从 python.org 下载 Python 3.13 并运行安装程序,在第一页勾选 Add python.exe to PATH。然后打开命令提示符(按 Windows 键并输入 cmd)。下文所有 Windows 命令都在命令提示符中运行。
从 python.org 安装 Python 3.13,或用 Homebrew:brew install python@3.13。然后打开终端。
在 Ubuntu 或 Debian 上:
sudo apt install python3 python3-venv python3-pip
OpenThai 2.1 OCR Text:任何电脑都能用
1. 新建文件夹和 Python 环境
- Windows
- Mac
- Linux
mkdir thai-ocr
cd thai-ocr
py -m venv .venv
.venv\Scripts\activate
mkdir thai-ocr && cd thai-ocr
python3 -m venv .venv
source .venv/bin/activate
mkdir thai-ocr && cd thai-ocr
python3 -m venv .venv
source .venv/bin/activate
这个环境把安装的软件包与电脑的其他部分隔开。每次打开新窗口时,再运行最后一行激活它。
2. 安装软件包并下载模型
所有系统都用相同的两条命令:
pip install onnxruntime opencv-python-headless pyclipper numpy pillow pypdfium2 huggingface_hub
hf download iapp/OpenThai2.1-OCR-Text-20261118 --local-dir OpenThai2.1-OCR-Text
模型是 1.8 MB、2.4 MB 和 2.4 MB 的三个文件,连同读取代码一起放在 OpenThai2.1-OCR-Text 文件夹中。该文件夹还附有 requirements.txt,列出模型团队测试过的软件包版本。如果希望在新版本发布后仍使用此版本,请在下载命令后加上 --revision v2.1.4。
Windows on Arm(RTX Spark 等 Arm 电脑):opencv-python-headless 和 pyclipper 两个软件包还没有 Windows on Arm 版本,因此 pip install 在这类电脑上会失败。可以从 python.org 安装 x64 版 Python,由 Windows 以模拟方式运行,速度较慢;或者使用在 Windows on Arm 上原生运行 OCR Text 的 Chinda Bot。
3. 保存脚本
把以下代码保存为 thai-ocr 文件夹中的 ocr_text.py:
"""Read Thai and English text from pictures and PDFs with OpenThai 2.1 OCR Text.
Usage: python ocr_text.py document.pdf [more files ...]
Prints the text and saves it next to each file as <file>.txt.
"""
import sys
import time
from pathlib import Path
MODEL_DIR = Path(__file__).resolve().parent / "OpenThai2.1-OCR-Text"
sys.path.insert(0, str(MODEL_DIR))
from runtime.line_engine import LineOCR # noqa: E402
def pages(path):
"""Each page of a PDF as a picture (drawn at 200 dpi), or the picture itself."""
if path.suffix.lower() == ".pdf":
import pypdfium2 as pdfium
pdf = pdfium.PdfDocument(str(path))
for i in range(len(pdf)):
yield pdf[i].render(scale=200 / 72).to_pil()
else:
yield str(path)
ocr = LineOCR(str(MODEL_DIR), threads=2)
for name in sys.argv[1:]:
path = Path(name)
texts = []
for number, page in enumerate(pages(path), start=1):
start = time.perf_counter()
result = ocr.read(page)
seconds = time.perf_counter() - start
print(f"{path.name} page {number}: {len(result['lines'])} lines in {seconds:.2f} s", file=sys.stderr)
texts.append(result["text"])
text = "\n\n".join(texts)
path.with_name(path.name + ".txt").write_text(text, encoding="utf-8")
print(text)
4. 读取文档
python ocr_text.py document.pdf
脚本会输出文本并保存为 document.pdf.txt。PDF 按页读取,图片(PNG、JPG 等常见格式)直接读取;也可以一次传入多个文件。在较新的电脑上每页约需半秒。
两点说明:
- 扫描 PDF 和带文字层的 PDF 都可以,因为每一页都先绘制成图片再读取。
- 处理上千页时,把
threads=2改为threads=1,按 CPU 核心数各运行一份脚本,分别处理一部分文件。单个进程中,线程数超过约两个核心后就不再变快。模型卡在 8 核服务器上测得约每分钟 950 页。
OpenThai 2.1 OCR Markdown
该模型有 2.5 GB,最适合在 GPU 上运行。我们在 Linux 上用 NVIDIA H100 GPU 运行它,并在 M3 Max 的 Mac 上测试了本指南。选择你的系统:
- Windows
- Mac
- Linux
有 NVIDIA GPU: 使用 WSL 2。它在 Windows 中运行 Ubuntu,并通过已安装的 NVIDIA 驱动让 Ubuntu 使用 GPU。以管理员身份打开 PowerShell 并运行:
wsl --install -d Ubuntu-24.04
按提示重启后,从开始菜单打开 Ubuntu,在其中按照本页 Linux 的步骤操作。我们尚未亲自在 Windows 上测试 OCR Markdown。
没有 NVIDIA GPU: 使用 llama.cpp、下文的 泰语文档转 Markdown API,或用 Chinda Bot 读取纯文本。
Apple 芯片(M1 或更新)的 Mac 可以在自带 GPU 上运行该模型。按 OCR Text 第 1 步创建环境(可用新文件夹),然后运行:
pip install huggingface_hub pypdfium2
hf download iapp/OpenThai2.1-OCR-Markdown-20261118 --local-dir OpenThai2.1-OCR-Markdown
pip install -e ./OpenThai2.1-OCR-Markdown
最后一行安装模型自带的读取软件包以及 PyTorch。然后保存下面的脚本并运行:
python ocr_markdown.py document.pdf
在我们的 M3 Max 上,一页表格用时 19.7 秒,一整页密集文字用时 33.0 秒。如需在 Mac 上更快地运行,请参阅下文的 llama.cpp。我们公布的分数是在 NVIDIA GPU 上用 vLLM 测得的;在 Mac 上同一套权重改由 PyTorch 运行,个别页面的结果可能略有不同。
有 NVIDIA GPU 时,用 vLLM 把模型作为服务运行,与我们自己的 API 相同。按 OCR Text 第 1 步创建环境,然后运行:
pip install huggingface_hub pypdfium2
hf download iapp/OpenThai2.1-OCR-Markdown-20261118 --local-dir OpenThai2.1-OCR-Markdown
pip install -e "./OpenThai2.1-OCR-Markdown[vllm,client]"
vllm serve ./OpenThai2.1-OCR-Markdown --served-model-name nemotron-parse --trust-remote-code
让服务保持运行。在同一文件夹中打开第二个终端,激活环境,保存下面的脚本并运行:
python ocr_markdown.py document.pdf --server http://localhost:8000/v1
在单张 H100 上每页约 1.5 秒;并行发送时,服务可以同时读取多页。我们的托管 API 为该模型使用约 8 GB 显存。我们只在 H100 GPU 上测试过;vLLM 默认占用显卡 90% 的显存,在较小的显卡上可能需要调低 --max-num-seqs。
没有 NVIDIA GPU 时,跳过与 vllm 有关的行,运行脚本时不加 --server。脚本会在 CPU 上运行模型,速度慢得多。
把以下代码保存为 ocr_markdown.py,放在包含 OpenThai2.1-OCR-Markdown 的文件夹中:
"""Read pictures and PDFs into Markdown with OpenThai 2.1 OCR Markdown.
python ocr_markdown.py document.pdf
runs the model on this computer: an NVIDIA GPU, a Mac's GPU, or the CPU
python ocr_markdown.py document.pdf --server http://localhost:8000/v1
sends the pages to a vLLM server instead (the fastest way)
Saves the Markdown next to each file as <file>.md. Tables come out as HTML.
"""
import argparse
import sys
import time
from pathlib import Path
from PIL import Image
from nemotron_parse.inference import DocumentParser, GenerationError, GenerationSettings, TransformersBackend
MODEL_DIR = Path(__file__).resolve().parent / "OpenThai2.1-OCR-Markdown"
def pages(path):
"""Each page of a PDF as a picture (drawn at 200 dpi), or the picture itself."""
if path.suffix.lower() == ".pdf":
import pypdfium2 as pdfium
pdf = pdfium.PdfDocument(str(path))
for i in range(len(pdf)):
yield pdf[i].render(scale=200 / 72).to_pil()
else:
yield Image.open(path)
def local_parser():
import torch
from transformers import AutoModel, AutoProcessor
if torch.cuda.is_available():
device, dtype = "cuda", torch.bfloat16
elif torch.backends.mps.is_available():
device, dtype = "mps", torch.float32
else:
device, dtype = "cpu", torch.float32
model = AutoModel.from_pretrained(MODEL_DIR, trust_remote_code=True, dtype=dtype).to(device).eval()
processor = AutoProcessor.from_pretrained(MODEL_DIR, trust_remote_code=True)
class Backend(TransformersBackend):
# a vLLM server reads the prompt after a new line; send the same tokens here
def __call__(self, image, *, prompt, **kwargs):
return super().__call__(image, prompt="\n" + prompt, **kwargs)
print(f"Running the model on {device}", file=sys.stderr)
# read greedily (temperature 0); with sampling, a Mac's GPU garbled pages in our test
return DocumentParser(backend=Backend(model, processor), fullpage=GenerationSettings(temperature=0))
args = argparse.ArgumentParser()
args.add_argument("files", nargs="+")
args.add_argument("--server", help="a vLLM server, for example http://localhost:8000/v1")
args = args.parse_args()
parser = DocumentParser(base_url=args.server, model="nemotron-parse") if args.server else local_parser()
with parser:
for name in args.files:
path = Path(name)
parts = []
for number, page in enumerate(pages(path), start=1):
start = time.perf_counter()
try:
parts.append(parser.parse(page, mode="single")["markdown"])
except GenerationError:
parts.append(f"<!-- page {number} could not be read completely -->")
print(f"{path.name} page {number}: {time.perf_counter() - start:.1f} s", file=sys.stderr)
markdown = "\n\n".join(parts)
path.with_name(path.name + ".md").write_text(markdown, encoding="utf-8")
print(markdown)
脚本会写出 document.pdf.md,每个表格是一个 HTML <table>,每个公式是写在 $$ 之间的 LaTeX,Markdown 阅读器和大多数语言模型都能直接读取。页眉和页脚不会写入,空白页返回空结果。若某页因超出长度上限被截断,脚本会在文件中注明,然后继续读下一页。
用 llama.cpp 在 Mac 或 CPU 上运行 OCR Markdown
2.1 版新增:OCR Markdown 另外提供 llama.cpp 用的 GGUF 文件,无需 PyTorch 或 vLLM,即可在 Mac 的 GPU、CPU 或 NVIDIA 显卡上运行。官方 llama.cpp 尚未包含该模型,因此需要先构建一次 iApp 的版本。你需要 git、CMake 和 C++ 编译器:在 Mac 上运行 xcode-select --install,再在第 1 步创建的环境中运行 pip install cmake;在 Ubuntu 上运行 sudo apt install git cmake build-essential。我们在 M3 Max 的 Mac 上测试了这一方法。
1. 构 建 llama.cpp(需要几分钟):
git clone -b nemotron-parse https://github.com/iapp-technology/llama.cpp
cmake -S llama.cpp -B llama.cpp/build -DCMAKE_BUILD_TYPE=Release -DLLAMA_USE_PREBUILT_UI=OFF
cmake --build llama.cpp/build -j --target llama-server
在 Mac 上会自动使用其 GPU(Metal);在装有 NVIDIA 显卡的电脑上,请在第一条 cmake 命令中加上 -DGGML_CUDA=ON。-DLLAMA_USE_PREBUILT_UI=OFF 会跳过服务的网页界面,OCR 不需要它,而且在我们的测试中它下载失败。
2. 下载模型文件(1.1 GB)以及不含完整权重的读取软件包:
hf download iapp/OpenThai2.1-OCR-Markdown-20261118-GGUF openthai2.1-ocr-markdown-q8_0.gguf mmproj-openthai2.1-ocr-markdown-f16.gguf --local-dir gguf
hf download iapp/OpenThai2.1-OCR-Markdown-20261118 --exclude "model.safetensors" --local-dir OpenThai2.1-OCR-Markdown
pip install --no-deps ./OpenThai2.1-OCR-Markdown
pip install httpx "Pillow>=12.2,<13" numpy beautifulsoup4 pypdfium2
--no-deps 安装会跳过这一方法用不到的 PyTorch,因此 pip 可能提示缺少某些软件包;这些提示在这里没有影响。
3. 启动服务并保持运行:
llama.cpp/build/bin/llama-server -m gguf/openthai2.1-ocr-markdown-q8_0.gguf --mmproj gguf/mmproj-openthai2.1-ocr-markdown-f16.gguf --jinja -c 16384 --port 8000
4. 读取文档:在第二个终端中,使用上文同一个 ocr_markdown.py 脚本:
python ocr_markdown.py document.pdf --server http://localhost:8000/v1
在我们的 M3 Max 上,用这种方法每页 4.7 至 9.0 秒,而用 PyTorch 约 20 至 33 秒,表格也保持为表格。模型团队核对过,GGUF 文件在 30 页测试页面中有 30 页给出与原模型相同的 Markdown;仅用 CPU 时每页约需一分钟。我们尚未在 Windows 上测试这一方法;llama.cpp 可以在 Windows 上用 CMake 和 Visual Studio 构建。
没有 GPU?使用 API
两个模型也提供托管 API,无需安装:
- 泰语文档转 Markdown API:传入 PDF 或图片,返回 Markdown 和表格,每页 0.15 IC。
- 泰语文档 OCR API:纯文本、Word、PowerPoint、Excel 或可搜索 PDF,每页 0.049 IC 起。
链接
- 模型页面及测试结果:OpenThai 2.1 OCR Text 和 OpenThai 2.1 OCR Markdown
- 两个模型的对比:OpenThai OCR
- Hugging Face 上的权重:iapp/OpenThai2.1-OCR-Text-20261118、iapp/OpenThai2.1-OCR-Markdown-20261118 和 GGUF 文件
- 2.1 版的新内容:发布文章;2.0 版发布:OpenThai 2.0 OCR Text 与 OpenThai 2.0 OCR Markdown
如果某份泰文文档读得不好,欢迎把不含个人信息的样本发送至 sale@iapp.co.th,这些页面能帮助我们改进下一个版本。