typhoon-ocr2 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- typhoon_ocr2/__init__.py +22 -0
- typhoon_ocr2/cli.py +80 -0
- typhoon_ocr2/client.py +251 -0
- typhoon_ocr2/images.py +119 -0
- typhoon_ocr2/output.py +95 -0
- typhoon_ocr2/prompts.py +58 -0
- typhoon_ocr2-0.1.0.dist-info/METADATA +233 -0
- typhoon_ocr2-0.1.0.dist-info/RECORD +13 -0
- typhoon_ocr2-0.1.0.dist-info/WHEEL +5 -0
- typhoon_ocr2-0.1.0.dist-info/entry_points.txt +2 -0
- typhoon_ocr2-0.1.0.dist-info/licenses/LICENSE +201 -0
- typhoon_ocr2-0.1.0.dist-info/licenses/NOTICE +7 -0
- typhoon_ocr2-0.1.0.dist-info/top_level.txt +1 -0
typhoon_ocr2/__init__.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Typhoon OCR V2: Thai and English document parsing with layout, from images and PDFs.
|
|
2
|
+
|
|
3
|
+
>>> from typhoon_ocr2 import TyphoonOCR
|
|
4
|
+
>>> ocr = TyphoonOCR(base_url="http://localhost:8000/v1") # vLLM, llama.cpp, MLX or Ollama
|
|
5
|
+
>>> page = ocr.parse("report.pdf", pages=1)[0]
|
|
6
|
+
>>> page.elements[0]
|
|
7
|
+
{'bbox': [62, 48, 938, 96], 'category': 'title', 'text': 'Annual Report 2025'}
|
|
8
|
+
>>> print(page.markdown)
|
|
9
|
+
"""
|
|
10
|
+
from .client import PageResult, TyphoonOCR, TyphoonOCRError, ocr_document
|
|
11
|
+
from .images import load_pages, render_pdf_pages, upscale_min_long
|
|
12
|
+
from .output import CATEGORIES, draw_layout, parse_elements, parse_json, to_markdown, to_pixels
|
|
13
|
+
from .prompts import EXTRACT_ALL_PROMPT, PARSE_PROMPT, V15_PROMPT
|
|
14
|
+
|
|
15
|
+
__version__ = "0.1.0"
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
"TyphoonOCR", "PageResult", "TyphoonOCRError", "ocr_document",
|
|
19
|
+
"parse_elements", "to_markdown", "to_pixels", "draw_layout", "parse_json", "CATEGORIES",
|
|
20
|
+
"load_pages", "render_pdf_pages", "upscale_min_long",
|
|
21
|
+
"PARSE_PROMPT", "EXTRACT_ALL_PROMPT", "V15_PROMPT",
|
|
22
|
+
]
|
typhoon_ocr2/cli.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""Command line: typhoon-ocr2 FILE [options]"""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
from . import __version__
|
|
9
|
+
from .client import TyphoonOCR, TyphoonOCRError
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _pages_json(results) -> str:
|
|
13
|
+
"""Pretty JSON with one element per line, so long pages stay readable."""
|
|
14
|
+
pages = []
|
|
15
|
+
for r in results:
|
|
16
|
+
els = ",\n".join(" " + json.dumps(e, ensure_ascii=False) for e in r.elements)
|
|
17
|
+
pages.append(" {\n"
|
|
18
|
+
f' "page": {r.page}, "width": {r.image_size[0]}, "height": {r.image_size[1]},\n'
|
|
19
|
+
f' "truncated": {json.dumps(r.truncated)},\n'
|
|
20
|
+
f' "elements": [\n{els}\n ],\n' if r.elements else
|
|
21
|
+
" {\n"
|
|
22
|
+
f' "page": {r.page}, "width": {r.image_size[0]}, "height": {r.image_size[1]},\n'
|
|
23
|
+
f' "truncated": {json.dumps(r.truncated)},\n'
|
|
24
|
+
' "elements": [],\n')
|
|
25
|
+
pages[-1] += f' "markdown": {json.dumps(r.markdown, ensure_ascii=False)}\n }}'
|
|
26
|
+
return "[\n" + ",\n".join(pages) + "\n]"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def main(argv=None) -> int:
|
|
30
|
+
ap = argparse.ArgumentParser(prog="typhoon-ocr2", description="Parse a PDF or image with Typhoon OCR.")
|
|
31
|
+
ap.add_argument("file", help="PDF or image")
|
|
32
|
+
ap.add_argument("--pages", help="PDF pages, e.g. 1-3,5 (default: all)")
|
|
33
|
+
ap.add_argument("--base-url", help="server URL (default: $TYPHOON_OCR_BASE_URL or http://localhost:8000/v1; "
|
|
34
|
+
"Typhoon API: https://api.opentyphoon.ai/v1; Ollama: http://localhost:11434)")
|
|
35
|
+
ap.add_argument("--model", help="served model name (default: the server's first model; Ollama: SuraponOCR/typhoon-ocr2-2b)")
|
|
36
|
+
ap.add_argument("--api-key", help="API key (default: $TYPHOON_OCR_API_KEY / $TYPHOON_API_KEY)")
|
|
37
|
+
ap.add_argument("--backend", choices=["auto", "openai", "ollama"], default="auto")
|
|
38
|
+
ap.add_argument("--version", dest="model_version", choices=["v2", "v1.5"], default=None,
|
|
39
|
+
help="Typhoon OCR version (default: follows --model; v2 otherwise)")
|
|
40
|
+
ap.add_argument("--format", choices=["md", "json"], default="md",
|
|
41
|
+
help="md: Markdown; json: one object per page with the layout elements")
|
|
42
|
+
ap.add_argument("--keep-header-footer", action="store_true", help="keep headers, footers and page footnotes in Markdown")
|
|
43
|
+
ap.add_argument("--exclude", nargs="*", metavar="CATEGORY",
|
|
44
|
+
help="categories to leave out of the Markdown, e.g. --exclude footer page_footnote "
|
|
45
|
+
"(default: header footer page_footnote; --exclude with no names keeps everything)")
|
|
46
|
+
ap.add_argument("--ask", metavar="QUESTION", help="ask a question about the page instead of parsing it (2B)")
|
|
47
|
+
ap.add_argument("--extract", nargs="*", metavar="FIELD",
|
|
48
|
+
help="extract key information as JSON (2B); list fields, or none to let the model choose")
|
|
49
|
+
ap.add_argument("--no-upscale", action="store_true", help="do not enlarge images under 1,600 px")
|
|
50
|
+
ap.add_argument("-V", "--package-version", action="version", version=f"typhoon-ocr2 {__version__}")
|
|
51
|
+
a = ap.parse_args(argv)
|
|
52
|
+
|
|
53
|
+
ocr = TyphoonOCR(base_url=a.base_url, model=a.model, api_key=a.api_key, backend=a.backend,
|
|
54
|
+
version=a.model_version, upscale=not a.no_upscale)
|
|
55
|
+
page = int(a.pages.split(",")[0].split("-")[0]) if a.pages else 1
|
|
56
|
+
try:
|
|
57
|
+
if a.ask:
|
|
58
|
+
print(ocr.ask(a.file, a.ask, page))
|
|
59
|
+
elif a.extract is not None:
|
|
60
|
+
print(json.dumps(ocr.extract(a.file, a.extract or None, page), ensure_ascii=False, indent=2))
|
|
61
|
+
else:
|
|
62
|
+
results = ocr.parse(a.file, a.pages, a.keep_header_footer, a.exclude)
|
|
63
|
+
for r in results:
|
|
64
|
+
if r.truncated:
|
|
65
|
+
print(f"warning: page {r.page} stopped at the token limit; only complete elements are kept",
|
|
66
|
+
file=sys.stderr)
|
|
67
|
+
if a.format == "json":
|
|
68
|
+
print(_pages_json(results))
|
|
69
|
+
else:
|
|
70
|
+
print("\n\n".join(r.markdown for r in results))
|
|
71
|
+
except (TyphoonOCRError, ValueError, OSError) as e:
|
|
72
|
+
print(f"error: {e}", file=sys.stderr)
|
|
73
|
+
return 1
|
|
74
|
+
finally:
|
|
75
|
+
ocr.close()
|
|
76
|
+
return 0
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
if __name__ == "__main__":
|
|
80
|
+
sys.exit(main())
|
typhoon_ocr2/client.py
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
"""Client for Typhoon OCR models served by vLLM, llama.cpp, MLX (mlx-vlm), Ollama or the Typhoon API."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import os
|
|
5
|
+
import re
|
|
6
|
+
import warnings
|
|
7
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from typing import Dict, List, Optional, Sequence, Tuple, Union
|
|
10
|
+
from urllib.parse import urlparse
|
|
11
|
+
|
|
12
|
+
import httpx
|
|
13
|
+
from PIL import Image
|
|
14
|
+
|
|
15
|
+
from . import images as im
|
|
16
|
+
from .output import parse_elements, parse_json, to_markdown
|
|
17
|
+
from .prompts import EXTRACT_ALL_PROMPT, PARSE_PROMPT, extract_fields_prompt, v15_prompt
|
|
18
|
+
|
|
19
|
+
DEFAULT_BASE_URL = "http://localhost:8000/v1"
|
|
20
|
+
DEFAULT_OLLAMA_MODEL = "SuraponOCR/typhoon-ocr2-2b"
|
|
21
|
+
TYPHOON_API_URL = "https://api.opentyphoon.ai/v1"
|
|
22
|
+
TYPHOON_API_MODELS = {"v2": "typhoon-ocr-v2", "v1.5": "typhoon-ocr-v1.5"} # model names on the Typhoon API
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class TyphoonOCRError(RuntimeError):
|
|
26
|
+
"""The server returned an error, or the output could not be used."""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class PageResult:
|
|
31
|
+
"""One parsed page. `elements` is empty for Typhoon OCR 1.5, which returns Markdown only."""
|
|
32
|
+
page: int
|
|
33
|
+
markdown: str
|
|
34
|
+
elements: List[Dict] = field(default_factory=list)
|
|
35
|
+
raw: str = ""
|
|
36
|
+
finish_reason: Optional[str] = None
|
|
37
|
+
image_size: Tuple[int, int] = (0, 0) # (width, height) of the page image, for to_pixels()
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
def truncated(self) -> bool:
|
|
41
|
+
"""True when the output stopped at the token limit (usually a repetition loop)."""
|
|
42
|
+
return self.finish_reason == "length"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class TyphoonOCR:
|
|
46
|
+
"""Parse documents with Typhoon OCR.
|
|
47
|
+
|
|
48
|
+
>>> ocr = TyphoonOCR(base_url="https://api.opentyphoon.ai/v1", model="typhoon-ocr-v2", version="v2")
|
|
49
|
+
>>> pages = ocr.parse("report.pdf", pages="1-3")
|
|
50
|
+
>>> print(pages[0].markdown)
|
|
51
|
+
|
|
52
|
+
Args:
|
|
53
|
+
base_url: server URL. OpenAI-compatible servers (Typhoon API, vLLM, llama.cpp, mlx-vlm) end in "/v1";
|
|
54
|
+
Ollama is "http://localhost:11434". Defaults to $TYPHOON_OCR_BASE_URL, then "http://localhost:8000/v1".
|
|
55
|
+
model: the model's name on the server. When None: "typhoon-ocr-v2" / "typhoon-ocr-v1.5" on the Typhoon
|
|
56
|
+
API (following `version`), "SuraponOCR/typhoon-ocr2-2b" on Ollama, else the server's first model.
|
|
57
|
+
api_key: for the Typhoon API or another server that needs one. Defaults to $TYPHOON_API_KEY,
|
|
58
|
+
$TYPHOON_OCR_API_KEY or $OPENAI_API_KEY.
|
|
59
|
+
backend: "openai", "ollama", or "auto" (Ollama when the URL has no "/v1" path and port 11434).
|
|
60
|
+
version: "v2" (Typhoon OCR V2: layout elements and Markdown) or "v1.5" (Typhoon OCR 1.5: Markdown).
|
|
61
|
+
Sets the prompt and output format. When None, it follows the model name (v1.5 for 1.5 models,
|
|
62
|
+
otherwise v2).
|
|
63
|
+
upscale: True (default) enlarges images whose long side is under 1,600 px; False turns it off; an
|
|
64
|
+
int sets another size. V2 only.
|
|
65
|
+
max_tokens: output token limit per page.
|
|
66
|
+
pdf_long_side: long side, in pixels, of rendered PDF pages.
|
|
67
|
+
max_workers: pages sent in parallel when parsing a multi-page document.
|
|
68
|
+
timeout: seconds to wait for one page.
|
|
69
|
+
"""
|
|
70
|
+
|
|
71
|
+
def __init__(self, base_url: Optional[str] = None, model: Optional[str] = None, api_key: Optional[str] = None,
|
|
72
|
+
backend: str = "auto", version: Optional[str] = None, upscale: Union[bool, int] = True,
|
|
73
|
+
max_tokens: int = 16384, pdf_long_side: int = im.PDF_LONG_SIDE, max_workers: int = 4,
|
|
74
|
+
timeout: float = 600.0, figure_language: str = "Thai"):
|
|
75
|
+
if version not in (None, "v2", "v1.5"):
|
|
76
|
+
raise ValueError("version must be 'v2' or 'v1.5'")
|
|
77
|
+
self.base_url = (base_url or os.getenv("TYPHOON_OCR_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
|
|
78
|
+
self.backend = _detect_backend(self.base_url) if backend == "auto" else backend
|
|
79
|
+
if self.backend not in ("openai", "ollama"):
|
|
80
|
+
raise ValueError("backend must be 'openai', 'ollama' or 'auto'")
|
|
81
|
+
self.api_key = api_key or os.getenv("TYPHOON_API_KEY") or os.getenv("TYPHOON_OCR_API_KEY") or os.getenv("OPENAI_API_KEY")
|
|
82
|
+
self._model = model or os.getenv("TYPHOON_OCR_MODEL")
|
|
83
|
+
implied = _version_of(self._model)
|
|
84
|
+
if version and implied and version != implied:
|
|
85
|
+
warnings.warn(f"model {self._model!r} looks like Typhoon OCR {implied}, but version={version!r}: "
|
|
86
|
+
f"the {version} prompt will be sent to it", stacklevel=2)
|
|
87
|
+
self.version = version or implied or "v2"
|
|
88
|
+
self.upscale = im.UPSCALE_MIN_LONG if upscale is True else int(upscale or 0)
|
|
89
|
+
self.max_tokens = max_tokens
|
|
90
|
+
self.pdf_long_side, self.max_workers, self.figure_language = pdf_long_side, max_workers, figure_language
|
|
91
|
+
self._client = httpx.Client(timeout=timeout, headers={"Authorization": f"Bearer {self.api_key}"} if self.api_key else {})
|
|
92
|
+
|
|
93
|
+
# ---------------------------------------------------------------- public API
|
|
94
|
+
@property
|
|
95
|
+
def model(self) -> str:
|
|
96
|
+
if not self._model:
|
|
97
|
+
if self.backend == "ollama":
|
|
98
|
+
self._model = DEFAULT_OLLAMA_MODEL
|
|
99
|
+
elif _is_typhoon_api(self.base_url):
|
|
100
|
+
self._model = TYPHOON_API_MODELS[self.version]
|
|
101
|
+
else:
|
|
102
|
+
self._model = self._first_served_model()
|
|
103
|
+
return self._model
|
|
104
|
+
|
|
105
|
+
def parse(self, source: im.ImageInput, pages: Union[None, int, str, Sequence[int]] = None,
|
|
106
|
+
keep_header_footer: bool = False, exclude: Optional[Sequence[str]] = None) -> List[PageResult]:
|
|
107
|
+
"""Parse each page. `pages` selects PDF pages (1-based), e.g. 2, "1-3,5" or [1, 4].
|
|
108
|
+
|
|
109
|
+
`page.elements` always holds every element the model returned. `page.markdown` leaves out header,
|
|
110
|
+
footer and page_footnote elements unless `keep_header_footer=True`; `exclude` picks the categories to
|
|
111
|
+
leave out yourself (e.g. ["footer"], or [] to keep everything)."""
|
|
112
|
+
page_numbers = im.parse_pages(pages)
|
|
113
|
+
page_images = im.load_pages(source, page_numbers, self.pdf_long_side)
|
|
114
|
+
numbers = page_numbers or list(range(1, len(page_images) + 1))
|
|
115
|
+
|
|
116
|
+
def one(args):
|
|
117
|
+
n, page = args
|
|
118
|
+
prompt = PARSE_PROMPT if self.version == "v2" else v15_prompt(self.figure_language)
|
|
119
|
+
raw, finish = self._generate(self._prepare(page), prompt)
|
|
120
|
+
if self.version == "v1.5":
|
|
121
|
+
return PageResult(n, raw, [], raw, finish, page.size)
|
|
122
|
+
try:
|
|
123
|
+
elements = parse_elements(raw)
|
|
124
|
+
except ValueError:
|
|
125
|
+
elements = []
|
|
126
|
+
return PageResult(n, to_markdown(elements, keep_header_footer, exclude), elements, raw, finish, page.size)
|
|
127
|
+
|
|
128
|
+
jobs = list(zip(numbers, page_images))
|
|
129
|
+
if len(jobs) == 1 or self.max_workers <= 1:
|
|
130
|
+
return [one(j) for j in jobs]
|
|
131
|
+
with ThreadPoolExecutor(self.max_workers) as pool:
|
|
132
|
+
return list(pool.map(one, jobs))
|
|
133
|
+
|
|
134
|
+
def ocr(self, source: im.ImageInput, pages: Union[None, int, str, Sequence[int]] = None,
|
|
135
|
+
keep_header_footer: bool = False, exclude: Optional[Sequence[str]] = None) -> str:
|
|
136
|
+
"""Markdown of the selected pages, separated by blank lines."""
|
|
137
|
+
return "\n\n".join(p.markdown for p in self.parse(source, pages, keep_header_footer, exclude))
|
|
138
|
+
|
|
139
|
+
def ask(self, source: im.ImageInput, question: str, page: int = 1) -> str:
|
|
140
|
+
"""Ask a question about one page (Typhoon OCR V2 2B). Returns the answer as text."""
|
|
141
|
+
image = im.load_pages(source, [page] if im.is_pdf(source) else None, self.pdf_long_side)[0]
|
|
142
|
+
return self._generate(self._prepare(image), question)[0].strip()
|
|
143
|
+
|
|
144
|
+
def extract(self, source: im.ImageInput, fields: Optional[Sequence[str]] = None, page: int = 1):
|
|
145
|
+
"""Extract key information as JSON (Typhoon OCR V2 2B). Without `fields`, the model picks the
|
|
146
|
+
fields itself, using the printed labels as keys. Raises TyphoonOCRError if the answer is not JSON."""
|
|
147
|
+
prompt = EXTRACT_ALL_PROMPT if not fields else extract_fields_prompt(fields)
|
|
148
|
+
raw = self.ask(source, prompt, page)
|
|
149
|
+
data = parse_json(raw)
|
|
150
|
+
if data is None:
|
|
151
|
+
raise TyphoonOCRError(f"the answer is not valid JSON: {raw[:300]!r}")
|
|
152
|
+
return data
|
|
153
|
+
|
|
154
|
+
def close(self) -> None:
|
|
155
|
+
self._client.close()
|
|
156
|
+
|
|
157
|
+
def __enter__(self):
|
|
158
|
+
return self
|
|
159
|
+
|
|
160
|
+
def __exit__(self, *exc):
|
|
161
|
+
self.close()
|
|
162
|
+
|
|
163
|
+
# ---------------------------------------------------------------- internals
|
|
164
|
+
def _prepare(self, image: Image.Image) -> Image.Image:
|
|
165
|
+
if self.version == "v1.5":
|
|
166
|
+
return _resize_v15(image)
|
|
167
|
+
return im.upscale_min_long(image, self.upscale) if self.upscale else image
|
|
168
|
+
|
|
169
|
+
def _generate(self, image: Image.Image, prompt: str) -> Tuple[str, Optional[str]]:
|
|
170
|
+
if self.backend == "ollama":
|
|
171
|
+
body = {"model": self.model, "stream": False, "think": False,
|
|
172
|
+
"messages": [{"role": "user", "content": prompt, "images": [im.to_base64_png(image)]}],
|
|
173
|
+
"options": {"temperature": 0, "top_p": 1.0, "num_predict": self.max_tokens, "num_ctx": 40960}}
|
|
174
|
+
if self.version == "v1.5":
|
|
175
|
+
body["options"].update(temperature=0.1, top_p=0.6, repeat_penalty=1.1)
|
|
176
|
+
d = self._post(f"{self.base_url}/api/chat", body)
|
|
177
|
+
return d["message"]["content"], d.get("done_reason")
|
|
178
|
+
body = {"model": self.model, "max_tokens": self.max_tokens,
|
|
179
|
+
"messages": [{"role": "user", "content": [
|
|
180
|
+
{"type": "image_url", "image_url": {"url": im.to_data_url(image)}},
|
|
181
|
+
{"type": "text", "text": prompt}]}]}
|
|
182
|
+
if self.version == "v2":
|
|
183
|
+
body.update(temperature=0.0, top_p=1.0, chat_template_kwargs={"enable_thinking": False})
|
|
184
|
+
else: # Typhoon OCR 1.5 settings from the original typhoon-ocr package
|
|
185
|
+
body.update(temperature=0.1, top_p=0.6, repetition_penalty=1.1)
|
|
186
|
+
try:
|
|
187
|
+
d = self._post(f"{self.base_url}/chat/completions", body)
|
|
188
|
+
except TyphoonOCRError as e:
|
|
189
|
+
# Some OpenAI-compatible gateways reject vLLM's chat_template_kwargs: retry once without it.
|
|
190
|
+
if "chat_template_kwargs" not in body or "chat_template_kwargs" not in str(e):
|
|
191
|
+
raise
|
|
192
|
+
body.pop("chat_template_kwargs")
|
|
193
|
+
d = self._post(f"{self.base_url}/chat/completions", body)
|
|
194
|
+
d = d["choices"][0]
|
|
195
|
+
return d["message"].get("content") or "", d.get("finish_reason")
|
|
196
|
+
|
|
197
|
+
def _post(self, url: str, body: dict) -> dict:
|
|
198
|
+
try:
|
|
199
|
+
r = self._client.post(url, json=body)
|
|
200
|
+
except httpx.HTTPError as e:
|
|
201
|
+
raise TyphoonOCRError(f"cannot reach {url}: {e}") from e
|
|
202
|
+
if r.status_code >= 400:
|
|
203
|
+
raise TyphoonOCRError(f"{url} returned {r.status_code}: {r.text[:500]}")
|
|
204
|
+
return r.json()
|
|
205
|
+
|
|
206
|
+
def _first_served_model(self) -> str:
|
|
207
|
+
try:
|
|
208
|
+
r = self._client.get(f"{self.base_url}/models")
|
|
209
|
+
r.raise_for_status()
|
|
210
|
+
data = r.json()
|
|
211
|
+
models = data["data"] if isinstance(data, dict) else data # vLLM: {"data": [...]}; some APIs: [...]
|
|
212
|
+
return models[0]["id"]
|
|
213
|
+
except Exception as e:
|
|
214
|
+
raise TyphoonOCRError(f"pass model=...: could not list the models served at {self.base_url} ({e})") from e
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _detect_backend(base_url: str) -> str:
|
|
218
|
+
u = urlparse(base_url)
|
|
219
|
+
return "ollama" if u.port == 11434 and not u.path.rstrip("/").endswith("/v1") else "openai"
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _version_of(model: Optional[str]) -> Optional[str]:
|
|
223
|
+
"""'v1.5' for Typhoon OCR 1.5 model names (typhoon-ocr, typhoon-ocr-v1.5, typhoon-ai/typhoon-ocr1.5-2b),
|
|
224
|
+
'v2' for V2 names (typhoon-ocr-v2, typhoon-ai/typhoon-ocr2-2b), None when the name says nothing."""
|
|
225
|
+
if not model:
|
|
226
|
+
return None
|
|
227
|
+
name = model.lower().rsplit("/", 1)[-1]
|
|
228
|
+
if re.search(r"ocr-?v?1\.5", name) or name == "typhoon-ocr":
|
|
229
|
+
return "v1.5"
|
|
230
|
+
if re.search(r"ocr-?v?2", name):
|
|
231
|
+
return "v2"
|
|
232
|
+
return None
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _is_typhoon_api(base_url: str) -> bool:
|
|
236
|
+
return urlparse(base_url).hostname == urlparse(TYPHOON_API_URL).hostname
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _resize_v15(image: Image.Image, long_side: int = 1800) -> Image.Image:
|
|
240
|
+
"""Typhoon OCR 1.5 resizing from the original package: the long side becomes 1800 px."""
|
|
241
|
+
w, h = image.size
|
|
242
|
+
if w <= 300 and h <= 300:
|
|
243
|
+
return image
|
|
244
|
+
s = long_side / max(w, h)
|
|
245
|
+
return image.resize((round(w * s), round(h * s)), Image.LANCZOS)
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def ocr_document(source: im.ImageInput, pages: Union[None, int, str, Sequence[int]] = None, **kwargs) -> str:
|
|
249
|
+
"""One call: parse a PDF or image and return Markdown. Keyword arguments go to TyphoonOCR."""
|
|
250
|
+
with TyphoonOCR(**kwargs) as ocr:
|
|
251
|
+
return ocr.ocr(source, pages)
|
typhoon_ocr2/images.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""Load pages from images and PDFs, and prepare them for the model."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import base64
|
|
5
|
+
import io
|
|
6
|
+
import os
|
|
7
|
+
from typing import Iterable, List, Optional, Sequence, Union
|
|
8
|
+
|
|
9
|
+
from PIL import Image
|
|
10
|
+
|
|
11
|
+
ImageInput = Union[str, os.PathLike, bytes, Image.Image]
|
|
12
|
+
|
|
13
|
+
# Images whose long side is below this are enlarged before they are sent. On ThaiOCRBench this raised
|
|
14
|
+
# Typhoon OCR V2 2B from 59.9 to 62.9 and 0.8B from 37.3 to 41.3; on large pages it changes nothing.
|
|
15
|
+
UPSCALE_MIN_LONG = 1600
|
|
16
|
+
# PDF pages are rendered with this long side, as in our olmOCR-bench evaluation.
|
|
17
|
+
PDF_LONG_SIDE = 2048
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def upscale_min_long(image: Image.Image, min_long: int = UPSCALE_MIN_LONG) -> Image.Image:
|
|
21
|
+
"""Enlarge the image so that its long side is at least `min_long` pixels, keeping the aspect
|
|
22
|
+
ratio. Images that are already large enough are returned unchanged."""
|
|
23
|
+
scale = min_long / max(image.size)
|
|
24
|
+
if scale <= 1:
|
|
25
|
+
return image
|
|
26
|
+
return image.resize((round(image.width * scale), round(image.height * scale)), Image.LANCZOS)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def is_pdf(source: ImageInput) -> bool:
|
|
30
|
+
if isinstance(source, (str, os.PathLike)):
|
|
31
|
+
return str(source).lower().endswith(".pdf")
|
|
32
|
+
if isinstance(source, bytes):
|
|
33
|
+
return source[:5] == b"%PDF-"
|
|
34
|
+
return False
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def pdf_page_count(source: Union[str, os.PathLike, bytes]) -> int:
|
|
38
|
+
pdfium = _pdfium()
|
|
39
|
+
doc = pdfium.PdfDocument(source)
|
|
40
|
+
try:
|
|
41
|
+
return len(doc)
|
|
42
|
+
finally:
|
|
43
|
+
doc.close()
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def render_pdf_pages(source: Union[str, os.PathLike, bytes], pages: Optional[Iterable[int]] = None,
|
|
47
|
+
long_side: int = PDF_LONG_SIDE) -> List[Image.Image]:
|
|
48
|
+
"""Render PDF pages (1-based numbers; all pages when `pages` is None) to RGB images whose long side
|
|
49
|
+
is `long_side` pixels."""
|
|
50
|
+
pdfium = _pdfium()
|
|
51
|
+
doc = pdfium.PdfDocument(source)
|
|
52
|
+
try:
|
|
53
|
+
n = len(doc)
|
|
54
|
+
numbers = list(range(1, n + 1)) if pages is None else list(pages)
|
|
55
|
+
out = []
|
|
56
|
+
for p in numbers:
|
|
57
|
+
if not 1 <= p <= n:
|
|
58
|
+
raise ValueError(f"page {p} is out of range: the PDF has {n} page(s)")
|
|
59
|
+
page = doc[p - 1]
|
|
60
|
+
w, h = page.get_size() # in points (1/72 inch)
|
|
61
|
+
bitmap = page.render(scale=long_side / max(w, h))
|
|
62
|
+
out.append(bitmap.to_pil().convert("RGB"))
|
|
63
|
+
page.close()
|
|
64
|
+
return out
|
|
65
|
+
finally:
|
|
66
|
+
doc.close()
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def load_pages(source: ImageInput, pages: Optional[Iterable[int]] = None,
|
|
70
|
+
pdf_long_side: int = PDF_LONG_SIDE) -> List[Image.Image]:
|
|
71
|
+
"""Return the pages of a PDF, or a single image, as RGB PIL images.
|
|
72
|
+
|
|
73
|
+
`source` can be a file path, raw bytes, or a PIL image. `pages` (1-based) applies to PDFs only."""
|
|
74
|
+
if isinstance(source, Image.Image):
|
|
75
|
+
return [source.convert("RGB")]
|
|
76
|
+
if is_pdf(source):
|
|
77
|
+
return render_pdf_pages(source, pages, pdf_long_side)
|
|
78
|
+
if pages is not None and list(pages) not in ([], [1]):
|
|
79
|
+
raise ValueError("`pages` can only be used with PDFs; an image has one page")
|
|
80
|
+
data = io.BytesIO(source) if isinstance(source, bytes) else source
|
|
81
|
+
with Image.open(data) as im:
|
|
82
|
+
return [im.convert("RGB")]
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def to_base64_png(image: Image.Image) -> str:
|
|
86
|
+
buf = io.BytesIO()
|
|
87
|
+
image.save(buf, format="PNG")
|
|
88
|
+
return base64.b64encode(buf.getvalue()).decode()
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def to_data_url(image: Image.Image) -> str:
|
|
92
|
+
return "data:image/png;base64," + to_base64_png(image)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def parse_pages(spec: Optional[Union[str, int, Sequence[int]]]) -> Optional[List[int]]:
|
|
96
|
+
"""'1-3,5' -> [1, 2, 3, 5]; an int -> [int]; None -> None (all pages)."""
|
|
97
|
+
if spec is None or isinstance(spec, (list, tuple)):
|
|
98
|
+
return None if spec is None else [int(p) for p in spec]
|
|
99
|
+
if isinstance(spec, int):
|
|
100
|
+
return [spec]
|
|
101
|
+
out: List[int] = []
|
|
102
|
+
for part in str(spec).split(","):
|
|
103
|
+
part = part.strip()
|
|
104
|
+
if not part:
|
|
105
|
+
continue
|
|
106
|
+
if "-" in part:
|
|
107
|
+
a, b = part.split("-", 1)
|
|
108
|
+
out.extend(range(int(a), int(b) + 1))
|
|
109
|
+
else:
|
|
110
|
+
out.append(int(part))
|
|
111
|
+
return out
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _pdfium():
|
|
115
|
+
try:
|
|
116
|
+
import pypdfium2 as pdfium
|
|
117
|
+
except ImportError as e: # pragma: no cover - it is a dependency, but give a clear message anyway
|
|
118
|
+
raise ImportError("PDF support needs pypdfium2: pip install pypdfium2") from e
|
|
119
|
+
return pdfium
|
typhoon_ocr2/output.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""Turn Typhoon OCR V2 output into layout elements, Markdown and pixel boxes."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import re
|
|
6
|
+
from typing import Dict, Iterable, List, Optional, Sequence
|
|
7
|
+
|
|
8
|
+
from PIL import Image, ImageDraw
|
|
9
|
+
|
|
10
|
+
CATEGORIES = ("header", "title", "text", "figure", "table", "formula", "figure_caption", "table_caption",
|
|
11
|
+
"formula_caption", "figure_footnote", "table_footnote", "page_footnote", "footer")
|
|
12
|
+
HEADER_FOOTER = frozenset({"header", "footer", "page_footnote"})
|
|
13
|
+
|
|
14
|
+
_FENCE = re.compile(r"```(?:json)?\s*\n(.*?)(?:\n```|$)", re.DOTALL)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def parse_elements(raw: str) -> List[Dict]:
|
|
18
|
+
"""Parse the model output, a JSON list of elements, usually inside a ```json fence.
|
|
19
|
+
|
|
20
|
+
If the output stopped at the token limit, the last, incomplete element is dropped and the complete
|
|
21
|
+
ones are returned. Raises ValueError when no element can be recovered."""
|
|
22
|
+
m = _FENCE.search(raw)
|
|
23
|
+
text = (m.group(1) if m else raw).strip()
|
|
24
|
+
try:
|
|
25
|
+
data = json.loads(text)
|
|
26
|
+
except json.JSONDecodeError:
|
|
27
|
+
cut = text.rfind('{"bbox":')
|
|
28
|
+
if cut <= 0:
|
|
29
|
+
raise ValueError("the model output is not a JSON list of elements") from None
|
|
30
|
+
try:
|
|
31
|
+
data = json.loads(text[:cut].rstrip().rstrip(",") + "]")
|
|
32
|
+
except json.JSONDecodeError:
|
|
33
|
+
raise ValueError("the model output is not a JSON list of elements") from None
|
|
34
|
+
if isinstance(data, dict): # the prompt asks for "a JSON object"; accept {"...": [elements]}
|
|
35
|
+
lists = [v for v in data.values() if isinstance(v, list)]
|
|
36
|
+
data = lists[0] if len(lists) == 1 else [data]
|
|
37
|
+
if not isinstance(data, list):
|
|
38
|
+
raise ValueError("the model output is not a JSON list of elements")
|
|
39
|
+
return [e for e in data if isinstance(e, dict)]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def to_markdown(elements: Sequence[Dict], keep_header_footer: bool = False,
|
|
43
|
+
exclude: Optional[Iterable[str]] = None) -> str:
|
|
44
|
+
"""Join the text of the elements in reading order.
|
|
45
|
+
|
|
46
|
+
By default, header, footer and page_footnote elements are left out (we evaluated the model this way).
|
|
47
|
+
`keep_header_footer=True` keeps every element. `exclude` sets exactly which categories to leave out,
|
|
48
|
+
e.g. exclude=["footer"] keeps headers but drops footers, and exclude=[] keeps everything."""
|
|
49
|
+
if exclude is not None:
|
|
50
|
+
skip = set(exclude)
|
|
51
|
+
unknown = skip - set(CATEGORIES)
|
|
52
|
+
if unknown:
|
|
53
|
+
raise ValueError(f"unknown categories {sorted(unknown)}; choose from {list(CATEGORIES)}")
|
|
54
|
+
else:
|
|
55
|
+
skip = set() if keep_header_footer else HEADER_FOOTER
|
|
56
|
+
return "\n\n".join(e["text"] for e in elements if e.get("text") and e.get("category") not in skip)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def to_pixels(bbox: Sequence[float], width: int, height: int) -> List[float]:
|
|
60
|
+
"""Map a box on the model's 0-1000 grid to pixels of an image of the given size."""
|
|
61
|
+
x1, y1, x2, y2 = bbox
|
|
62
|
+
x1, x2 = sorted((x1, x2))
|
|
63
|
+
y1, y2 = sorted((y1, y2))
|
|
64
|
+
return [x1 * width / 1000, y1 * height / 1000, x2 * width / 1000, y2 * height / 1000]
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
_COLORS = {"title": (228, 87, 46), "text": (91, 84, 214), "table": (42, 157, 85), "figure": (192, 138, 0),
|
|
68
|
+
"formula": (181, 23, 158)}
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def draw_layout(image: Image.Image, elements: Sequence[Dict], numbers: bool = True) -> Image.Image:
|
|
72
|
+
"""Return a copy of `image` with the element boxes drawn on it, numbered in reading order."""
|
|
73
|
+
out = image.convert("RGB").copy()
|
|
74
|
+
d = ImageDraw.Draw(out, "RGBA")
|
|
75
|
+
w, h = out.size
|
|
76
|
+
lw = max(2, round(max(w, h) / 600))
|
|
77
|
+
for i, e in enumerate(elements, 1):
|
|
78
|
+
if not e.get("bbox") or len(e["bbox"]) != 4:
|
|
79
|
+
continue
|
|
80
|
+
box = to_pixels(e["bbox"], w, h)
|
|
81
|
+
c = _COLORS.get(e.get("category"), (127, 127, 127))
|
|
82
|
+
d.rectangle(box, outline=c + (255,), width=lw, fill=c + (28,))
|
|
83
|
+
if numbers:
|
|
84
|
+
d.text((box[0] + lw, box[1] + lw), str(i), fill=c + (255,))
|
|
85
|
+
return out
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def parse_json(raw: str) -> Optional[object]:
|
|
89
|
+
"""Parse a JSON answer (key-information extraction), with or without a ```json fence.
|
|
90
|
+
Returns None when the answer is not valid JSON."""
|
|
91
|
+
m = _FENCE.search(raw)
|
|
92
|
+
try:
|
|
93
|
+
return json.loads((m.group(1) if m else raw).strip())
|
|
94
|
+
except json.JSONDecodeError:
|
|
95
|
+
return None
|
typhoon_ocr2/prompts.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""Prompts the Typhoon OCR models were trained with. Use them exactly as written."""
|
|
2
|
+
|
|
3
|
+
# Typhoon OCR V2: full-page parsing into layout elements (the doc2json prompt from Infinity-Parser2).
|
|
4
|
+
PARSE_PROMPT = """- Extract layout information from the provided PDF image.
|
|
5
|
+
- For each layout element, output its bbox, category, and the text content within the bbox.
|
|
6
|
+
- Bbox format: [x1, y1, x2, y2].
|
|
7
|
+
- Allowed layout categories: ['header', 'title', 'text', 'figure', 'table', 'formula', 'figure_caption', 'table_caption', 'formula_caption', 'figure_footnote', 'table_footnote', 'page_footnote', 'footer'].
|
|
8
|
+
- Text extraction and formatting:
|
|
9
|
+
1) For 'figure', the text field must be an empty string.
|
|
10
|
+
2) For 'formula', format text as LaTeX.
|
|
11
|
+
3) For 'table', format text as HTML.
|
|
12
|
+
4) For all other categories (e.g., text, title), format text as Markdown.
|
|
13
|
+
- The output text must be exactly the original text from the image, with no translation or rewriting.
|
|
14
|
+
- Sort all layout elements in human reading order.
|
|
15
|
+
- Final output must be a single JSON object."""
|
|
16
|
+
|
|
17
|
+
# Typhoon OCR V2 2B: extract every field as JSON without naming the fields.
|
|
18
|
+
EXTRACT_ALL_PROMPT = 'Perform open-schema key information extraction (WYSIWYG) on this image: one JSON object, printed labels as keys, values copied exactly, "" for blank fields, arrays for repeated rows. Return only JSON.'
|
|
19
|
+
|
|
20
|
+
# Typhoon OCR 1.5: full-page Markdown. `figure_language` is "Thai" or "English".
|
|
21
|
+
V15_PROMPT = """Extract all text from the image.
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
Instructions:
|
|
25
|
+
- Only return the clean Markdown.
|
|
26
|
+
- Do not include any explanation or extra text.
|
|
27
|
+
- You must include all information on the page.
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
Formatting Rules:
|
|
31
|
+
- Tables: Render tables using <table>...</table> in clean HTML format.
|
|
32
|
+
- Equations: Render equations using LaTeX syntax with inline ($...$) and block ($$...$$).
|
|
33
|
+
- Images/Charts/Diagrams: Wrap any clearly defined visual areas (e.g. charts, diagrams, pictures) in:
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
<figure>
|
|
37
|
+
Describe the image's main elements (people, objects, text), note any contextual clues (place, event, culture), mention visible text and its meaning, provide deeper analysis when relevant (especially for financial charts, graphs, or documents), comment on style or architecture if relevant, then give a concise overall summary. Describe in {figure_language}.
|
|
38
|
+
</figure>
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
- Page Numbers: Wrap page numbers in <page_number>...</page_number> (e.g., <page_number>14</page_number>).
|
|
42
|
+
- Checkboxes: Use ☐ for unchecked and ☑ for checked boxes.
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def v15_prompt(figure_language: str = "Thai") -> str:
|
|
47
|
+
if figure_language not in ("Thai", "English"):
|
|
48
|
+
raise ValueError("figure_language must be 'Thai' or 'English'")
|
|
49
|
+
return V15_PROMPT.format(figure_language=figure_language)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def extract_fields_prompt(fields) -> str:
|
|
53
|
+
"""Prompt for extracting named fields as one JSON object (Typhoon OCR V2 2B)."""
|
|
54
|
+
keys = "\n".join(str(f) for f in fields)
|
|
55
|
+
return (
|
|
56
|
+
"Extract the following fields from the image and return one JSON object with exactly these keys. "
|
|
57
|
+
"Copy values exactly as they appear; use \"\" for fields that are missing or blank. Return only JSON.\n" + keys
|
|
58
|
+
)
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: typhoon-ocr2
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Parse Thai and English documents (PDFs and images) into layout elements and Markdown with Typhoon OCR V2
|
|
5
|
+
Author: Surapon Nonesung
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/srn-source/typhoon-ocr2
|
|
8
|
+
Project-URL: Model (2B), https://huggingface.co/typhoon-ai/typhoon-ocr2-2b
|
|
9
|
+
Project-URL: Model (0.8B), https://huggingface.co/typhoon-ai/typhoon-ocr2-0.8b
|
|
10
|
+
Project-URL: Playground, https://playground.opentyphoon.ai/ocr
|
|
11
|
+
Keywords: ocr,document-parsing,layout-analysis,thai,vlm,typhoon
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Topic :: Scientific/Engineering :: Image Recognition
|
|
16
|
+
Classifier: Natural Language :: Thai
|
|
17
|
+
Classifier: Natural Language :: English
|
|
18
|
+
Requires-Python: >=3.10
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
License-File: LICENSE
|
|
21
|
+
License-File: NOTICE
|
|
22
|
+
Requires-Dist: httpx>=0.24
|
|
23
|
+
Requires-Dist: pillow>=9.0
|
|
24
|
+
Requires-Dist: pypdfium2>=4.0
|
|
25
|
+
Provides-Extra: dev
|
|
26
|
+
Requires-Dist: pytest>=7; extra == "dev"
|
|
27
|
+
Dynamic: license-file
|
|
28
|
+
|
|
29
|
+
# typhoon-ocr2
|
|
30
|
+
|
|
31
|
+
Read Thai and English documents (PDFs and images) with **Typhoon OCR**. For every page you get:
|
|
32
|
+
|
|
33
|
+
- the page as **Markdown** (tables as HTML, formulas as LaTeX), and
|
|
34
|
+
- with Typhoon OCR V2, the **layout elements** in reading order: each one has a category (title, text, table, …), a bounding box and its text.
|
|
35
|
+
|
|
36
|
+
Links: [Typhoon OCR V2 2B](https://huggingface.co/typhoon-ai/typhoon-ocr2-2b) · [Typhoon OCR V2 0.8B](https://huggingface.co/typhoon-ai/typhoon-ocr2-0.8b) · [Playground](https://playground.opentyphoon.ai/ocr) · [Typhoon API docs](https://docs.opentyphoon.ai/)
|
|
37
|
+
|
|
38
|
+
This package continues [scb-10x/typhoon-ocr](https://github.com/scb-10x/typhoon-ocr) (`pip install typhoon-ocr`) with the Typhoon team's permission. It has a new name, so code that uses `typhoon-ocr` keeps working.
|
|
39
|
+
|
|
40
|
+
## Install
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
pip install typhoon-ocr2
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
PDF support is included; you do not need to install Poppler.
|
|
47
|
+
|
|
48
|
+
## Quick start: Typhoon API (no GPU needed)
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
import os
|
|
52
|
+
from typhoon_ocr2 import TyphoonOCR
|
|
53
|
+
|
|
54
|
+
os.environ["TYPHOON_API_KEY"] = "YOUR_KEY" # your Typhoon API key (or pass api_key="YOUR_KEY" below)
|
|
55
|
+
|
|
56
|
+
ocr = TyphoonOCR(
|
|
57
|
+
base_url="https://api.opentyphoon.ai/v1", # the Typhoon API
|
|
58
|
+
version="v2", # Typhoon OCR V2 ("v1.5" for Typhoon OCR 1.5)
|
|
59
|
+
upscale=True, # enlarge images under 1,600 px (recommended; see Settings)
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
pages = ocr.parse("report.pdf", pages="1-3") # a PDF or an image; pages: "1-3", 2, [1, 4] or None for all
|
|
63
|
+
for page in pages:
|
|
64
|
+
print(f"--- page {page.page}")
|
|
65
|
+
print(page.markdown)
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## Typhoon OCR V2 or 1.5
|
|
69
|
+
|
|
70
|
+
Switch with `version`; the rest of the code stays the same.
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
ocr_v15 = TyphoonOCR(
|
|
74
|
+
base_url="https://api.opentyphoon.ai/v1",
|
|
75
|
+
version="v1.5",
|
|
76
|
+
)
|
|
77
|
+
print(ocr_v15.parse("page.jpg")[0].markdown)
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
| | `version="v2"` | `version="v1.5"` |
|
|
81
|
+
|---|---|---|
|
|
82
|
+
| model used on the Typhoon API | `typhoon-ocr-v2` | `typhoon-ocr-v1.5` |
|
|
83
|
+
| `page.markdown` | yes | yes |
|
|
84
|
+
| `page.elements` (category, box, text) | yes | no (empty list) |
|
|
85
|
+
| `ask()` / `extract()` | yes | not tested |
|
|
86
|
+
|
|
87
|
+
**`version` or `model`?** `version` tells the package which prompt to send and how to read the answer. `model` is the model's name on the server. On the Typhoon API you only need `version`: the package picks the matching model for you. You need `model` when you run the model yourself (next section), because there the name depends on how you started the server.
|
|
88
|
+
|
|
89
|
+
## Run the model yourself
|
|
90
|
+
|
|
91
|
+
Start a server, then point `base_url` and `model` at it:
|
|
92
|
+
|
|
93
|
+
```bash
|
|
94
|
+
# vLLM 0.33.0 or newer (GPU)
|
|
95
|
+
vllm serve typhoon-ai/typhoon-ocr2-2b --max-model-len 40960 \
|
|
96
|
+
--limit-mm-per-prompt '{"image": 1}' \
|
|
97
|
+
--mm-processor-kwargs '{"min_pixels": 2048, "max_pixels": 16777216}'
|
|
98
|
+
|
|
99
|
+
# Ollama 0.40.15 or newer
|
|
100
|
+
ollama pull SuraponOCR/typhoon-ocr2-2b
|
|
101
|
+
|
|
102
|
+
# llama.cpp (GGUF)
|
|
103
|
+
llama-server -hf typhoon-ai/typhoon-ocr2-2b-GGUF:Q8_0 --jinja --reasoning off -c 40960 --image-max-tokens 16384
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
| Server | `base_url` | `model` |
|
|
107
|
+
|---|---|---|
|
|
108
|
+
| vLLM | `"http://localhost:8000/v1"` | `"typhoon-ai/typhoon-ocr2-2b"` |
|
|
109
|
+
| Ollama | `"http://localhost:11434"` | `"SuraponOCR/typhoon-ocr2-2b"` |
|
|
110
|
+
| llama.cpp | `"http://localhost:8080/v1"` | `"typhoon-ocr2"` (llama-server serves one model; any name works) |
|
|
111
|
+
|
|
112
|
+
```python
|
|
113
|
+
ocr = TyphoonOCR(
|
|
114
|
+
base_url="http://localhost:8000/v1",
|
|
115
|
+
model="typhoon-ai/typhoon-ocr2-2b",
|
|
116
|
+
version="v2",
|
|
117
|
+
upscale=True,
|
|
118
|
+
)
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
For the smaller page parser, use `typhoon-ai/typhoon-ocr2-0.8b` (Ollama: `SuraponOCR/typhoon-ocr2-0.8b`). On vLLM older than 0.33.0, add `--enforce-eager` to `vllm serve`: in the default compiled mode of vLLM 0.27.1, accuracy dropped by about 9 points on MDPBench. Other OpenAI-compatible servers work the same way.
|
|
122
|
+
|
|
123
|
+
## What you get back
|
|
124
|
+
|
|
125
|
+
`ocr.parse()` returns one `PageResult` per page:
|
|
126
|
+
|
|
127
|
+
| Field | Meaning |
|
|
128
|
+
|---|---|
|
|
129
|
+
| `page.page` | page number (1-based) |
|
|
130
|
+
| `page.markdown` | the page as Markdown; by default without headers, footers and page footnotes (see below) |
|
|
131
|
+
| `page.elements` | V2 only: **every** element the model returned, as `{"bbox": [x1, y1, x2, y2], "category": "...", "text": "..."}`, in reading order |
|
|
132
|
+
| `page.image_size` | `(width, height)` of the page image the boxes refer to |
|
|
133
|
+
| `page.truncated` | True if the output stopped at the token limit (usually a repetition loop); `elements` keeps the complete ones |
|
|
134
|
+
| `page.raw` | the model's raw output |
|
|
135
|
+
|
|
136
|
+
### Headers, footers and other categories
|
|
137
|
+
|
|
138
|
+
The model always returns header, footer and page_footnote elements, and they are always in `page.elements`. Only `page.markdown` leaves them out by default, because that is how the model was evaluated (and running page numbers and headers usually get in the way of reading). You choose what the Markdown keeps:
|
|
139
|
+
|
|
140
|
+
```python
|
|
141
|
+
pages = ocr.parse("report.pdf") # default: no header, footer, page_footnote
|
|
142
|
+
pages = ocr.parse("report.pdf", keep_header_footer=True) # keep every element
|
|
143
|
+
pages = ocr.parse("report.pdf", exclude=["footer"]) # keep headers, drop footers only
|
|
144
|
+
pages = ocr.parse("report.pdf", exclude=["header", "footer", "page_footnote", "figure_caption"]) # your own list
|
|
145
|
+
|
|
146
|
+
footers = [e["text"] for e in pages[0].elements if e["category"] == "footer"] # the elements themselves
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
On the command line: `--keep-header-footer`, or `--exclude footer` (several names allowed; `--exclude` with no names keeps everything).
|
|
150
|
+
|
|
151
|
+
The 13 categories are header, title, text, figure, table, formula, figure_caption, table_caption, formula_caption, figure_footnote, table_footnote, page_footnote and footer. Boxes use a 0–1000 grid relative to the page, so they do not depend on the image size:
|
|
152
|
+
|
|
153
|
+
```python
|
|
154
|
+
from typhoon_ocr2 import draw_layout, load_pages, to_pixels
|
|
155
|
+
|
|
156
|
+
image = load_pages("report.pdf", pages=[1])[0]
|
|
157
|
+
first = pages[0].elements[0]
|
|
158
|
+
print(first["category"], to_pixels(first["bbox"], *image.size)) # box in pixels
|
|
159
|
+
draw_layout(image, pages[0].elements).save("page1_layout.png") # boxes numbered in reading order
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
## Questions and key information (Typhoon OCR V2 2B)
|
|
163
|
+
|
|
164
|
+
```python
|
|
165
|
+
answer = ocr.ask("receipt.jpg", "What is the total amount?") # plain text
|
|
166
|
+
fields = ocr.extract("receipt.jpg", ["Date", "Total", "VAT 7%"]) # dict with these keys
|
|
167
|
+
everything = ocr.extract("receipt.jpg") # every field; the model picks the keys
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
The 0.8B model is a page parser only; it is much weaker at questions and extraction. Check extracted values before you use them: key-information extraction is the 2B model's weakest task.
|
|
171
|
+
|
|
172
|
+
## Command line
|
|
173
|
+
|
|
174
|
+
```bash
|
|
175
|
+
export TYPHOON_API_KEY=YOUR_KEY
|
|
176
|
+
API=https://api.opentyphoon.ai/v1
|
|
177
|
+
|
|
178
|
+
typhoon-ocr2 report.pdf --base-url $API # Markdown of every page (V2)
|
|
179
|
+
typhoon-ocr2 report.pdf --base-url $API --pages 2-4 --format json # layout elements
|
|
180
|
+
typhoon-ocr2 receipt.jpg --base-url $API --ask "What is the total amount?"
|
|
181
|
+
typhoon-ocr2 receipt.jpg --base-url $API --extract Date Total
|
|
182
|
+
typhoon-ocr2 page.jpg --base-url $API --version v1.5 # Typhoon OCR 1.5
|
|
183
|
+
typhoon-ocr2 page.jpg --base-url http://localhost:11434 --model SuraponOCR/typhoon-ocr2-2b # Ollama
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
To avoid repeating `--base-url`, set `TYPHOON_OCR_BASE_URL`. Add `--no-upscale` to turn upscaling off.
|
|
187
|
+
|
|
188
|
+
## Settings
|
|
189
|
+
|
|
190
|
+
All settings of `TyphoonOCR(...)`. The defaults are the settings the models were evaluated with.
|
|
191
|
+
|
|
192
|
+
| Setting | Default | What it does |
|
|
193
|
+
|---|---|---|
|
|
194
|
+
| `base_url` | `$TYPHOON_OCR_BASE_URL`, else `"http://localhost:8000/v1"` | server address |
|
|
195
|
+
| `model` | on the Typhoon API, chosen from `version`; on Ollama, `"SuraponOCR/typhoon-ocr2-2b"`; on other servers, the first model they serve | model name on the server; needed only for your own server |
|
|
196
|
+
| `api_key` | `$TYPHOON_API_KEY` | key for the Typhoon API |
|
|
197
|
+
| `version` | `"v2"` (or follows `model`, if you set one) | `"v2"` or `"v1.5"`: the prompt and output format |
|
|
198
|
+
| `upscale` | `True` | enlarge images whose long side is under 1,600 px. On ThaiOCRBench this raised Typhoon OCR V2 2B from 59.9 to 62.9 and 0.8B from 37.3 to 41.3; large pages are not changed. `False` turns it off; a number sets another size |
|
|
199
|
+
| `max_tokens` | `16384` | output limit per page |
|
|
200
|
+
| `pdf_long_side` | `2048` | PDF pages are rendered with this long side, in pixels |
|
|
201
|
+
| `max_workers` | `4` | PDF pages sent in parallel |
|
|
202
|
+
| `timeout` | `600` | seconds to wait for one page |
|
|
203
|
+
| `backend` | `"auto"` | `"openai"` or `"ollama"`; auto picks Ollama for `http://localhost:11434` |
|
|
204
|
+
| `figure_language` | `"Thai"` | v1.5 only: language of figure descriptions |
|
|
205
|
+
|
|
206
|
+
The prompts are the ones the models were trained with (`typhoon_ocr2.PARSE_PROMPT` for V2), and decoding is greedy with thinking turned off.
|
|
207
|
+
|
|
208
|
+
## Coming from `typhoon-ocr`
|
|
209
|
+
|
|
210
|
+
| `typhoon-ocr` | `typhoon-ocr2` |
|
|
211
|
+
|---|---|
|
|
212
|
+
| `from typhoon_ocr import ocr_document` | `from typhoon_ocr2 import ocr_document` (same idea), or `TyphoonOCR` for more |
|
|
213
|
+
| `ocr_document(path, page_num=1, base_url=..., model=...)` | `ocr_document(path, pages=1, base_url=..., model=...)` |
|
|
214
|
+
| returns a Markdown string | `TyphoonOCR.parse()` also returns layout elements with boxes |
|
|
215
|
+
| one page per call | `pages="1-3,5"` or all pages, sent in parallel |
|
|
216
|
+
| needs Poppler for PDFs | no system dependency |
|
|
217
|
+
|
|
218
|
+
## Development
|
|
219
|
+
|
|
220
|
+
```bash
|
|
221
|
+
pip install -e ".[dev]"
|
|
222
|
+
pytest # unit tests, no GPU needed
|
|
223
|
+
TYPHOON_OCR2_TEST_URL=http://localhost:8000/v1 pytest -m integration # against a running server
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
## Releasing
|
|
227
|
+
|
|
228
|
+
1. On pypi.org, add a Trusted Publisher for project `typhoon-ocr2`: this GitHub repository, workflow `publish.yml`, environment `pypi`.
|
|
229
|
+
2. Bump `__version__` in `src/typhoon_ocr2/__init__.py`, commit, then tag and push: `git tag v0.1.0 && git push origin v0.1.0`.
|
|
230
|
+
|
|
231
|
+
## License
|
|
232
|
+
|
|
233
|
+
Apache-2.0. See [LICENSE](LICENSE) and [NOTICE](NOTICE). Use of the Typhoon models is subject to the [OpenTyphoon Terms and Conditions](https://opentyphoon.ai/tac).
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
typhoon_ocr2/__init__.py,sha256=_0UZzmrH4nodFK-b8q2nHoARbbuqtkZwSZOmIk2fpYI,1037
|
|
2
|
+
typhoon_ocr2/cli.py,sha256=rOej-SYQpCfcbgkrMRKH0oNn6rdkC9rGy5p8XUK2rlM,4332
|
|
3
|
+
typhoon_ocr2/client.py,sha256=GX-2Sbb3hy1g8P6xv7ZeGF209XVqmbAC_rnkmx7RsI8,12736
|
|
4
|
+
typhoon_ocr2/images.py,sha256=A2v6xTE29MQXozJqFWK7QTaaE07SmvOKE6EhfatNKdo,4373
|
|
5
|
+
typhoon_ocr2/output.py,sha256=sCYks4G9Woikwx_RT8nqpAzaaKthIDYsONXTUur-1Hs,4246
|
|
6
|
+
typhoon_ocr2/prompts.py,sha256=tntbBDAIZeZPSMy2-rp0-J5rEdoanHV8XRof2PcAA0o,3127
|
|
7
|
+
typhoon_ocr2-0.1.0.dist-info/licenses/LICENSE,sha256=s6-69xOT4llrbefd0qWleUOZmo-BsT2Bs4yftYKO8qc,11347
|
|
8
|
+
typhoon_ocr2-0.1.0.dist-info/licenses/NOTICE,sha256=ql5f3B5JHgQ1mOQJ0rcIKsaEoVxhh1NfQ7rRCkjSPaY,391
|
|
9
|
+
typhoon_ocr2-0.1.0.dist-info/METADATA,sha256=FX0CzGo0mgmKDn0G6gdv1akG4no33Ogz7XZw-lNhDB0,11122
|
|
10
|
+
typhoon_ocr2-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
11
|
+
typhoon_ocr2-0.1.0.dist-info/entry_points.txt,sha256=mUPjOj78dgDUOxxOl70jOufEDeDc-C69Y2wvVM6Y3mo,55
|
|
12
|
+
typhoon_ocr2-0.1.0.dist-info/top_level.txt,sha256=lRFuCuVs22On4-cBppieIoMqUjcnwj94RAXNoaWJ_eo,13
|
|
13
|
+
typhoon_ocr2-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2025 SCB 10X Co., Ltd.
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
typhoon-ocr2
|
|
2
|
+
Copyright 2026 Surapon Nonesung
|
|
3
|
+
|
|
4
|
+
This project is derived from typhoon-ocr (https://github.com/scb-10x/typhoon-ocr),
|
|
5
|
+
Copyright the Typhoon OCR Contributors, SCB 10X, licensed under the Apache License 2.0.
|
|
6
|
+
It is maintained as a separate package with the Typhoon team's permission.
|
|
7
|
+
"Typhoon" is used to refer to the Typhoon models; this package is not an official SCB 10X product.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
typhoon_ocr2
|