enzohagz commited on
Commit
b3baef2
·
verified ·
1 Parent(s): 17e118b

Add inference code and usage instructions

Browse files
NOTICE CHANGED
@@ -9,5 +9,10 @@ revision 97c77dff50b2797bcc558fa2d909761dbc575c59), licensed under the Apache Li
9
  weights were fine-tuned with LoRA for Japanese page transcription and the adapter was merged into BF16 weights.
10
  The base model's publisher also publishes a usage policy, reproduced in notices/Muse-Glimmer-30B-USAGE_POLICY.md.
11
 
12
- The separately distributed document pipeline is released under the GNU Affero General Public License v3.0.
13
- It includes UVDoc code, MIT licensed, Copyright (c) 2023 Tanguy MAGNE.
 
 
 
 
 
 
9
  weights were fine-tuned with LoRA for Japanese page transcription and the adapter was merged into BF16 weights.
10
  The base model's publisher also publishes a usage policy, reproduced in notices/Muse-Glimmer-30B-USAGE_POLICY.md.
11
 
12
+ The page reader wasabi_read (orientation check, UVDoc flattening, whole-page read and per-page output) is released
13
+ under the GNU Affero General Public License v3.0.
14
+
15
+ UVDoc (https://github.com/tanguymagne/UVDoc), code at commit 4c9b82b537057aff2526e6dd118a847cdd072e82: MIT License,
16
+ Copyright (c) 2023 Tanguy MAGNE. wasabi_read downloads the UVDoc code and its pretrained weights
17
+ (model/best_model.pkl) from that commit at first use and does not redistribute them. The UVDoc repository carries
18
+ no weights-specific licence statement; the weights remain under their own terms.
README.md CHANGED
@@ -1,97 +1,169 @@
1
  ---
2
  license: agpl-3.0
3
  base_model: meta-models/Muse-Glimmer-30B
4
- base_model_relation: finetune
5
- library_name: transformers
6
  pipeline_tag: image-text-to-text
7
  language:
8
  - ja
 
9
  tags:
10
  - ocr
11
  - document-transcription
12
  - japanese
 
13
  ---
14
 
15
  # Wasabi-30B
16
 
17
- Wasabi-30B is Sionic AI's Japanese document fine-tune of [Muse Glimmer 30B](https://huggingface.co/meta-models/Muse-Glimmer-30B). It transcribes page images into Markdown, including headings, paragraphs, tables and mathematical notation.
18
 
19
- The checkpoint is provided as merged BF16 weights in two safetensors shards, approximately 60 GB in total. No separate adapter or base-model download is needed.
 
 
 
20
 
21
- ## Document processing
22
 
23
- Fine-tuning focuses on Japanese text structure, paragraph continuity and faithful transcription. The full document-processing pipeline also handles page orientation, complex layouts and small text annotations through preprocessing and output refinement.
 
 
 
24
 
25
- The complete pipeline is maintained in Sionic AI's private [Wasabi repository](https://github.com/sionic-ai/Wasabi-30B), accessible to authorized collaborators. The Docker package supplied for evaluation includes the full inference pipeline and its runtime assets.
26
 
27
- ## Quickstart
 
 
 
 
 
 
 
28
 
29
- This example transcribes one upright page image. Convert PDFs to page images first. Allow GPU memory for the weights, image processing and generated tokens; `device_map="auto"` distributes the model across available devices.
30
 
31
- Install PyTorch for your CUDA environment, then:
32
 
33
- ```bash
34
- pip install "transformers==5.15.0" accelerate pillow huggingface_hub
35
- ```
36
 
37
- Save the following as `transcribe.py` and run `python transcribe.py page.jpg > page.md`:
 
38
 
39
- ```python
40
- import argparse
41
- from pathlib import Path
42
 
43
- import torch
44
- from huggingface_hub import hf_hub_download
45
- from PIL import Image, ImageOps
46
- from transformers import AutoModelForImageTextToText, AutoProcessor
47
 
48
- parser = argparse.ArgumentParser()
49
- parser.add_argument("image")
50
- parser.add_argument("--rotate", type=int, choices=[0, 90, 180, 270], default=0,
51
- help="Additional clockwise rotation in degrees")
52
- args = parser.parse_args()
53
 
54
- model_id = "sionic-ai/Wasabi-30B"
55
- processor = AutoProcessor.from_pretrained(model_id)
56
- model = AutoModelForImageTextToText.from_pretrained(
57
- model_id, dtype=torch.bfloat16, device_map="auto"
58
- ).eval()
59
 
60
- prompt_path = hf_hub_download(model_id, "prompt.txt")
61
- prompt = Path(prompt_path).read_text(encoding="utf-8")
62
- with Image.open(args.image) as source:
63
- image = ImageOps.exif_transpose(source).convert("RGB")
64
- if args.rotate:
65
- image = image.rotate(-args.rotate, expand=True)
66
- messages = [{"role": "user", "content": [
67
- {"type": "image", "image": image},
68
- {"type": "text", "text": prompt},
69
- ]}]
70
- inputs = processor.apply_chat_template(
71
- messages, add_generation_prompt=True, tokenize=True,
72
- return_dict=True, return_tensors="pt", reasoning_strength="low",
73
- ).to(model.device)
74
 
75
- with torch.inference_mode():
76
- output = model.generate(**inputs, max_new_tokens=8192, do_sample=False)
77
- generated = output[0, inputs["input_ids"].shape[1]:]
78
- print(processor.decode(generated, skip_special_tokens=True))
79
- ```
80
 
81
- The example applies EXIF orientation metadata. For a page still turned sideways, use `python transcribe.py page.jpg --rotate 90 > page.md`. Automatic visual orientation correction is part of the private pipeline.
82
 
83
- Use the included [transcription prompt](prompt.txt) with the supplied chat template. The example covers direct model inference. For deployment support, contact [Sionic AI](https://sionic.ai).
 
84
 
85
- File checksums are provided in `SHA256SUMS`.
86
 
87
- ## Limitations
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
 
89
- - Dense or low-quality pages can lose text, table structure or reading order.
90
- - Use upright page images and check important details against the source.
91
- - Retrieval, question answering and general chat require separate evaluation.
92
 
93
- ## Licence and attribution
 
94
 
95
- Wasabi-30B is released under AGPL-3.0. See `LICENSE` and `NOTICE` for terms and attribution.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
 
97
- The base model is [Muse Glimmer 30B](https://huggingface.co/meta-models/Muse-Glimmer-30B), revision `97c77dff50b2797bcc558fa2d909761dbc575c59`. Its Apache-2.0 licence and publisher usage policy are included in `notices/`.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  license: agpl-3.0
3
  base_model: meta-models/Muse-Glimmer-30B
 
 
4
  pipeline_tag: image-text-to-text
5
  language:
6
  - ja
7
+ library_name: transformers
8
  tags:
9
  - ocr
10
  - document-transcription
11
  - japanese
12
+ - vllm
13
  ---
14
 
15
  # Wasabi-30B
16
 
17
+ Wasabi-30B reads a Japanese document page image and writes the page as Markdown:
18
 
19
+ - full text in reading order;
20
+ - tables as HTML `<table>`;
21
+ - math as LaTeX, `$...$` inline and `$$...$$` for display;
22
+ - ruby (furigana) kept inline as `<ruby>base<rt>reading</rt></ruby>`.
23
 
24
+ ## Model details
25
 
26
+ - Fine-tune of Muse-Glimmer-30B (https://huggingface.co/meta-models/Muse-Glimmer-30B, revision
27
+ `97c77dff50b2797bcc558fa2d909761dbc575c59`).
28
+ - A LoRA adapter trained for Japanese page transcription, merged into BF16 weights.
29
+ - Two safetensors shards.
30
 
31
+ ## Files in this repository
32
 
33
+ | path | what it is |
34
+ |---|---|
35
+ | `model-00001-of-00002.safetensors`, `model-00002-of-00002.safetensors`, `model.safetensors.index.json` | merged BF16 weights |
36
+ | `config.json`, `generation_config.json`, `processor_config.json` | model and processor configuration |
37
+ | `tokenizer.json`, `tokenizer_config.json`, `chat_template.jinja` | tokenizer and chat template |
38
+ | `inference/` | the page reader package (`wasabi_read`, AGPL-3.0) and its two prompts |
39
+ | `LICENSE`, `NOTICE`, `notices/` | licence texts: this model (AGPL-3.0), the base model (Apache-2.0) and its usage policy |
40
+ | `SHA256SUMS` | checksums of every file |
41
 
42
+ ## Inference
43
 
44
+ The package reads a folder of page images (`.jpg`, `.jpeg`, `.png`) and writes one `.md` file per page.
45
 
46
+ pip install -e "./inference[dewarp]"
 
 
47
 
48
+ Python 3.10+. The reader flattens every page locally with UVDoc on CPU, so torch and OpenCV are required in every
49
+ mode, including endpoint mode.
50
 
51
+ Local serving needs vLLM with muse_glimmer support, built from commit `6adad08767583f52eb4d2122111af0bf638ed5e6`
52
+ (version `0.26.1rc1.dev769`). Released vLLM 0.26.0 has no muse_glimmer model, so it cannot serve this model. A
53
+ source build needs a CUDA toolchain:
54
 
55
+ pip install "vllm @ git+https://github.com/vllm-project/vllm.git@6adad08767583f52eb4d2122111af0bf638ed5e6" "transformers==5.15.0"
 
 
 
56
 
57
+ Then, with the Python of that vLLM environment, apply the one-file processor fix. Without it, the muse_glimmer
58
+ processor of this vLLM commit rejects the `max_image_tokens` setting that every server below is started with, and the
59
+ server does not start. The script edits one file, checks its sha256 before and after, and can undo the edit
60
+ (`--check`, `--revert`). A server you start yourself (endpoint mode, direct model use) needs it too.
 
61
 
62
+ python inference/patch_vllm_max_image_tokens.py --apply
 
 
 
 
63
 
64
+ An endpoint run needs no local vLLM.
 
 
 
 
 
 
 
 
 
 
 
 
 
65
 
66
+ Tested with Python 3.12, vLLM `0.26.1rc1.dev769` (commit 6adad087), transformers 5.15.0, torch 2.13.0,
67
+ opencv-python-headless 5.0.0.93, numpy 2.3.5 and Pillow 13.0.0.
 
 
 
68
 
69
+ Wasabi-30B is the only checkpoint the reader needs: it checks the page orientation and reads the page.
70
 
71
+ Local vLLM (the package starts and stops the servers itself: first the orientation check, then the reader, both from
72
+ the same weights):
73
 
74
+ python inference/wasabi_read.py pages/ out/ --engine vllm --model-dir /models/Wasabi-30B --tensor-parallel-size 1 --whole-upscale-tokens 8192
75
 
76
+ Against OpenAI-compatible servers you already run, both serving Wasabi-30B: the reader started with
77
+ `--mm-processor-kwargs '{"max_image_tokens": 8192}'`, the orientation check with
78
+ `--mm-processor-kwargs '{"max_image_tokens": 4096}'`, and both with `--reasoning-parser muse_glimmer`. Name what each
79
+ server serves with `--endpoint-revision` and `--orient-endpoint-revision`; the addresses and revisions are part of the
80
+ output identity, so a rerun against another server is refused instead of mixed into the same output directory.
81
+
82
+ python inference/wasabi_read.py pages/ out/ --engine endpoint --endpoint-url http://gpu-host:8000 --endpoint-revision wasabi-30b-v1.0 --orient-endpoint-url http://gpu-host:8001 --orient-endpoint-revision wasabi-30b-v1.0
83
+
84
+ `--plan` prints the stages and exits without loading a model.
85
+
86
+ The API key, the UVDoc cache location and offline UVDoc use are described under
87
+ [Configuration](inference/README.md#configuration).
88
+
89
+ ### Direct model use
90
+
91
+ This sends the page image as it is: no orientation check, no flattening, no enlargement and no retries. It is a basic
92
+ transcription path, separate from the reader above. It uses the vLLM build and the processor fix from the Inference
93
+ section.
94
+
95
+ pip install openai
96
+ vllm serve /models/Wasabi-30B --served-model-name wasabi --max-model-len 36864 \
97
+ --mm-processor-kwargs '{"max_image_tokens": 8192}' --reasoning-parser muse_glimmer
98
 
99
+ Then send one page with the OpenAI-compatible API, using the recommended decoding (greedy, repetition penalty 1.10,
100
+ seed 42, up to 24,576 new tokens, low reasoning strength):
 
101
 
102
+ import base64
103
+ from openai import OpenAI
104
 
105
+ client = OpenAI(base_url="http://localhost:8000/v1", api_key="none")
106
+ png = base64.b64encode(open("page.png", "rb").read()).decode()
107
+ prompt = open("inference/wasabi_read/prompts/draft.txt", encoding="utf-8").read()
108
+ r = client.chat.completions.create(
109
+ model="wasabi",
110
+ messages=[{"role": "user", "content": [
111
+ {"type": "image_url", "image_url": {"url": "data:image/png;base64," + png}},
112
+ {"type": "text", "text": prompt}]}],
113
+ temperature=0.0,
114
+ seed=42,
115
+ max_tokens=24576,
116
+ extra_body={"repetition_penalty": 1.10,
117
+ "repetition_detection": {"max_pattern_size": 512, "min_pattern_size": 4, "min_count": 16},
118
+ "chat_template_kwargs": {"reasoning_strength": "low", "current_date": "2026-10-16"}},
119
+ )
120
+ print(r.choices[0].message.content)
121
+
122
+ The transcription prompt is the file `inference/wasabi_read/prompts/draft.txt`. The reader pins `current_date` so that the output does
123
+ not depend on the day you run it, and `repetition_detection` stops a looping answer early.
124
+
125
+ `generation_config.json` keeps the base model's sampling defaults; pass `temperature=0` (as above) for the
126
+ recommended greedy transcription.
127
+
128
+ ## What the reader does
129
+
130
+ Per page:
131
+
132
+ 1. Orientation check: Wasabi-30B answers a four-way upright probe at 4,096 image tokens; a turn is applied only when
133
+ the margin is at least 5.0.
134
+ 2. Flattening with UVDoc on CPU. The UVDoc code and weights are fetched at first use from a pinned commit and checked
135
+ by sha256 before loading.
136
+ 3. A whole-page read at 8,192 image tokens, greedy.
137
+ 4. If the answer is degenerate, a retry ladder at temperatures 0.1, 0.3, 0.5 and 0.8.
138
+ 5. Output is written per page as `<stem>.md`, atomically. Rerunning the same command resumes: finished pages are
139
+ skipped. Pages with no usable answer are listed in `out/.wasabi-read/run-report.json`.
140
+
141
+ ## Benchmark submission
142
+
143
+ The MDPBench submission includes additional inference components provided to the organizers. The complete inference
144
+ code is maintained in a [private repository](https://github.com/sionic-ai/Wasabi-30B).
145
+ The code included here runs independently of that repository.
146
+
147
+ ## Limitations
148
 
149
+ - Japanese-focused. Other languages are not a target.
150
+ - The `transformers` engine has not been measured and is not guaranteed to follow the vLLM path's image size and
151
+ decoding; use the vLLM or endpoint engine for the behaviour documented here.
152
+ - Each orientation decision comes from one greedy probe per rotation, so a different serving stack (attention backend,
153
+ CUDA build, batching) can change the turn on a few pages.
154
+ - Ruby appears only as the model writes it inline; there is no separate ruby pass.
155
+ - Photographed pages and very small print can be misread.
156
+ - The reader package runs on Linux and macOS only (it uses POSIX file locks). Its local vLLM engine starts the servers
157
+ with the FlashInfer vision-encoder attention backend; to use another backend, serve the model yourself and use
158
+ endpoint mode.
159
+
160
+ ## License
161
+
162
+ - This model and the reader package: GNU Affero General Public License v3.0 (`LICENSE`).
163
+ - Base model Muse-Glimmer-30B: Apache License 2.0 (`notices/Muse-Glimmer-30B-LICENSE.txt`), together with its
164
+ publisher's usage policy (`notices/Muse-Glimmer-30B-USAGE_POLICY.md`).
165
+ - UVDoc code (commit 4c9b82b5): MIT License, Copyright (c) 2023 Tanguy MAGNE. The reader downloads the UVDoc code
166
+ and its pretrained weights at first use and does not redistribute them. The weights carry no separate licence
167
+ statement and remain under their upstream terms.
168
+
169
+ Copyright 2026 Sionic AI Inc.
SHA256SUMS CHANGED
@@ -1,11 +1,27 @@
1
- a0e948ca693c63e0b5139f66bd709003cbcf8bc764acb1ee687a552885c8fe2c .gitattributes
2
- d358c3e18ad2722f9784f5f5350181005b5d5779d54abf35ba6b87c4743fc7ab .gitignore
3
  0d96a4ff68ad6d4b6f1f30f713b18d5184912ba8dd389f86aa7710db079abcb0 LICENSE
4
- e4e2e4db780cbe91dc4e739e614a9d8c03953c39b5e4ef324a84393d0a5ade95 NOTICE
5
- 4c413ad09db035795702d4a57e559971d89181a165b8b6232361f9ea8dda5b6e README.md
6
  114f55ebdc1804c1af371197b9fdf2d6bb925966c9dfe46b73782a71bc07965e chat_template.jinja
7
  1c235df3179388bb56e522a25543d1f9e417a25e71b162887378a4362c5e4dbc config.json
8
  519ca0cad3bf6cb10c4f74dfb64786f651533bae2f316c609d66e0bcf5adfde6 generation_config.json
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  0a5fdba915e499084969163518830e320040b0f2e03eb43843bbb71be450c5a7 model-00001-of-00002.safetensors
10
  20dfe7774a3ba1194b853e54fac1fb589bdc28872198b6e80c6c37ea32ef21b4 model-00002-of-00002.safetensors
11
  79f6028c3b5544f6be46607b8580d7376bf68bdc66647480fd3bfa520ad9efa3 model.safetensors.index.json
 
 
 
1
  0d96a4ff68ad6d4b6f1f30f713b18d5184912ba8dd389f86aa7710db079abcb0 LICENSE
2
+ 9a696bb21eb15253ed57505ef28b1cf24b21232808ee13336ed7244a6a5ea9b9 NOTICE
3
+ b374b8bfb0cb6eecf7f2a1d9decad8f87bc27c332c4094579c2c34196ef53d26 README.md
4
  114f55ebdc1804c1af371197b9fdf2d6bb925966c9dfe46b73782a71bc07965e chat_template.jinja
5
  1c235df3179388bb56e522a25543d1f9e417a25e71b162887378a4362c5e4dbc config.json
6
  519ca0cad3bf6cb10c4f74dfb64786f651533bae2f316c609d66e0bcf5adfde6 generation_config.json
7
+ 0d96a4ff68ad6d4b6f1f30f713b18d5184912ba8dd389f86aa7710db079abcb0 inference/LICENSE
8
+ 9a696bb21eb15253ed57505ef28b1cf24b21232808ee13336ed7244a6a5ea9b9 inference/NOTICE
9
+ 70d546c82d5c2cf88a3dc5f5c4a1772c5c49ededff0ddf2cb92f3cd88cc32c51 inference/README.md
10
+ b47659c857a9df27fcac4eaeade20ec382f733e176350bc8ff38a2d1ea0fc6ac inference/patch_vllm_max_image_tokens.py
11
+ 22c09a27433e96357534f2b8795ecc21a749e534fee895b9d5967f17109ae26c inference/pyproject.toml
12
+ 835cef3a918b418b121c014acc350d08f58410c8692d45545e21bef603d81b46 inference/wasabi_read.py
13
+ 7f94773ff631125c1bea6cdaa5a2214d4032a79163ecbdafb331451f52ec60e4 inference/wasabi_read/__init__.py
14
+ 377ad9282dcd4e44df878094cf3b1606238059c346cf79ca620567bde2ce7a5e inference/wasabi_read/cli.py
15
+ ba4a7fb751896db1d9acf402a2c32412ba7c64f0a481028d8fb9251dd5877d02 inference/wasabi_read/dewarp.py
16
+ 53d23fe1224e771390ed9f453dc2304263eb93aa487ccfd1cd22cd20860d21b7 inference/wasabi_read/engine.py
17
+ ee8210b9034290c139f1ee99ae1f31fb43960369111315c01984e9d77a4132cb inference/wasabi_read/identity.py
18
+ c4e1ee6fc0e09276d6ec75d9b6832c7541359a5714871be38d7db5b4bc7b924b inference/wasabi_read/inputs.py
19
+ 930700f660bef1973d05459f34854df6055c14b98e4ba01f211d00d49d2ea607 inference/wasabi_read/orient.py
20
+ 647386ef8705c3841606ceb0b5411b6347f06b9fa67d92646226bc942b8d347f inference/wasabi_read/output.py
21
+ 1f80d2ca0bcb5c815ab15f1fe8d6a7fc16d2c2c305ffeabcec90eca4292d97f8 inference/wasabi_read/prompts/draft.txt
22
+ ad089da4c37eb9a25a5bf56dd4124497d2258c282ae0b593112984e10cd7d159 inference/wasabi_read/prompts/orient-upright.txt
23
+ 7839b0fc9685bb3a727fe1c0b1122c66ca80893067bcb17e5aa54e8998efcc67 inference/wasabi_read/reliability.py
24
+ aa27844934edb224e0ebee66c8baf1f37c07229d58a94f2fe1cf8152a148b4b7 inference/wasabi_read/views.py
25
  0a5fdba915e499084969163518830e320040b0f2e03eb43843bbb71be450c5a7 model-00001-of-00002.safetensors
26
  20dfe7774a3ba1194b853e54fac1fb589bdc28872198b6e80c6c37ea32ef21b4 model-00002-of-00002.safetensors
27
  79f6028c3b5544f6be46607b8580d7376bf68bdc66647480fd3bfa520ad9efa3 model.safetensors.index.json
inference/LICENSE ADDED
@@ -0,0 +1,661 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU AFFERO GENERAL PUBLIC LICENSE
2
+ Version 3, 19 November 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU Affero General Public License is a free, copyleft license for
11
+ software and other kinds of works, specifically designed to ensure
12
+ cooperation with the community in the case of network server software.
13
+
14
+ The licenses for most software and other practical works are designed
15
+ to take away your freedom to share and change the works. By contrast,
16
+ our General Public Licenses are intended to guarantee your freedom to
17
+ share and change all versions of a program--to make sure it remains free
18
+ software for all its users.
19
+
20
+ When we speak of free software, we are referring to freedom, not
21
+ price. Our General Public Licenses are designed to make sure that you
22
+ have the freedom to distribute copies of free software (and charge for
23
+ them if you wish), that you receive source code or can get it if you
24
+ want it, that you can change the software or use pieces of it in new
25
+ free programs, and that you know you can do these things.
26
+
27
+ Developers that use our General Public Licenses protect your rights
28
+ with two steps: (1) assert copyright on the software, and (2) offer
29
+ you this License which gives you legal permission to copy, distribute
30
+ and/or modify the software.
31
+
32
+ A secondary benefit of defending all users' freedom is that
33
+ improvements made in alternate versions of the program, if they
34
+ receive widespread use, become available for other developers to
35
+ incorporate. Many developers of free software are heartened and
36
+ encouraged by the resulting cooperation. However, in the case of
37
+ software used on network servers, this result may fail to come about.
38
+ The GNU General Public License permits making a modified version and
39
+ letting the public access it on a server without ever releasing its
40
+ source code to the public.
41
+
42
+ The GNU Affero General Public License is designed specifically to
43
+ ensure that, in such cases, the modified source code becomes available
44
+ to the community. It requires the operator of a network server to
45
+ provide the source code of the modified version running there to the
46
+ users of that server. Therefore, public use of a modified version, on
47
+ a publicly accessible server, gives the public access to the source
48
+ code of the modified version.
49
+
50
+ An older license, called the Affero General Public License and
51
+ published by Affero, was designed to accomplish similar goals. This is
52
+ a different license, not a version of the Affero GPL, but Affero has
53
+ released a new version of the Affero GPL which permits relicensing under
54
+ this license.
55
+
56
+ The precise terms and conditions for copying, distribution and
57
+ modification follow.
58
+
59
+ TERMS AND CONDITIONS
60
+
61
+ 0. Definitions.
62
+
63
+ "This License" refers to version 3 of the GNU Affero General Public License.
64
+
65
+ "Copyright" also means copyright-like laws that apply to other kinds of
66
+ works, such as semiconductor masks.
67
+
68
+ "The Program" refers to any copyrightable work licensed under this
69
+ License. Each licensee is addressed as "you". "Licensees" and
70
+ "recipients" may be individuals or organizations.
71
+
72
+ To "modify" a work means to copy from or adapt all or part of the work
73
+ in a fashion requiring copyright permission, other than the making of an
74
+ exact copy. The resulting work is called a "modified version" of the
75
+ earlier work or a work "based on" the earlier work.
76
+
77
+ A "covered work" means either the unmodified Program or a work based
78
+ on the Program.
79
+
80
+ To "propagate" a work means to do anything with it that, without
81
+ permission, would make you directly or secondarily liable for
82
+ infringement under applicable copyright law, except executing it on a
83
+ computer or modifying a private copy. Propagation includes copying,
84
+ distribution (with or without modification), making available to the
85
+ public, and in some countries other activities as well.
86
+
87
+ To "convey" a work means any kind of propagation that enables other
88
+ parties to make or receive copies. Mere interaction with a user through
89
+ a computer network, with no transfer of a copy, is not conveying.
90
+
91
+ An interactive user interface displays "Appropriate Legal Notices"
92
+ to the extent that it includes a convenient and prominently visible
93
+ feature that (1) displays an appropriate copyright notice, and (2)
94
+ tells the user that there is no warranty for the work (except to the
95
+ extent that warranties are provided), that licensees may convey the
96
+ work under this License, and how to view a copy of this License. If
97
+ the interface presents a list of user commands or options, such as a
98
+ menu, a prominent item in the list meets this criterion.
99
+
100
+ 1. Source Code.
101
+
102
+ The "source code" for a work means the preferred form of the work
103
+ for making modifications to it. "Object code" means any non-source
104
+ form of a work.
105
+
106
+ A "Standard Interface" means an interface that either is an official
107
+ standard defined by a recognized standards body, or, in the case of
108
+ interfaces specified for a particular programming language, one that
109
+ is widely used among developers working in that language.
110
+
111
+ The "System Libraries" of an executable work include anything, other
112
+ than the work as a whole, that (a) is included in the normal form of
113
+ packaging a Major Component, but which is not part of that Major
114
+ Component, and (b) serves only to enable use of the work with that
115
+ Major Component, or to implement a Standard Interface for which an
116
+ implementation is available to the public in source code form. A
117
+ "Major Component", in this context, means a major essential component
118
+ (kernel, window system, and so on) of the specific operating system
119
+ (if any) on which the executable work runs, or a compiler used to
120
+ produce the work, or an object code interpreter used to run it.
121
+
122
+ The "Corresponding Source" for a work in object code form means all
123
+ the source code needed to generate, install, and (for an executable
124
+ work) run the object code and to modify the work, including scripts to
125
+ control those activities. However, it does not include the work's
126
+ System Libraries, or general-purpose tools or generally available free
127
+ programs which are used unmodified in performing those activities but
128
+ which are not part of the work. For example, Corresponding Source
129
+ includes interface definition files associated with source files for
130
+ the work, and the source code for shared libraries and dynamically
131
+ linked subprograms that the work is specifically designed to require,
132
+ such as by intimate data communication or control flow between those
133
+ subprograms and other parts of the work.
134
+
135
+ The Corresponding Source need not include anything that users
136
+ can regenerate automatically from other parts of the Corresponding
137
+ Source.
138
+
139
+ The Corresponding Source for a work in source code form is that
140
+ same work.
141
+
142
+ 2. Basic Permissions.
143
+
144
+ All rights granted under this License are granted for the term of
145
+ copyright on the Program, and are irrevocable provided the stated
146
+ conditions are met. This License explicitly affirms your unlimited
147
+ permission to run the unmodified Program. The output from running a
148
+ covered work is covered by this License only if the output, given its
149
+ content, constitutes a covered work. This License acknowledges your
150
+ rights of fair use or other equivalent, as provided by copyright law.
151
+
152
+ You may make, run and propagate covered works that you do not
153
+ convey, without conditions so long as your license otherwise remains
154
+ in force. You may convey covered works to others for the sole purpose
155
+ of having them make modifications exclusively for you, or provide you
156
+ with facilities for running those works, provided that you comply with
157
+ the terms of this License in conveying all material for which you do
158
+ not control copyright. Those thus making or running the covered works
159
+ for you must do so exclusively on your behalf, under your direction
160
+ and control, on terms that prohibit them from making any copies of
161
+ your copyrighted material outside their relationship with you.
162
+
163
+ Conveying under any other circumstances is permitted solely under
164
+ the conditions stated below. Sublicensing is not allowed; section 10
165
+ makes it unnecessary.
166
+
167
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168
+
169
+ No covered work shall be deemed part of an effective technological
170
+ measure under any applicable law fulfilling obligations under article
171
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172
+ similar laws prohibiting or restricting circumvention of such
173
+ measures.
174
+
175
+ When you convey a covered work, you waive any legal power to forbid
176
+ circumvention of technological measures to the extent such circumvention
177
+ is effected by exercising rights under this License with respect to
178
+ the covered work, and you disclaim any intention to limit operation or
179
+ modification of the work as a means of enforcing, against the work's
180
+ users, your or third parties' legal rights to forbid circumvention of
181
+ technological measures.
182
+
183
+ 4. Conveying Verbatim Copies.
184
+
185
+ You may convey verbatim copies of the Program's source code as you
186
+ receive it, in any medium, provided that you conspicuously and
187
+ appropriately publish on each copy an appropriate copyright notice;
188
+ keep intact all notices stating that this License and any
189
+ non-permissive terms added in accord with section 7 apply to the code;
190
+ keep intact all notices of the absence of any warranty; and give all
191
+ recipients a copy of this License along with the Program.
192
+
193
+ You may charge any price or no price for each copy that you convey,
194
+ and you may offer support or warranty protection for a fee.
195
+
196
+ 5. Conveying Modified Source Versions.
197
+
198
+ You may convey a work based on the Program, or the modifications to
199
+ produce it from the Program, in the form of source code under the
200
+ terms of section 4, provided that you also meet all of these conditions:
201
+
202
+ a) The work must carry prominent notices stating that you modified
203
+ it, and giving a relevant date.
204
+
205
+ b) The work must carry prominent notices stating that it is
206
+ released under this License and any conditions added under section
207
+ 7. This requirement modifies the requirement in section 4 to
208
+ "keep intact all notices".
209
+
210
+ c) You must license the entire work, as a whole, under this
211
+ License to anyone who comes into possession of a copy. This
212
+ License will therefore apply, along with any applicable section 7
213
+ additional terms, to the whole of the work, and all its parts,
214
+ regardless of how they are packaged. This License gives no
215
+ permission to license the work in any other way, but it does not
216
+ invalidate such permission if you have separately received it.
217
+
218
+ d) If the work has interactive user interfaces, each must display
219
+ Appropriate Legal Notices; however, if the Program has interactive
220
+ interfaces that do not display Appropriate Legal Notices, your
221
+ work need not make them do so.
222
+
223
+ A compilation of a covered work with other separate and independent
224
+ works, which are not by their nature extensions of the covered work,
225
+ and which are not combined with it such as to form a larger program,
226
+ in or on a volume of a storage or distribution medium, is called an
227
+ "aggregate" if the compilation and its resulting copyright are not
228
+ used to limit the access or legal rights of the compilation's users
229
+ beyond what the individual works permit. Inclusion of a covered work
230
+ in an aggregate does not cause this License to apply to the other
231
+ parts of the aggregate.
232
+
233
+ 6. Conveying Non-Source Forms.
234
+
235
+ You may convey a covered work in object code form under the terms
236
+ of sections 4 and 5, provided that you also convey the
237
+ machine-readable Corresponding Source under the terms of this License,
238
+ in one of these ways:
239
+
240
+ a) Convey the object code in, or embodied in, a physical product
241
+ (including a physical distribution medium), accompanied by the
242
+ Corresponding Source fixed on a durable physical medium
243
+ customarily used for software interchange.
244
+
245
+ b) Convey the object code in, or embodied in, a physical product
246
+ (including a physical distribution medium), accompanied by a
247
+ written offer, valid for at least three years and valid for as
248
+ long as you offer spare parts or customer support for that product
249
+ model, to give anyone who possesses the object code either (1) a
250
+ copy of the Corresponding Source for all the software in the
251
+ product that is covered by this License, on a durable physical
252
+ medium customarily used for software interchange, for a price no
253
+ more than your reasonable cost of physically performing this
254
+ conveying of source, or (2) access to copy the
255
+ Corresponding Source from a network server at no charge.
256
+
257
+ c) Convey individual copies of the object code with a copy of the
258
+ written offer to provide the Corresponding Source. This
259
+ alternative is allowed only occasionally and noncommercially, and
260
+ only if you received the object code with such an offer, in accord
261
+ with subsection 6b.
262
+
263
+ d) Convey the object code by offering access from a designated
264
+ place (gratis or for a charge), and offer equivalent access to the
265
+ Corresponding Source in the same way through the same place at no
266
+ further charge. You need not require recipients to copy the
267
+ Corresponding Source along with the object code. If the place to
268
+ copy the object code is a network server, the Corresponding Source
269
+ may be on a different server (operated by you or a third party)
270
+ that supports equivalent copying facilities, provided you maintain
271
+ clear directions next to the object code saying where to find the
272
+ Corresponding Source. Regardless of what server hosts the
273
+ Corresponding Source, you remain obligated to ensure that it is
274
+ available for as long as needed to satisfy these requirements.
275
+
276
+ e) Convey the object code using peer-to-peer transmission, provided
277
+ you inform other peers where the object code and Corresponding
278
+ Source of the work are being offered to the general public at no
279
+ charge under subsection 6d.
280
+
281
+ A separable portion of the object code, whose source code is excluded
282
+ from the Corresponding Source as a System Library, need not be
283
+ included in conveying the object code work.
284
+
285
+ A "User Product" is either (1) a "consumer product", which means any
286
+ tangible personal property which is normally used for personal, family,
287
+ or household purposes, or (2) anything designed or sold for incorporation
288
+ into a dwelling. In determining whether a product is a consumer product,
289
+ doubtful cases shall be resolved in favor of coverage. For a particular
290
+ product received by a particular user, "normally used" refers to a
291
+ typical or common use of that class of product, regardless of the status
292
+ of the particular user or of the way in which the particular user
293
+ actually uses, or expects or is expected to use, the product. A product
294
+ is a consumer product regardless of whether the product has substantial
295
+ commercial, industrial or non-consumer uses, unless such uses represent
296
+ the only significant mode of use of the product.
297
+
298
+ "Installation Information" for a User Product means any methods,
299
+ procedures, authorization keys, or other information required to install
300
+ and execute modified versions of a covered work in that User Product from
301
+ a modified version of its Corresponding Source. The information must
302
+ suffice to ensure that the continued functioning of the modified object
303
+ code is in no case prevented or interfered with solely because
304
+ modification has been made.
305
+
306
+ If you convey an object code work under this section in, or with, or
307
+ specifically for use in, a User Product, and the conveying occurs as
308
+ part of a transaction in which the right of possession and use of the
309
+ User Product is transferred to the recipient in perpetuity or for a
310
+ fixed term (regardless of how the transaction is characterized), the
311
+ Corresponding Source conveyed under this section must be accompanied
312
+ by the Installation Information. But this requirement does not apply
313
+ if neither you nor any third party retains the ability to install
314
+ modified object code on the User Product (for example, the work has
315
+ been installed in ROM).
316
+
317
+ The requirement to provide Installation Information does not include a
318
+ requirement to continue to provide support service, warranty, or updates
319
+ for a work that has been modified or installed by the recipient, or for
320
+ the User Product in which it has been modified or installed. Access to a
321
+ network may be denied when the modification itself materially and
322
+ adversely affects the operation of the network or violates the rules and
323
+ protocols for communication across the network.
324
+
325
+ Corresponding Source conveyed, and Installation Information provided,
326
+ in accord with this section must be in a format that is publicly
327
+ documented (and with an implementation available to the public in
328
+ source code form), and must require no special password or key for
329
+ unpacking, reading or copying.
330
+
331
+ 7. Additional Terms.
332
+
333
+ "Additional permissions" are terms that supplement the terms of this
334
+ License by making exceptions from one or more of its conditions.
335
+ Additional permissions that are applicable to the entire Program shall
336
+ be treated as though they were included in this License, to the extent
337
+ that they are valid under applicable law. If additional permissions
338
+ apply only to part of the Program, that part may be used separately
339
+ under those permissions, but the entire Program remains governed by
340
+ this License without regard to the additional permissions.
341
+
342
+ When you convey a copy of a covered work, you may at your option
343
+ remove any additional permissions from that copy, or from any part of
344
+ it. (Additional permissions may be written to require their own
345
+ removal in certain cases when you modify the work.) You may place
346
+ additional permissions on material, added by you to a covered work,
347
+ for which you have or can give appropriate copyright permission.
348
+
349
+ Notwithstanding any other provision of this License, for material you
350
+ add to a covered work, you may (if authorized by the copyright holders of
351
+ that material) supplement the terms of this License with terms:
352
+
353
+ a) Disclaiming warranty or limiting liability differently from the
354
+ terms of sections 15 and 16 of this License; or
355
+
356
+ b) Requiring preservation of specified reasonable legal notices or
357
+ author attributions in that material or in the Appropriate Legal
358
+ Notices displayed by works containing it; or
359
+
360
+ c) Prohibiting misrepresentation of the origin of that material, or
361
+ requiring that modified versions of such material be marked in
362
+ reasonable ways as different from the original version; or
363
+
364
+ d) Limiting the use for publicity purposes of names of licensors or
365
+ authors of the material; or
366
+
367
+ e) Declining to grant rights under trademark law for use of some
368
+ trade names, trademarks, or service marks; or
369
+
370
+ f) Requiring indemnification of licensors and authors of that
371
+ material by anyone who conveys the material (or modified versions of
372
+ it) with contractual assumptions of liability to the recipient, for
373
+ any liability that these contractual assumptions directly impose on
374
+ those licensors and authors.
375
+
376
+ All other non-permissive additional terms are considered "further
377
+ restrictions" within the meaning of section 10. If the Program as you
378
+ received it, or any part of it, contains a notice stating that it is
379
+ governed by this License along with a term that is a further
380
+ restriction, you may remove that term. If a license document contains
381
+ a further restriction but permits relicensing or conveying under this
382
+ License, you may add to a covered work material governed by the terms
383
+ of that license document, provided that the further restriction does
384
+ not survive such relicensing or conveying.
385
+
386
+ If you add terms to a covered work in accord with this section, you
387
+ must place, in the relevant source files, a statement of the
388
+ additional terms that apply to those files, or a notice indicating
389
+ where to find the applicable terms.
390
+
391
+ Additional terms, permissive or non-permissive, may be stated in the
392
+ form of a separately written license, or stated as exceptions;
393
+ the above requirements apply either way.
394
+
395
+ 8. Termination.
396
+
397
+ You may not propagate or modify a covered work except as expressly
398
+ provided under this License. Any attempt otherwise to propagate or
399
+ modify it is void, and will automatically terminate your rights under
400
+ this License (including any patent licenses granted under the third
401
+ paragraph of section 11).
402
+
403
+ However, if you cease all violation of this License, then your
404
+ license from a particular copyright holder is reinstated (a)
405
+ provisionally, unless and until the copyright holder explicitly and
406
+ finally terminates your license, and (b) permanently, if the copyright
407
+ holder fails to notify you of the violation by some reasonable means
408
+ prior to 60 days after the cessation.
409
+
410
+ Moreover, your license from a particular copyright holder is
411
+ reinstated permanently if the copyright holder notifies you of the
412
+ violation by some reasonable means, this is the first time you have
413
+ received notice of violation of this License (for any work) from that
414
+ copyright holder, and you cure the violation prior to 30 days after
415
+ your receipt of the notice.
416
+
417
+ Termination of your rights under this section does not terminate the
418
+ licenses of parties who have received copies or rights from you under
419
+ this License. If your rights have been terminated and not permanently
420
+ reinstated, you do not qualify to receive new licenses for the same
421
+ material under section 10.
422
+
423
+ 9. Acceptance Not Required for Having Copies.
424
+
425
+ You are not required to accept this License in order to receive or
426
+ run a copy of the Program. Ancillary propagation of a covered work
427
+ occurring solely as a consequence of using peer-to-peer transmission
428
+ to receive a copy likewise does not require acceptance. However,
429
+ nothing other than this License grants you permission to propagate or
430
+ modify any covered work. These actions infringe copyright if you do
431
+ not accept this License. Therefore, by modifying or propagating a
432
+ covered work, you indicate your acceptance of this License to do so.
433
+
434
+ 10. Automatic Licensing of Downstream Recipients.
435
+
436
+ Each time you convey a covered work, the recipient automatically
437
+ receives a license from the original licensors, to run, modify and
438
+ propagate that work, subject to this License. You are not responsible
439
+ for enforcing compliance by third parties with this License.
440
+
441
+ An "entity transaction" is a transaction transferring control of an
442
+ organization, or substantially all assets of one, or subdividing an
443
+ organization, or merging organizations. If propagation of a covered
444
+ work results from an entity transaction, each party to that
445
+ transaction who receives a copy of the work also receives whatever
446
+ licenses to the work the party's predecessor in interest had or could
447
+ give under the previous paragraph, plus a right to possession of the
448
+ Corresponding Source of the work from the predecessor in interest, if
449
+ the predecessor has it or can get it with reasonable efforts.
450
+
451
+ You may not impose any further restrictions on the exercise of the
452
+ rights granted or affirmed under this License. For example, you may
453
+ not impose a license fee, royalty, or other charge for exercise of
454
+ rights granted under this License, and you may not initiate litigation
455
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
456
+ any patent claim is infringed by making, using, selling, offering for
457
+ sale, or importing the Program or any portion of it.
458
+
459
+ 11. Patents.
460
+
461
+ A "contributor" is a copyright holder who authorizes use under this
462
+ License of the Program or a work on which the Program is based. The
463
+ work thus licensed is called the contributor's "contributor version".
464
+
465
+ A contributor's "essential patent claims" are all patent claims
466
+ owned or controlled by the contributor, whether already acquired or
467
+ hereafter acquired, that would be infringed by some manner, permitted
468
+ by this License, of making, using, or selling its contributor version,
469
+ but do not include claims that would be infringed only as a
470
+ consequence of further modification of the contributor version. For
471
+ purposes of this definition, "control" includes the right to grant
472
+ patent sublicenses in a manner consistent with the requirements of
473
+ this License.
474
+
475
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
476
+ patent license under the contributor's essential patent claims, to
477
+ make, use, sell, offer for sale, import and otherwise run, modify and
478
+ propagate the contents of its contributor version.
479
+
480
+ In the following three paragraphs, a "patent license" is any express
481
+ agreement or commitment, however denominated, not to enforce a patent
482
+ (such as an express permission to practice a patent or covenant not to
483
+ sue for patent infringement). To "grant" such a patent license to a
484
+ party means to make such an agreement or commitment not to enforce a
485
+ patent against the party.
486
+
487
+ If you convey a covered work, knowingly relying on a patent license,
488
+ and the Corresponding Source of the work is not available for anyone
489
+ to copy, free of charge and under the terms of this License, through a
490
+ publicly available network server or other readily accessible means,
491
+ then you must either (1) cause the Corresponding Source to be so
492
+ available, or (2) arrange to deprive yourself of the benefit of the
493
+ patent license for this particular work, or (3) arrange, in a manner
494
+ consistent with the requirements of this License, to extend the patent
495
+ license to downstream recipients. "Knowingly relying" means you have
496
+ actual knowledge that, but for the patent license, your conveying the
497
+ covered work in a country, or your recipient's use of the covered work
498
+ in a country, would infringe one or more identifiable patents in that
499
+ country that you have reason to believe are valid.
500
+
501
+ If, pursuant to or in connection with a single transaction or
502
+ arrangement, you convey, or propagate by procuring conveyance of, a
503
+ covered work, and grant a patent license to some of the parties
504
+ receiving the covered work authorizing them to use, propagate, modify
505
+ or convey a specific copy of the covered work, then the patent license
506
+ you grant is automatically extended to all recipients of the covered
507
+ work and works based on it.
508
+
509
+ A patent license is "discriminatory" if it does not include within
510
+ the scope of its coverage, prohibits the exercise of, or is
511
+ conditioned on the non-exercise of one or more of the rights that are
512
+ specifically granted under this License. You may not convey a covered
513
+ work if you are a party to an arrangement with a third party that is
514
+ in the business of distributing software, under which you make payment
515
+ to the third party based on the extent of your activity of conveying
516
+ the work, and under which the third party grants, to any of the
517
+ parties who would receive the covered work from you, a discriminatory
518
+ patent license (a) in connection with copies of the covered work
519
+ conveyed by you (or copies made from those copies), or (b) primarily
520
+ for and in connection with specific products or compilations that
521
+ contain the covered work, unless you entered into that arrangement,
522
+ or that patent license was granted, prior to 28 March 2007.
523
+
524
+ Nothing in this License shall be construed as excluding or limiting
525
+ any implied license or other defenses to infringement that may
526
+ otherwise be available to you under applicable patent law.
527
+
528
+ 12. No Surrender of Others' Freedom.
529
+
530
+ If conditions are imposed on you (whether by court order, agreement or
531
+ otherwise) that contradict the conditions of this License, they do not
532
+ excuse you from the conditions of this License. If you cannot convey a
533
+ covered work so as to satisfy simultaneously your obligations under this
534
+ License and any other pertinent obligations, then as a consequence you may
535
+ not convey it at all. For example, if you agree to terms that obligate you
536
+ to collect a royalty for further conveying from those to whom you convey
537
+ the Program, the only way you could satisfy both those terms and this
538
+ License would be to refrain entirely from conveying the Program.
539
+
540
+ 13. Remote Network Interaction; Use with the GNU General Public License.
541
+
542
+ Notwithstanding any other provision of this License, if you modify the
543
+ Program, your modified version must prominently offer all users
544
+ interacting with it remotely through a computer network (if your version
545
+ supports such interaction) an opportunity to receive the Corresponding
546
+ Source of your version by providing access to the Corresponding Source
547
+ from a network server at no charge, through some standard or customary
548
+ means of facilitating copying of software. This Corresponding Source
549
+ shall include the Corresponding Source for any work covered by version 3
550
+ of the GNU General Public License that is incorporated pursuant to the
551
+ following paragraph.
552
+
553
+ Notwithstanding any other provision of this License, you have
554
+ permission to link or combine any covered work with a work licensed
555
+ under version 3 of the GNU General Public License into a single
556
+ combined work, and to convey the resulting work. The terms of this
557
+ License will continue to apply to the part which is the covered work,
558
+ but the work with which it is combined will remain governed by version
559
+ 3 of the GNU General Public License.
560
+
561
+ 14. Revised Versions of this License.
562
+
563
+ The Free Software Foundation may publish revised and/or new versions of
564
+ the GNU Affero General Public License from time to time. Such new versions
565
+ will be similar in spirit to the present version, but may differ in detail to
566
+ address new problems or concerns.
567
+
568
+ Each version is given a distinguishing version number. If the
569
+ Program specifies that a certain numbered version of the GNU Affero General
570
+ Public License "or any later version" applies to it, you have the
571
+ option of following the terms and conditions either of that numbered
572
+ version or of any later version published by the Free Software
573
+ Foundation. If the Program does not specify a version number of the
574
+ GNU Affero General Public License, you may choose any version ever published
575
+ by the Free Software Foundation.
576
+
577
+ If the Program specifies that a proxy can decide which future
578
+ versions of the GNU Affero General Public License can be used, that proxy's
579
+ public statement of acceptance of a version permanently authorizes you
580
+ to choose that version for the Program.
581
+
582
+ Later license versions may give you additional or different
583
+ permissions. However, no additional obligations are imposed on any
584
+ author or copyright holder as a result of your choosing to follow a
585
+ later version.
586
+
587
+ 15. Disclaimer of Warranty.
588
+
589
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597
+
598
+ 16. Limitation of Liability.
599
+
600
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608
+ SUCH DAMAGES.
609
+
610
+ 17. Interpretation of Sections 15 and 16.
611
+
612
+ If the disclaimer of warranty and limitation of liability provided
613
+ above cannot be given local legal effect according to their terms,
614
+ reviewing courts shall apply local law that most closely approximates
615
+ an absolute waiver of all civil liability in connection with the
616
+ Program, unless a warranty or assumption of liability accompanies a
617
+ copy of the Program in return for a fee.
618
+
619
+ END OF TERMS AND CONDITIONS
620
+
621
+ How to Apply These Terms to Your New Programs
622
+
623
+ If you develop a new program, and you want it to be of the greatest
624
+ possible use to the public, the best way to achieve this is to make it
625
+ free software which everyone can redistribute and change under these terms.
626
+
627
+ To do so, attach the following notices to the program. It is safest
628
+ to attach them to the start of each source file to most effectively
629
+ state the exclusion of warranty; and each file should have at least
630
+ the "copyright" line and a pointer to where the full notice is found.
631
+
632
+ <one line to give the program's name and a brief idea of what it does.>
633
+ Copyright (C) <year> <name of author>
634
+
635
+ This program is free software: you can redistribute it and/or modify
636
+ it under the terms of the GNU Affero General Public License as published by
637
+ the Free Software Foundation, either version 3 of the License, or
638
+ (at your option) any later version.
639
+
640
+ This program is distributed in the hope that it will be useful,
641
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
642
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643
+ GNU Affero General Public License for more details.
644
+
645
+ You should have received a copy of the GNU Affero General Public License
646
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
647
+
648
+ Also add information on how to contact you by electronic and paper mail.
649
+
650
+ If your software can interact with users remotely through a computer
651
+ network, you should also make sure that it provides a way for users to
652
+ get its source. For example, if your program is a web application, its
653
+ interface could display a "Source" link that leads users to an archive
654
+ of the code. There are many ways you could offer source, and different
655
+ solutions will be better for different programs; see section 13 for the
656
+ specific requirements.
657
+
658
+ You should also get your employer (if you work as a programmer) or school,
659
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
660
+ For more information on this, and how to apply and follow the GNU AGPL, see
661
+ <https://www.gnu.org/licenses/>.
inference/NOTICE ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Wasabi-30B
2
+ Copyright 2026 Sionic AI Inc.
3
+
4
+ Wasabi-30B is released under the GNU Affero General Public License v3.0 (see LICENSE).
5
+
6
+ This model is a fine-tune of Muse-Glimmer-30B (https://huggingface.co/meta-models/Muse-Glimmer-30B,
7
+ revision 97c77dff50b2797bcc558fa2d909761dbc575c59), licensed under the Apache License, Version 2.0
8
+ (notices/Muse-Glimmer-30B-LICENSE.txt). The base model snapshot has no NOTICE file. Modification: the base
9
+ weights were fine-tuned with LoRA for Japanese page transcription and the adapter was merged into BF16 weights.
10
+ The base model's publisher also publishes a usage policy, reproduced in notices/Muse-Glimmer-30B-USAGE_POLICY.md.
11
+
12
+ The page reader wasabi_read (orientation check, UVDoc flattening, whole-page read and per-page output) is released
13
+ under the GNU Affero General Public License v3.0.
14
+
15
+ UVDoc (https://github.com/tanguymagne/UVDoc), code at commit 4c9b82b537057aff2526e6dd118a847cdd072e82: MIT License,
16
+ Copyright (c) 2023 Tanguy MAGNE. wasabi_read downloads the UVDoc code and its pretrained weights
17
+ (model/best_model.pkl) from that commit at first use and does not redistribute them. The UVDoc repository carries
18
+ no weights-specific licence statement; the weights remain under their own terms.
inference/README.md ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # wasabi-read
2
+
3
+ Reads a directory of page images (.jpg, .jpeg, .png) and writes one Markdown file per page with Wasabi-30B.
4
+ The supported setup uses one checkpoint, Wasabi-30B, for every model step. Per page: an orientation check by
5
+ Wasabi-30B itself (a 4-way upright probe at 4,096 image tokens; a turn is applied only at margin >= 5.0), UVDoc dewarp
6
+ on CPU, the whole page read at 8,192 image tokens (greedy), and a temperature ladder when a first answer is degenerate.
7
+
8
+ ## Install
9
+
10
+ pip install -e "./inference[dewarp]"
11
+
12
+ Python 3.10+. Endpoint and local runs both dewarp on the local CPU, so the `dewarp` extra (torch and OpenCV) is needed
13
+ in both modes; without OpenCV the run refuses. The OpenCV, torch, numpy and Pillow versions and the UVDoc pins are part
14
+ of the output identity, so a rerun with other versions is refused and one output directory never mixes them.
15
+ A local GPU run needs the vLLM build of commit 6adad087 (released vLLM 0.26.0 has no muse_glimmer model); an endpoint
16
+ run needs no vLLM. After installing that build, run `python inference/patch_vllm_max_image_tokens.py --apply` with the
17
+ Python of the vLLM environment: unpatched, its processor rejects the `max_image_tokens` setting the servers are started
18
+ with. It edits one file, pinned by sha256 (`--check`, `--revert`); a server you start yourself for endpoint mode needs it
19
+ too. Download the weights with `huggingface-cli download`.
20
+
21
+ Tested environment: opencv-python-headless 5.0.0.93, torch 2.13.0+cu130, numpy 2.3.5, Pillow 13.0.0,
22
+ vllm 0.26.1rc1.dev769+g6adad0876, transformers 5.15.0, openai 3.37.0 (the package itself talks to servers with the
23
+ Python standard library; openai was present, not required).
24
+
25
+ The package sets `NUMPY_MADVISE_HUGEPAGE=0` at import unless you set it yourself: with numpy's default, a Linux host with
26
+ transparent huge pages on `madvise` can stall in the kernel while dewarping large page images. The output is the same
27
+ either way.
28
+
29
+ ## Configuration
30
+
31
+ - `WASABI_READ_API_KEY`: optional API key, sent to both the reader and the orientation endpoint. Set it in the
32
+ environment and keep the value out of commands, scripts and documentation.
33
+ - `WASABI_READ_CACHE`: directory for the downloaded UVDoc files. The default is `~/.cache/wasabi-read`, and the files go
34
+ into a pinned `uvdoc-<revision>` subdirectory. Page outputs and run caches stay under the output directory you pass.
35
+ - `--uvdoc-dir PATH`: keep the UVDoc files in PATH in place of the default cache. In the normal fetch mode, missing
36
+ pinned files are downloaded and every file is verified.
37
+ - `--uvdoc-source vendored --uvdoc-dir PATH`: use an existing local UVDoc copy without downloading. The code and weights
38
+ it needs must pass the built-in size and sha256 checks.
39
+
40
+ ## Orientation
41
+
42
+ The orientation check runs on its own server at 4,096 image tokens, before the reader starts. It uses Wasabi-30B and
43
+ turns a page only at margin >= 5.0. A turn is a decision from one greedy probe per rotation: a different serving stack
44
+ (attention backend, CUDA build, batching) can change it on a few pages.
45
+
46
+ ## Run on a CPU-only machine (endpoint mode)
47
+
48
+ Everything except the 30B forward passes runs on the local CPU. Point the package at two OpenAI-compatible servers, both
49
+ serving Wasabi-30B and started with `--reasoning-parser muse_glimmer`: the reader, with
50
+ `--mm-processor-kwargs '{"max_image_tokens": 8192}'`, and the orientation check, with
51
+ `--mm-processor-kwargs '{"max_image_tokens": 4096}'`. Name what each server serves with `--endpoint-revision` and
52
+ `--orient-endpoint-revision`: the URLs and revisions are part of the output identity, so a rerun against another server
53
+ is refused and one output directory never mixes servers. If the servers need a key, set `WASABI_READ_API_KEY`
54
+ (see Configuration).
55
+
56
+ python inference/wasabi_read.py pages/ out/ --engine endpoint --endpoint-url http://gpu-host:8000 --endpoint-revision wasabi-30b-v1.0 --orient-endpoint-url http://gpu-host:8001 --orient-endpoint-revision wasabi-30b-v1.0
57
+
58
+ `--plan` prints the stages and exits without loading a model.
59
+
60
+ python inference/wasabi_read.py pages/ out/ --engine endpoint --endpoint-url http://gpu-host:8000 --endpoint-revision wasabi-30b-v1.0 --orient-endpoint-url http://gpu-host:8001 --orient-endpoint-revision wasabi-30b-v1.0 --plan
61
+
62
+ ## Run on a local GPU (vllm engine)
63
+
64
+ The package starts and stops the local vLLM servers itself (the orientation check first, then the reader, both from the
65
+ same weights). The engine kind and its version, and the reasoning parser (vLLM's built-in `muse_glimmer`, or the sha256
66
+ of a `--reasoning-plugin` file), are part of the output and orientation identity, so a rerun on another engine or
67
+ parser is refused.
68
+
69
+ python inference/wasabi_read.py pages/ out/ --engine vllm --model-dir /models/Wasabi-30B --tensor-parallel-size 1 --whole-upscale-tokens 8192
70
+
71
+ `--engine transformers` loads the model in-process. It was not part of the measured runs and does not follow the
72
+ `--engine vllm` path: the image-token budget is set on the processor when the model is loaded (not through a server),
73
+ the sampling seed is applied with `torch.manual_seed`, and the raw decoded text is used, with no server-side
74
+ reasoning-channel split and no repetition-detection stop. Use it for a few pages only; its results are not comparable
75
+ to the vLLM runs.
76
+
77
+ ## Resume and exit codes
78
+
79
+ Each page is written as soon as it finishes (`<stem>.md`, atomic), with a sidecar under `out/.wasabi-read/`. Rerun the same
80
+ command to resume: finished pages are skipped, orientation and dewarp results are reused, and when nothing is left no
81
+ engine is started. An existing output that this input or package settings did not write is refused unless
82
+ `--overwrite-stale` is given. A page whose final answer is degenerate, empty or failed is not written and is listed with
83
+ its reason in `out/.wasabi-read/run-report.json`.
84
+
85
+ | exit | meaning |
86
+ |---|---|
87
+ | 0 | every page has an output |
88
+ | 2 | refusal (bad input or options, stale or locked output directory) |
89
+ | 4 | incomplete: some pages have no usable output; rerun to retry them |
90
+
91
+ ## Licence
92
+
93
+ Code: GNU Affero General Public License v3.0 (`LICENSE`, `NOTICE`). UVDoc code is MIT (Copyright (c) 2023 Tanguy MAGNE);
94
+ its pretrained weights are downloaded from the pinned commit at first use (size and sha256 checked before they are loaded)
95
+ and keep their own terms.
inference/patch_vllm_max_image_tokens.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Patch the vLLM build of commit 6adad087 so its Muse-Glimmer processor accepts ``max_image_tokens``.
3
+
4
+ Why: wasabi-read starts its vLLM servers with ``--mm-processor-kwargs '{"max_image_tokens": N}'`` (the whole-page
5
+ image-token budget). In vLLM commit 6adad08767583f52eb4d2122111af0bf638ed5e6, ``MuseGlimmerProcessor.__init__``
6
+ builds a default ``MuseGlimmerImageProcessor()`` (``max_image_tokens`` 4096) and forwards every unknown keyword to
7
+ ``ProcessorMixin.__init__``, which raises ``TypeError`` on ``max_image_tokens``, so the server does not start. The rest
8
+ of vLLM already reads ``image_processor.max_image_tokens``. This script makes one anchored edit to that ``__init__``:
9
+ it takes the key out before ``super().__init__`` and gives it to the image processor. Without the key, behaviour is
10
+ unchanged. Run it once after installing vLLM, with the Python of the environment that holds vLLM; any server you start
11
+ yourself with that kwarg (endpoint mode) needs it too.
12
+
13
+ The edit is keyed to exact file bytes: ``--apply`` acts only on the pinned ORIGINAL sha256 and verifies the pinned
14
+ PATCHED sha256 after writing; an already-patched file is a no-op (exit 0); any other file is refused (exit 2) with
15
+ nothing changed. ``--apply`` keeps the original next to the file (suffix ``.orig``); ``--revert`` restores it.
16
+
17
+ python inference/patch_vllm_max_image_tokens.py --check|--apply|--revert [--venv PREFIX]
18
+
19
+ PREFIX defaults to the running interpreter's ``sys.prefix``; the file is found under
20
+ ``PREFIX/lib/python3*/site-packages/vllm/transformers_utils/processors/muse_glimmer.py``.
21
+ Standard library only.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import argparse
27
+ import glob
28
+ import hashlib
29
+ import os
30
+ import sys
31
+ import tempfile
32
+
33
+ # vLLM commit 6adad08767583f52eb4d2122111af0bf638ed5e6, file of 582 lines
34
+ ORIGINAL_SHA256 = "66ff8858c571bb9b89702aafdfcc7f49271fe4e8e42a3d1ae7767624957ae96c"
35
+ PATCHED_SHA256 = "ee2033943a2fb0eb45333291466f3dfb3b1a8f914628a08990733fa0ab9c08ab"
36
+
37
+ REL_PATH = "vllm/transformers_utils/processors/muse_glimmer.py"
38
+ BACKUP_SUFFIX = ".orig"
39
+
40
+ ANCHOR_OLD = (
41
+ " if image_processor is None:\n"
42
+ " image_processor = MuseGlimmerImageProcessor()\n"
43
+ " if video_processor is None:\n"
44
+ )
45
+ ANCHOR_NEW = (
46
+ " # wasabi-read (inference/patch_vllm_max_image_tokens.py): pass max_image_tokens to the image processor.\n"
47
+ " _requested_max_image_tokens = kwargs.pop(\"max_image_tokens\", None)\n"
48
+ " if image_processor is None:\n"
49
+ " if _requested_max_image_tokens is None:\n"
50
+ " image_processor = MuseGlimmerImageProcessor()\n"
51
+ " else:\n"
52
+ " image_processor = MuseGlimmerImageProcessor(\n"
53
+ " max_image_tokens=int(_requested_max_image_tokens))\n"
54
+ " elif _requested_max_image_tokens is not None:\n"
55
+ " image_processor.max_image_tokens = int(_requested_max_image_tokens)\n"
56
+ " if video_processor is None:\n"
57
+ )
58
+
59
+ RC_OK = 0
60
+ RC_REFUSED = 2
61
+
62
+
63
+ def sha256_bytes(data: bytes) -> str:
64
+ return hashlib.sha256(data).hexdigest()
65
+
66
+
67
+ def locate(prefix: str) -> str:
68
+ hits = sorted(glob.glob(os.path.join(prefix, "lib", "python3*", "site-packages", REL_PATH)))
69
+ if len(hits) != 1:
70
+ raise FileNotFoundError(f"expected exactly one {REL_PATH} under {prefix}, found {len(hits)}: {hits}")
71
+ return hits[0]
72
+
73
+
74
+ def transform(data: bytes) -> bytes:
75
+ text = data.decode("utf-8")
76
+ n = text.count(ANCHOR_OLD)
77
+ if n != 1:
78
+ raise ValueError(f"anchor found {n} times (need exactly 1)")
79
+ return text.replace(ANCHOR_OLD, ANCHOR_NEW).encode("utf-8")
80
+
81
+
82
+ def atomic_write(path: str, data: bytes, *, like: str | None = None) -> None:
83
+ """Temp file in the same directory, fsync, then os.replace; keeps the permission bits of ``like`` (default: path)."""
84
+ mode = os.stat(like or path).st_mode & 0o7777
85
+ fd, tmp = tempfile.mkstemp(prefix=".patch-", dir=os.path.dirname(path))
86
+ try:
87
+ with os.fdopen(fd, "wb") as fh:
88
+ fh.write(data)
89
+ fh.flush()
90
+ os.fsync(fh.fileno())
91
+ os.chmod(tmp, mode)
92
+ os.replace(tmp, path)
93
+ except BaseException:
94
+ if os.path.exists(tmp):
95
+ os.unlink(tmp)
96
+ raise
97
+
98
+
99
+ def state(sha: str, orig: str, patched: str) -> str:
100
+ if sha == orig:
101
+ return "original"
102
+ if sha == patched:
103
+ return "patched"
104
+ return "unknown"
105
+
106
+
107
+ def do_check(path: str, orig: str, patched: str) -> int:
108
+ with open(path, "rb") as fh:
109
+ sha = sha256_bytes(fh.read())
110
+ st = state(sha, orig, patched)
111
+ print(f"{st} {sha} {path}")
112
+ return RC_OK if st != "unknown" else RC_REFUSED
113
+
114
+
115
+ def do_apply(path: str, orig: str, patched: str) -> int:
116
+ with open(path, "rb") as fh:
117
+ data = fh.read()
118
+ sha = sha256_bytes(data)
119
+ st = state(sha, orig, patched)
120
+ if st == "patched":
121
+ print(f"already patched {sha} {path}")
122
+ return RC_OK
123
+ if st == "unknown":
124
+ print(f"REFUSED: {path} sha {sha} is neither the pinned original {orig} nor the pinned patched {patched}; "
125
+ f"nothing changed", file=sys.stderr)
126
+ return RC_REFUSED
127
+ new = transform(data)
128
+ new_sha = sha256_bytes(new)
129
+ if new_sha != patched:
130
+ print(f"REFUSED: transformed sha {new_sha} != pinned patched {patched}; nothing changed", file=sys.stderr)
131
+ return RC_REFUSED
132
+ backup = path + BACKUP_SUFFIX
133
+ if os.path.exists(backup):
134
+ with open(backup, "rb") as fh:
135
+ bsha = sha256_bytes(fh.read())
136
+ if bsha != orig:
137
+ print(f"REFUSED: existing backup {backup} sha {bsha} != pinned original; nothing changed", file=sys.stderr)
138
+ return RC_REFUSED
139
+ else:
140
+ atomic_write(backup, data, like=path)
141
+ atomic_write(path, new)
142
+ with open(path, "rb") as fh:
143
+ final = sha256_bytes(fh.read())
144
+ if final != patched:
145
+ print(f"ERROR: post-write sha {final} != pinned patched {patched}", file=sys.stderr)
146
+ return RC_REFUSED
147
+ print(f"applied {orig} -> {final} {path} (backup {backup})")
148
+ return RC_OK
149
+
150
+
151
+ def do_revert(path: str, orig: str, patched: str) -> int:
152
+ with open(path, "rb") as fh:
153
+ sha = sha256_bytes(fh.read())
154
+ st = state(sha, orig, patched)
155
+ if st == "original":
156
+ print(f"already original {sha} {path}")
157
+ return RC_OK
158
+ if st == "unknown":
159
+ print(f"REFUSED: {path} sha {sha} is not the pinned patched sha; nothing changed", file=sys.stderr)
160
+ return RC_REFUSED
161
+ backup = path + BACKUP_SUFFIX
162
+ if not os.path.exists(backup):
163
+ print(f"REFUSED: no backup {backup}; nothing changed", file=sys.stderr)
164
+ return RC_REFUSED
165
+ with open(backup, "rb") as fh:
166
+ bdata = fh.read()
167
+ if sha256_bytes(bdata) != orig:
168
+ print(f"REFUSED: backup {backup} sha != pinned original; nothing changed", file=sys.stderr)
169
+ return RC_REFUSED
170
+ atomic_write(path, bdata)
171
+ with open(path, "rb") as fh:
172
+ final = sha256_bytes(fh.read())
173
+ if final != orig:
174
+ print(f"ERROR: post-revert sha {final} != pinned original {orig}", file=sys.stderr)
175
+ return RC_REFUSED
176
+ print(f"reverted {patched} -> {final} {path}")
177
+ return RC_OK
178
+
179
+
180
+ def main(argv: list[str] | None = None) -> int:
181
+ ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
182
+ ap.add_argument("--venv", default=sys.prefix,
183
+ help="prefix of the environment that holds vLLM (default: this interpreter's sys.prefix)")
184
+ mode = ap.add_mutually_exclusive_group(required=True)
185
+ mode.add_argument("--check", action="store_true")
186
+ mode.add_argument("--apply", action="store_true")
187
+ mode.add_argument("--revert", action="store_true")
188
+ ap.add_argument("--expect-shas", nargs=2, metavar=("ORIG", "PATCHED"), help=argparse.SUPPRESS) # test seam only
189
+ args = ap.parse_args(argv)
190
+ orig, patched = args.expect_shas or (ORIGINAL_SHA256, PATCHED_SHA256)
191
+ try:
192
+ path = locate(args.venv)
193
+ except FileNotFoundError as exc:
194
+ print(f"REFUSED: {exc}", file=sys.stderr)
195
+ return RC_REFUSED
196
+ if args.check:
197
+ return do_check(path, orig, patched)
198
+ if args.apply:
199
+ return do_apply(path, orig, patched)
200
+ return do_revert(path, orig, patched)
201
+
202
+
203
+ if __name__ == "__main__":
204
+ sys.exit(main())
inference/pyproject.toml ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "wasabi-read"
7
+ version = "0.1.0"
8
+ description = "Read a directory of page images into one Markdown file per page with Wasabi-30B."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = { file = "LICENSE" }
12
+ dependencies = ["pillow>=10", "numpy>=1.26"]
13
+
14
+ [project.optional-dependencies]
15
+ # dewarp: UVDoc on CPU, part of every normal run; install the package as ./inference[dewarp]. OpenCV is required
16
+ # (the upstream resize).
17
+ dewarp = ["torch>=2.3", "opencv-python-headless>=4.8"]
18
+ # local CPU/GPU reads without a server (unmeasured, few pages only)
19
+ transformers = ["torch>=2.3", "transformers>=5.15"]
20
+ test = ["pytest>=8"]
21
+
22
+ [project.scripts]
23
+ wasabi-read = "wasabi_read.cli:main"
24
+
25
+ [tool.setuptools]
26
+ packages = ["wasabi_read"]
27
+
28
+ # the two prompt files ship inside the package, so a regular (non-editable) install finds them
29
+ [tool.setuptools.package-data]
30
+ wasabi_read = ["prompts/*.txt"]
31
+
32
+ [tool.pytest.ini_options]
33
+ testpaths = ["tests"]
34
+ pythonpath = [".", "tests"]
inference/wasabi_read.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Launcher: python wasabi_read.py INPUT_DIR OUTPUT_DIR [options]."""
3
+ import os
4
+ import sys
5
+
6
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
7
+
8
+ from wasabi_read.cli import main # noqa: E402
9
+
10
+ if __name__ == "__main__":
11
+ sys.exit(main())
inference/wasabi_read/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """wasabi_read: read a directory of page images into one Markdown file per page (Wasabi-30B)."""
2
+ import os
3
+
4
+ # numpy reads this once, at its first import, so it is set before any submodule can import numpy or torch. Default numpy
5
+ # madvises huge pages for large arrays; on a Linux host with transparent huge pages on madvise, every fault on a large
6
+ # page array can then stall in kernel compaction and the CPU dewarp crawls. Off, the output bytes are unchanged. A value
7
+ # the user already set is kept.
8
+ os.environ.setdefault("NUMPY_MADVISE_HUGEPAGE", "0")
9
+
10
+ __version__ = "0.1.0"
11
+ CODE_VERSION = "wasabi-read-" + __version__
12
+
13
+
14
+ class PortError(RuntimeError):
15
+ """A refusal: bad input, bad configuration, or a stale/foreign output directory (exit 2)."""
16
+
17
+
18
+ class IncompleteOutput(PortError):
19
+ """The run finished but some pages have no usable output (exit 4)."""
inference/wasabi_read/cli.py ADDED
@@ -0,0 +1,426 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """wasabi_read command line: INPUT_DIR OUTPUT_DIR -> one Markdown file per page image.
2
+
3
+ Exit codes: 0 ok (every page has output), 2 refusal (bad input, bad configuration, stale or locked output),
4
+ 4 incomplete (some page has no usable output; its reason is in the run report).
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import argparse
9
+ import hashlib
10
+ import json
11
+ import sys
12
+ import threading
13
+ from concurrent.futures import ThreadPoolExecutor
14
+ from dataclasses import dataclass
15
+ from pathlib import Path
16
+ from typing import Any, Callable
17
+
18
+ from . import CODE_VERSION, IncompleteOutput, PortError
19
+ from . import dewarp as dw
20
+ from . import engine as eng
21
+ from . import orient as ori
22
+ from .identity import (PROMPT_PINS, check_model_tree, identity_sha, load_prompt, package_identity)
23
+ from .inputs import collect_images, sha256_file
24
+ from .output import OutputStore, atomic_write_bytes
25
+ from .reliability import page_verdict, read_page
26
+ from .views import ALLOWED_TOKENS, png_bytes, prepare_whole
27
+
28
+ EXIT_OK, EXIT_REFUSED, EXIT_INCOMPLETE = 0, 2, 4
29
+ ENGINES = ("vllm", "endpoint", "transformers")
30
+
31
+
32
+ @dataclass
33
+ class Deps:
34
+ """Test seams: a dewarp backend (PIL -> PIL) with its identity, and an engine opener (EngineSpec -> context
35
+ manager of a Reader)."""
36
+ dewarp: Callable | None = None
37
+ open_reader: Callable | None = None
38
+ dewarp_identity: dict | None = None
39
+
40
+
41
+ def build_parser() -> argparse.ArgumentParser:
42
+ p = argparse.ArgumentParser(
43
+ prog="wasabi-read", description="Read a directory of page images into one Markdown file per page.")
44
+ p.add_argument("input_dir", help="directory of .jpg/.jpeg/.png pages (searched recursively)")
45
+ p.add_argument("output_dir", help="receives <stem>.md per page plus a .wasabi-read/ state directory")
46
+ p.add_argument("--engine", choices=ENGINES, default="vllm",
47
+ help="vllm = spawn a local vLLM server; endpoint = call an OpenAI-compatible URL (CPU-only "
48
+ "machines); transformers = local, unmeasured, few pages only")
49
+ p.add_argument("--endpoint-url", help="reader endpoint base URL (engine endpoint)")
50
+ p.add_argument("--endpoint-revision",
51
+ help="what the reader endpoint serves, e.g. the model revision or its folder digest (engine "
52
+ "endpoint, required): recorded in the output identity with the URL")
53
+ p.add_argument("--model-dir", help="Wasabi-30B folder (engines vllm and transformers; hash-checked)")
54
+ p.add_argument("--served-model-name", default="wasabi-30b", help="model name sent in requests")
55
+ p.add_argument("--orient-judge", choices=("self", "base"), default="self",
56
+ help="orientation judge: self = Wasabi-30B itself, turn floor 5.0 (default); base = the base "
57
+ "Muse-Glimmer-30B, turn floor 2.0")
58
+ p.add_argument("--orient-model-dir", help="base Muse-Glimmer-30B folder (engines vllm/transformers, judge base)")
59
+ p.add_argument("--orient-endpoint-url",
60
+ help="judge endpoint URL (engine endpoint, required): a server started with max_image_tokens "
61
+ f"{ori.ORIENT_IMAGE_TOKENS}, serving Wasabi-30B (judge self) or the base model (judge base)")
62
+ p.add_argument("--orient-endpoint-revision",
63
+ help="what the judge endpoint serves (engine endpoint, required): recorded in the orientation "
64
+ "identity with the URL")
65
+ p.add_argument("--orient-served-model-name", default=None,
66
+ help="model name sent to the judge (default: --served-model-name for judge self, "
67
+ "muse-glimmer-30b-base for judge base)")
68
+ p.add_argument("--whole-upscale-tokens", type=int, choices=ALLOWED_TOKENS, default=8192,
69
+ help="whole-page image tokens; 4096 = the native whole view (no enlargement)")
70
+ p.add_argument("--view", choices=("whole",), default="whole", help="page view (the whole page)")
71
+ p.add_argument("--uvdoc-source", choices=("fetch", "vendored"), default="fetch",
72
+ help="fetch = download the pinned UVDoc commit at first use (size + sha256 checked before any "
73
+ "unpickle); vendored = use a local checkout given by --uvdoc-dir")
74
+ p.add_argument("--uvdoc-dir", help="UVDoc checkout directory (vendored: required; fetch: cache location)")
75
+ p.add_argument("--tensor-parallel-size", type=int, default=1)
76
+ p.add_argument("--reasoning-plugin", help="path of a vLLM reasoning-parser plugin file (engine vllm)")
77
+ p.add_argument("--max-tokens", type=int, default=eng.GLIMMER_MAX_TOKENS, help="completion-token cap per request")
78
+ p.add_argument("--page-budget-s", type=float, default=3600.0, help="wall budget per page, all attempts")
79
+ p.add_argument("--request-timeout-s", type=float, default=1800.0)
80
+ p.add_argument("--concurrency", type=int, default=4, help="pages in flight")
81
+ p.add_argument("--plan", action="store_true", help="print the stages and exit; loads no model, starts no engine")
82
+ p.add_argument("--overwrite-stale", action="store_true",
83
+ help="replace existing outputs that this input/package identity did not write (otherwise refused)")
84
+ p.add_argument("--report", help="run report JSON path (default OUTPUT_DIR/.wasabi-read/run-report.json)")
85
+ return p
86
+
87
+
88
+ def validate(args: argparse.Namespace) -> None:
89
+ if args.concurrency < 1:
90
+ raise PortError("--concurrency must be >= 1")
91
+ if args.engine == "endpoint":
92
+ if not args.endpoint_url or not args.endpoint_revision:
93
+ raise PortError("--engine endpoint needs --endpoint-url and --endpoint-revision (what that server serves)")
94
+ if not args.orient_endpoint_url or not args.orient_endpoint_revision:
95
+ raise PortError("--engine endpoint needs --orient-endpoint-url and --orient-endpoint-revision: a judge "
96
+ f"server started with max_image_tokens {ori.ORIENT_IMAGE_TOKENS}, serving Wasabi-30B "
97
+ "(judge self) or the base model (judge base)")
98
+ else:
99
+ if not args.model_dir:
100
+ raise PortError(f"--engine {args.engine} needs --model-dir")
101
+ if args.orient_judge == "base" and not args.orient_model_dir:
102
+ raise PortError("--orient-judge base needs --orient-model-dir (the base Muse-Glimmer-30B folder), "
103
+ "or use --orient-judge self")
104
+ if args.reasoning_plugin:
105
+ if args.engine != "vllm":
106
+ raise PortError("--reasoning-plugin applies to --engine vllm only (an endpoint's parser is the server's, "
107
+ "named by its revision)")
108
+ if not Path(args.reasoning_plugin).is_file():
109
+ raise PortError(f"--reasoning-plugin file does not exist: {args.reasoning_plugin}")
110
+ if args.uvdoc_source == "vendored" and not args.uvdoc_dir:
111
+ raise PortError("--uvdoc-source vendored needs --uvdoc-dir")
112
+
113
+
114
+ def plan_text(args: argparse.Namespace, images: list[Path], existing: int) -> str:
115
+ judge = "base Muse-Glimmer-30B" if args.orient_judge == "base" else "Wasabi-30B itself"
116
+ lines = [f"wasabi_read {CODE_VERSION} plan (no model loaded, no engine started)",
117
+ f"input: {len(images)} page image(s) in {args.input_dir}",
118
+ f"output: {args.output_dir} ({existing} <stem>.md already present; resume decides at run time)",
119
+ f"engine: {args.engine}",
120
+ f"stage 1 orient: 4-way upright probe on every page at {ori.ORIENT_IMAGE_TOKENS} image tokens, judge = "
121
+ f"{judge}, turn applied only if margin >= {ori.ORIENT_FLOORS[args.orient_judge]:g}",
122
+ f"stage 2 dewarp: UVDoc on CPU, source = {args.uvdoc_source}",
123
+ f"stage 3 read: whole page at {args.whole_upscale_tokens} image tokens, greedy, degeneration ladder "
124
+ f"{', '.join(str(t) for t in (0.1, 0.3, 0.5, 0.8))}",
125
+ "stage 4 write: <stem>.md per finished page (atomic), sidecar + journal under .wasabi-read/"]
126
+ return "\n".join(lines)
127
+
128
+
129
+ def _settings(args: argparse.Namespace, dewarp_ident: dict | None = None) -> dict[str, Any]:
130
+ return {"dewarp": dewarp_ident,"view": args.view, "whole_upscale_tokens": args.whole_upscale_tokens, "orient_judge": args.orient_judge,
131
+ "orient_floor": ori.ORIENT_FLOORS[args.orient_judge], "orient_variant": ori.ORIENT_VARIANT,
132
+ "orient_image_tokens": ori.ORIENT_IMAGE_TOKENS, "orient_preprocess": ori.ORIENT_PREPROCESS,
133
+ "uvdoc_commit": dw.UVDOC_COMMIT, "max_tokens": args.max_tokens, "ladder": [0.1, 0.3, 0.5, 0.8],
134
+ "serving": serving_identity(args)}
135
+
136
+
137
+ def _dist_version(dist: str) -> str | None:
138
+ import importlib.metadata as md
139
+ try:
140
+ return md.version(dist)
141
+ except md.PackageNotFoundError:
142
+ return None
143
+
144
+
145
+ def serving_identity(args: argparse.Namespace) -> dict[str, Any]:
146
+ """How the answers are produced and split into reasoning and content: the engine kind and the effective reasoning
147
+ parser (vLLM's built-in muse_glimmer with the vLLM version, or a plugin file by its sha256). An endpoint's parser
148
+ is the server's, covered by the endpoint revisions."""
149
+ if args.engine == "endpoint":
150
+ return {"engine": "endpoint", "reasoning_parser": {"source": "server side (endpoint revision)"}}
151
+ if args.engine == "transformers":
152
+ return {"engine": "transformers", "transformers": _dist_version("transformers"),
153
+ "reasoning_parser": {"source": "in-process split (no server parser)"}}
154
+ parser: dict[str, Any] = {"name": "muse_glimmer"}
155
+ if args.reasoning_plugin:
156
+ parser.update(source="plugin", plugin_sha256=sha256_file(Path(args.reasoning_plugin)))
157
+ else:
158
+ parser.update(source="vllm built-in")
159
+ return {"engine": "vllm", "vllm": _dist_version("vllm"), "reasoning_parser": parser}
160
+
161
+
162
+ def _endpoint(url: str, revision: str) -> dict[str, str]:
163
+ return {"url": url.rstrip("/"), "revision": revision}
164
+
165
+
166
+ def _judge_served_name(args: argparse.Namespace) -> str:
167
+ if args.orient_served_model_name:
168
+ return args.orient_served_model_name
169
+ return args.served_model_name if args.orient_judge == "self" else "muse-glimmer-30b-base"
170
+
171
+
172
+ def _model_identity(args: argparse.Namespace, state_dir: Path) -> dict[str, Any]:
173
+ """What serves the reads and the orientation probe: local folders by their file digests (the reader's pinned
174
+ files are checked), endpoints by URL plus the declared revision."""
175
+ judge: dict[str, Any] = {"mode": args.orient_judge, "served_name": _judge_served_name(args),
176
+ "image_tokens": ori.ORIENT_IMAGE_TOKENS}
177
+ if args.engine == "endpoint":
178
+ judge["endpoint"] = _endpoint(args.orient_endpoint_url, args.orient_endpoint_revision)
179
+ return {"served_model_name": args.served_model_name, "tree": None,
180
+ "endpoint": _endpoint(args.endpoint_url, args.endpoint_revision), "judge": judge}
181
+ state_dir.mkdir(parents=True, exist_ok=True)
182
+ tree = check_model_tree_cached(Path(args.model_dir), state_dir / "model-tree.json")
183
+ if args.orient_judge == "self":
184
+ judge["tree_sha256"] = tree["tree_sha256"]
185
+ else:
186
+ judge["tree_sha256"] = check_model_tree_cached(Path(args.orient_model_dir), state_dir / "orient-model-tree.json",
187
+ pins={})["tree_sha256"]
188
+ return {"served_model_name": args.served_model_name, "tree": tree, "endpoint": None, "judge": judge}
189
+
190
+
191
+ def orient_identity(judge: dict[str, Any], floor: float, serving: dict[str, Any] | None = None) -> str:
192
+ """The orientation-decision cache key: the judge (weights digest, or endpoint URL and revision; served name;
193
+ processor geometry), the serving identity (engine kind, reasoning parser), the prompt pin, the floor, the variant,
194
+ the image preprocessing and the probe request."""
195
+ probe = eng.build_probe_payload("", b"", "")
196
+ request = {k: v for k, v in probe.items() if k not in ("model", "messages")}
197
+ return hashlib.sha256(json.dumps(
198
+ {"judge": judge, "serving": serving, "prompt": PROMPT_PINS["orient-upright.txt"], "floor": floor,
199
+ "variant": ori.ORIENT_VARIANT,
200
+ "preprocess": ori.ORIENT_PREPROCESS, "request": request}, sort_keys=True).encode()).hexdigest()
201
+
202
+
203
+ def check_model_tree_cached(model_dir: Path, cache_file: Path, pins: dict | None = None) -> dict:
204
+ """check_model_tree, remembered by the (name, size, mtime) signature of the files that identify the model, so a
205
+ resume does not rehash 60 GB."""
206
+ from .identity import MODEL_FILE_PINS
207
+ names = sorted(MODEL_FILE_PINS if pins is None else pins)
208
+ sig = hashlib.sha256(json.dumps(
209
+ [(p.name, p.stat().st_size, p.stat().st_mtime_ns)
210
+ for p in (sorted(model_dir / n for n in names) if names else sorted(model_dir.iterdir())) if p.is_file()],
211
+ sort_keys=True).encode()).hexdigest() \
212
+ if model_dir.is_dir() else ""
213
+ if cache_file.is_file():
214
+ try:
215
+ hit = json.loads(cache_file.read_text(encoding="ascii"))
216
+ if hit.get("signature") == sig and sig:
217
+ return hit["result"]
218
+ except ValueError:
219
+ pass
220
+ result = check_model_tree(model_dir, pins=pins)
221
+ atomic_write_bytes(cache_file, (json.dumps({"signature": sig, "result": result}) + "\n").encode("ascii"))
222
+ return result
223
+
224
+
225
+ def _load_png_image(path: Path):
226
+ from PIL import Image
227
+ with Image.open(path) as im:
228
+ return im.convert("RGB")
229
+
230
+
231
+ def _spec(args, role: str) -> eng.EngineSpec:
232
+ import os
233
+ key = os.environ.get("WASABI_READ_API_KEY")
234
+ if role == "judge":
235
+ judge_dir = args.model_dir if args.orient_judge == "self" else args.orient_model_dir
236
+ return eng.EngineSpec(kind=args.engine, served_name=_judge_served_name(args),
237
+ model_dir=judge_dir, url=args.orient_endpoint_url, api_key=key,
238
+ tensor_parallel=args.tensor_parallel_size, image_tokens=ori.ORIENT_IMAGE_TOKENS,
239
+ max_tokens=eng.PROBE_MAX_TOKENS, reasoning_plugin=args.reasoning_plugin,
240
+ request_timeout_s=args.request_timeout_s)
241
+ return eng.EngineSpec(kind=args.engine, served_name=args.served_model_name, model_dir=args.model_dir,
242
+ url=args.endpoint_url, api_key=key, tensor_parallel=args.tensor_parallel_size,
243
+ image_tokens=args.whole_upscale_tokens, max_tokens=args.max_tokens,
244
+ reasoning_plugin=args.reasoning_plugin, request_timeout_s=args.request_timeout_s)
245
+
246
+
247
+ def run(args: argparse.Namespace, deps: Deps | None = None) -> int:
248
+ deps = deps or Deps()
249
+ opener = deps.open_reader or eng.open_reader
250
+ validate(args)
251
+ images = collect_images(Path(args.input_dir))
252
+ out_dir = Path(args.output_dir)
253
+ if args.plan:
254
+ existing = sum(1 for im in images if (out_dir / (im.stem + ".md")).is_file())
255
+ print(plan_text(args, images, existing))
256
+ return EXIT_OK
257
+ draft_prompt = load_prompt("draft.txt")
258
+ orient_prompt = load_prompt("orient-upright.txt")
259
+ state_dir = out_dir / ".wasabi-read"
260
+ dewarp_ident = (deps.dewarp_identity or {"backend": "injected"}) if deps.dewarp else dw.dewarp_identity()
261
+ model = _model_identity(args, state_dir)
262
+ identity = package_identity(_settings(args, dewarp_ident), model)
263
+ digest = identity_sha(identity)
264
+ orient_ident = orient_identity(model["judge"], ori.ORIENT_FLOORS[args.orient_judge],
265
+ identity["settings"]["serving"])
266
+ dewarp_key = hashlib.sha256(json.dumps(dewarp_ident, sort_keys=True).encode()).hexdigest()
267
+ shas = {im.stem: sha256_file(im) for im in images}
268
+ by_stem = {im.stem: im for im in images}
269
+ report: dict[str, Any] = {"schema": "wasabi-read-run-report-v1", "code_version": CODE_VERSION,
270
+ "identity_sha256": digest, "inputs": len(images), "skipped": 0, "written": 0,
271
+ "failed": [], "pages": {}, "stage_seconds": {}}
272
+ with OutputStore(out_dir, identity, digest, args.overwrite_stale) as store:
273
+ cls = store.classify([(s, shas[s]) for s in sorted(by_stem)])
274
+ report["skipped"] = len(cls["done"])
275
+ pending = sorted(cls["pending"])
276
+ # A rerun with nothing left to do writes nothing under the output directory (no journal line, no report).
277
+ if pending:
278
+ try:
279
+ store.journal_append({"event": "run_start", "inputs": len(images), "done": len(cls["done"]),
280
+ "pending": len(pending)})
281
+ _process(args, deps, opener, store, by_stem, shas, pending, draft_prompt, orient_prompt, orient_ident,
282
+ dewarp_key, report)
283
+ store.journal_append({"event": "run_end", "written": report["written"],
284
+ "failed": len(report["failed"])})
285
+ finally:
286
+ _write_report(args, store, report)
287
+ if report["failed"]:
288
+ print(f"INCOMPLETE: {len(report['failed'])} of {len(images)} page(s) have no usable output; see the run "
289
+ f"report: " + ", ".join(f"{f['stem']}={f['reason']}" for f in report["failed"][:10]), file=sys.stderr)
290
+ return EXIT_INCOMPLETE
291
+ print(f"ok: {report['written']} page(s) written, {report['skipped']} already done", file=sys.stderr)
292
+ return EXIT_OK
293
+
294
+
295
+ def _write_report(args, store: OutputStore, report: dict) -> None:
296
+ path = Path(args.report) if args.report else store.state / "run-report.json"
297
+ path.parent.mkdir(parents=True, exist_ok=True)
298
+ atomic_write_bytes(path, (json.dumps(report, indent=1, sort_keys=True, ensure_ascii=True) + "\n").encode("ascii"))
299
+
300
+
301
+ def _process(args, deps, opener, store, by_stem, shas, pending, draft_prompt, orient_prompt, orient_ident,
302
+ dewarp_key, report) -> None:
303
+ import time
304
+ lock = threading.Lock()
305
+ floor = ori.ORIENT_FLOORS[args.orient_judge]
306
+ backend = deps.dewarp or dw.TorchUVDoc(dw.resolve_uvdoc(args.uvdoc_source, args.uvdoc_dir))
307
+ prepared: dict[str, dict] = {}
308
+
309
+ def prep(stem: str) -> None:
310
+ try:
311
+ im = ori.load_upright(by_stem[stem])
312
+ sha = shas[stem]
313
+ dec = ori.orient_cached(im, sha, orient_ident, store.state / "cache", judge_reader[0].ask, orient_prompt,
314
+ png_bytes, _cache_write, floor)
315
+ rotated = ori.apply_angle(im, dec["applied_angle"])
316
+ # one dewarped image per input bytes, full orientation identity and full dewarp identity (UVDoc pins,
317
+ # preprocessing, OpenCV/torch/numpy/Pillow versions)
318
+ dpath = store.cache_path("dewarp", f"{sha}-{orient_ident}-{dewarp_key}.png")
319
+ if dpath.is_file():
320
+ dewarped_ok = True
321
+ else:
322
+ out = dw.dewarp_image(rotated, backend)
323
+ _cache_write(dpath, png_bytes(out))
324
+ dewarped_ok = True
325
+ with lock:
326
+ prepared[stem] = {"orient": dec, "dewarp_path": dpath, "dewarped": dewarped_ok}
327
+ except Exception as exc: # noqa: BLE001 (one bad page must not stop the others)
328
+ with lock:
329
+ _fail(report, store, stem, f"prep:{type(exc).__name__}:{exc}")
330
+
331
+ def read(stem: str) -> None:
332
+ p = prepared.get(stem)
333
+ if p is None:
334
+ return
335
+ try:
336
+ im = _load_png_image(p["dewarp_path"])
337
+ sent, view = prepare_whole(im, args.whole_upscale_tokens)
338
+ png = png_bytes(sent) if view["upscaled"] else png_bytes(im)
339
+ rd = reader_box[0]
340
+ rec = read_page(stem, lambda rung, t, s, rem: rd.call(png, draft_prompt, t, s, rem),
341
+ page_budget_s=args.page_budget_s)
342
+ ok, reason = page_verdict(rec)
343
+ with lock:
344
+ _account(report, stem, rec, p["orient"], view)
345
+ if ok:
346
+ store.write_page(stem, rec["final_text"], shas[stem], {
347
+ "orientation": {k: p["orient"].get(k) for k in ("applied_angle", "chosen_angle", "margin", "floored")},
348
+ "view": view, "outcome": "ok", "final_finish_reason": rec["final_finish_reason"],
349
+ "ladder_end": rec["ladder_end"], "retry_attempts": rec["retry_attempts"]})
350
+ with lock:
351
+ report["written"] += 1
352
+ store.journal_append({"event": "page_done", "stem": stem, "ladder_end": rec["ladder_end"]})
353
+ else:
354
+ with lock:
355
+ _fail(report, store, stem, reason)
356
+ except Exception as exc: # noqa: BLE001
357
+ with lock:
358
+ _fail(report, store, stem, f"read:{type(exc).__name__}:{exc}")
359
+
360
+ judge_reader: list = [None]
361
+ reader_box: list = [None]
362
+
363
+ def run_prep():
364
+ t0 = time.monotonic()
365
+ store.journal_append({"event": "stage_start", "stage": "orient+dewarp", "pages": len(pending)})
366
+ with ThreadPoolExecutor(max_workers=args.concurrency) as ex:
367
+ list(ex.map(prep, pending))
368
+ report["stage_seconds"]["orient_dewarp"] = round(time.monotonic() - t0, 1)
369
+
370
+ def run_read():
371
+ t0 = time.monotonic()
372
+ store.journal_append({"event": "stage_start", "stage": "read", "pages": len(prepared)})
373
+ with ThreadPoolExecutor(max_workers=args.concurrency) as ex:
374
+ list(ex.map(read, sorted(prepared)))
375
+ report["stage_seconds"]["read"] = round(time.monotonic() - t0, 1)
376
+
377
+ # The judge always has its own server at the probe geometry, the self-judge too (same weights, fewer image
378
+ # tokens than the read); it is released before the reader starts.
379
+ with opener(_spec(args, "judge")) as jd:
380
+ judge_reader[0] = jd
381
+ run_prep()
382
+ with opener(_spec(args, "reader")) as rd:
383
+ reader_box[0] = rd
384
+ run_read()
385
+
386
+
387
+ def _cache_write(path: Path, data: bytes) -> None:
388
+ atomic_write_bytes(path, data, unique=True)
389
+
390
+
391
+ def _fail(report: dict, store: OutputStore, stem: str, reason: str) -> None:
392
+ report["failed"].append({"stem": stem, "reason": reason})
393
+ store.journal_append({"event": "page_failed", "stem": stem, "reason": reason})
394
+
395
+
396
+ def _account(report: dict, stem: str, rec: dict, orient: dict, view: dict) -> None:
397
+ cands = rec.get("candidates") or []
398
+ report["pages"][stem] = {
399
+ "outcome": rec.get("outcome"), "ladder_end": rec.get("ladder_end"),
400
+ "final_finish_reason": rec.get("final_finish_reason"), "retry_attempts": rec.get("retry_attempts"),
401
+ "infra_retries": rec.get("infra_retries"), "initial_degen": rec.get("initial_degen"),
402
+ "final_degen": rec.get("final_degen"),
403
+ "selected_rung": (cands[rec["selected_index"]]["rung"] if rec.get("selected_index") is not None else None),
404
+ "candidate_finish_reasons": [c.get("finish_reason") for c in cands],
405
+ "applied_angle": orient.get("applied_angle"), "rotated": bool(orient.get("applied_angle")),
406
+ "upscaled": view.get("upscaled")}
407
+
408
+
409
+ def main(argv: list[str] | None = None, deps: Deps | None = None) -> int:
410
+ parser = build_parser()
411
+ try:
412
+ args = parser.parse_args(argv)
413
+ except SystemExit as exc: # argparse refusals (unknown engine, bad choice) exit 2
414
+ return int(exc.code) if isinstance(exc.code, int) else EXIT_REFUSED
415
+ try:
416
+ return run(args, deps)
417
+ except IncompleteOutput as exc:
418
+ print(f"INCOMPLETE: {exc}", file=sys.stderr)
419
+ return EXIT_INCOMPLETE
420
+ except PortError as exc:
421
+ print(f"REFUSED: {exc}", file=sys.stderr)
422
+ return EXIT_REFUSED
423
+
424
+
425
+ if __name__ == "__main__":
426
+ sys.exit(main())
inference/wasabi_read/dewarp.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """UVDoc dewarp on CPU: verified fetch, verified load, per-page dewarp.
2
+
3
+ The weights are a pickle: size and sha256 are checked BEFORE any unpickle, and the UVDoc code
4
+ files are checked before they are imported. torch is imported lazily and the device is always cpu.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import hashlib
9
+ import importlib.util
10
+ import os
11
+ import sys
12
+ import time
13
+ import urllib.error
14
+ import urllib.request
15
+ from pathlib import Path
16
+ from typing import Callable
17
+
18
+ from . import PortError
19
+
20
+ UVDOC_REPO = "tanguymagne/UVDoc"
21
+ UVDOC_COMMIT = "4c9b82b537057aff2526e6dd118a847cdd072e82"
22
+ WEIGHTS = "model/best_model.pkl"
23
+ WEIGHTS_BYTES = 32158393
24
+ #: sha256 pins of every file used, taken from the pinned upstream commit.
25
+ UVDOC_PINS = {
26
+ "model/best_model.pkl": "7e90861b8a516eb4bc51f84bd889cb77275743d2d1d3ca8091951ec9f2b7da23",
27
+ "model.py": "320f460edc54cf830dfdd9788dfbc1b96a836429b64ed6078a30582be6f59e42",
28
+ "utils.py": "64909e09e7493dcef1cd356b833c316e87c8ce31a544c567dee4b95ece78d3c2",
29
+ "LICENSE": "cf80bdbde76b47756c7fa62b56854ae54902979016bb08a6ba2edbebf93e9b90",
30
+ }
31
+ IMG_SIZE_FALLBACK = (488, 712) # upstream utils.IMG_SIZE [w, h]
32
+ NUM_FILTER, KERNEL_SIZE = 32, 5 # upstream utils.load_model
33
+ #: The dewarp preprocessing: the network input is resized with OpenCV (the upstream demo's resize), and an output of
34
+ #: another size is resized back to the input size.
35
+ DEWARP_PREPROCESS = ("cv2.resize INTER_LINEAR float32 to the UVDoc img_size; "
36
+ "PIL LANCZOS back to the input size when the output size differs")
37
+
38
+
39
+ def require_cv2():
40
+ """OpenCV is required: the network input is resized with it, as upstream does. There is no other resize path."""
41
+ try:
42
+ import cv2
43
+ except ImportError:
44
+ raise PortError("dewarp needs OpenCV: install the package with its dewarp extra "
45
+ "(pip install -e \"./inference[dewarp]\")") from None
46
+ return cv2
47
+
48
+
49
+ def dewarp_identity() -> dict:
50
+ """What a dewarped page depends on besides its input pixels: the pinned UVDoc files, the resize steps and the
51
+ library versions that run them. Part of the output identity and of the dewarp cache key; a missing OpenCV or torch
52
+ refuses here, before any page is read."""
53
+ import importlib.metadata as md
54
+ cv2 = require_cv2()
55
+ versions = {"opencv": cv2.__version__}
56
+ for dist in ("torch", "numpy", "pillow"):
57
+ try:
58
+ versions[dist] = md.version(dist)
59
+ except md.PackageNotFoundError:
60
+ raise PortError(f"dewarp needs {dist}: install the package with its dewarp extra") from None
61
+ return {"uvdoc_commit": UVDOC_COMMIT, "uvdoc_pins": dict(UVDOC_PINS), "num_filter": NUM_FILTER,
62
+ "kernel_size": KERNEL_SIZE, "preprocess": DEWARP_PREPROCESS, "device": "cpu",
63
+ "versions": versions}
64
+
65
+
66
+ def default_uvdoc_dir() -> Path:
67
+ return Path(os.environ.get("WASABI_READ_CACHE", str(Path.home() / ".cache" / "wasabi-read"))) / ("uvdoc-" + UVDOC_COMMIT[:8])
68
+
69
+
70
+ def url_of(path: str, commit: str = UVDOC_COMMIT) -> str:
71
+ return f"https://raw.githubusercontent.com/{UVDOC_REPO}/{commit}/{path}"
72
+
73
+
74
+ def download(url: str, timeout: float = 60.0, tries: int = 3) -> bytes:
75
+ last = None
76
+ for k in range(tries):
77
+ try:
78
+ with urllib.request.urlopen(url, timeout=timeout) as r: # noqa: S310 (pinned https URL)
79
+ return r.read()
80
+ except urllib.error.HTTPError as e:
81
+ raise PortError(f"UVDoc download: HTTP {e.code} on {url}") from None
82
+ except (urllib.error.URLError, TimeoutError, OSError) as e:
83
+ last = e
84
+ time.sleep(2 * (k + 1))
85
+ raise PortError(f"UVDoc download: network error {type(last).__name__} after {tries} tries on {url}")
86
+
87
+
88
+ def check_blob(rel: str, data: bytes) -> None:
89
+ """Refuse bytes that are not the pinned file (size for the weights, sha256 for every file)."""
90
+ if rel == WEIGHTS and len(data) != WEIGHTS_BYTES:
91
+ raise PortError(f"UVDoc {rel}: {len(data)} bytes != pinned {WEIGHTS_BYTES} (an LFS pointer or a wrong file)")
92
+ got = hashlib.sha256(data).hexdigest()
93
+ if got != UVDOC_PINS[rel]:
94
+ raise PortError(f"UVDoc {rel}: sha256 {got} != pinned {UVDOC_PINS[rel]}")
95
+
96
+
97
+ def verify_weights(path: Path) -> None:
98
+ """Size and sha256 of a weights file on disk, checked before it is ever unpickled."""
99
+ path = Path(path)
100
+ if not path.is_file():
101
+ raise PortError(f"UVDoc weights missing: {path}")
102
+ if path.stat().st_size != WEIGHTS_BYTES:
103
+ raise PortError(f"UVDoc weights {path}: {path.stat().st_size} bytes != pinned {WEIGHTS_BYTES}")
104
+ h = hashlib.sha256()
105
+ with path.open("rb") as f:
106
+ for block in iter(lambda: f.read(1 << 20), b""):
107
+ h.update(block)
108
+ if h.hexdigest() != UVDOC_PINS[WEIGHTS]:
109
+ raise PortError(f"UVDoc weights {path}: sha256 {h.hexdigest()} != pinned {UVDOC_PINS[WEIGHTS]}")
110
+
111
+
112
+ def verify_dir(uvdoc_dir: Path) -> None:
113
+ """Every pinned UVDoc file present and matching (weights first, so a bad pickle is refused before code import)."""
114
+ uvdoc_dir = Path(uvdoc_dir)
115
+ verify_weights(uvdoc_dir / WEIGHTS)
116
+ for rel in ("model.py", "utils.py", "LICENSE"):
117
+ f = uvdoc_dir / rel
118
+ if not f.is_file():
119
+ raise PortError(f"UVDoc file missing: {f}")
120
+ check_blob(rel, f.read_bytes())
121
+
122
+
123
+ def fetch_uvdoc(dest: Path, fetcher: Callable[[str], bytes] = download) -> Path:
124
+ """Make `dest` a verified UVDoc checkout of the pinned commit. An existing verified dir is reused. Every blob is
125
+ verified in memory before it is written, so unverified bytes never reach disk under their final name."""
126
+ dest = Path(dest)
127
+ try:
128
+ verify_dir(dest)
129
+ return dest
130
+ except PortError:
131
+ pass
132
+ blobs = {}
133
+ for rel in (WEIGHTS, "model.py", "utils.py", "LICENSE"):
134
+ data = fetcher(url_of(rel))
135
+ check_blob(rel, data)
136
+ blobs[rel] = data
137
+ for rel, data in blobs.items():
138
+ target = dest / rel
139
+ target.parent.mkdir(parents=True, exist_ok=True)
140
+ tmp = target.with_name(target.name + ".tmp")
141
+ tmp.write_bytes(data)
142
+ os.replace(tmp, target)
143
+ verify_dir(dest)
144
+ return dest
145
+
146
+
147
+ def resolve_uvdoc(source: str, uvdoc_dir: str | None, fetcher: Callable[[str], bytes] = download) -> Path:
148
+ if source == "vendored":
149
+ if not uvdoc_dir:
150
+ raise PortError("--uvdoc-source vendored needs --uvdoc-dir PATH (a local UVDoc checkout)")
151
+ verify_dir(Path(uvdoc_dir))
152
+ return Path(uvdoc_dir)
153
+ return fetch_uvdoc(Path(uvdoc_dir) if uvdoc_dir else default_uvdoc_dir(), fetcher)
154
+
155
+
156
+ def _load_module(name: str, path: Path):
157
+ spec = importlib.util.spec_from_file_location(name, str(path))
158
+ mod = importlib.util.module_from_spec(spec)
159
+ sys.modules[name] = mod
160
+ spec.loader.exec_module(mod)
161
+ return mod
162
+
163
+
164
+ class TorchUVDoc:
165
+ """The UVDoc network on CPU. Call with a PIL image, get the dewarped PIL image (same size)."""
166
+
167
+ def __init__(self, uvdoc_dir: Path):
168
+ verify_dir(uvdoc_dir) # size + sha256 before torch.load and before importing model.py
169
+ self._cv2 = require_cv2()
170
+ import torch
171
+ import torch.nn.functional as F
172
+ torch.set_num_threads(min(32, os.cpu_count() or 4))
173
+ self._torch = torch
174
+ uvmodel = _load_module("wasabi_uvdoc_model", Path(uvdoc_dir) / "model.py")
175
+ net = uvmodel.UVDocnet(num_filter=NUM_FILTER, kernel_size=KERNEL_SIZE)
176
+ ck = torch.load(str(Path(uvdoc_dir) / WEIGHTS), map_location="cpu", weights_only=True)
177
+ net.load_state_dict(ck["model_state"] if "model_state" in ck else ck)
178
+ net.eval()
179
+ try:
180
+ uvutils = _load_module("wasabi_uvdoc_utils", Path(uvdoc_dir) / "utils.py")
181
+ self.img_size, self.unwarp = tuple(uvutils.IMG_SIZE), uvutils.bilinear_unwarping
182
+ except Exception:
183
+ def unwarp(warped_img, point_positions, img_size): # mirror of upstream utils.bilinear_unwarping
184
+ up = F.interpolate(point_positions, size=(img_size[1], img_size[0]), mode="bilinear",
185
+ align_corners=True)
186
+ return F.grid_sample(warped_img, up.permute(0, 2, 3, 1), align_corners=True)
187
+ self.img_size, self.unwarp = IMG_SIZE_FALLBACK, unwarp
188
+ self.net = net
189
+
190
+ def __call__(self, im):
191
+ import numpy as np
192
+ from PIL import Image
193
+ torch = self._torch
194
+ W, H = im.size
195
+ arr = np.asarray(im, dtype=np.float32) / 255.0
196
+ small = self._cv2.resize(arr, tuple(self.img_size), interpolation=self._cv2.INTER_LINEAR) # upstream demo
197
+ inp = torch.from_numpy(small.transpose(2, 0, 1)).unsqueeze(0)
198
+ with torch.no_grad():
199
+ pts2d, _pts3d = self.net(inp)
200
+ full = torch.from_numpy(arr.transpose(2, 0, 1)).unsqueeze(0)
201
+ out = self.unwarp(warped_img=full, point_positions=torch.unsqueeze(pts2d[0], dim=0), img_size=(W, H))
202
+ o = (out[0].numpy().transpose(1, 2, 0).clip(0, 1) * 255).astype(np.uint8)
203
+ return Image.fromarray(o)
204
+
205
+
206
+ def dewarp_image(im, backend: Callable):
207
+ """Run a dewarp backend (callable PIL -> PIL) and return an image of the INPUT size (LANCZOS resize if the
208
+ backend returned another size)."""
209
+ from PIL import Image
210
+ out = backend(im)
211
+ if out.size != im.size:
212
+ out = out.resize(im.size, Image.LANCZOS)
213
+ return out.convert("RGB")
inference/wasabi_read/engine.py ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """One request builder, three backends: `vllm` (a spawned local server), `endpoint` (an OpenAI-compatible URL) and
2
+ `transformers` (local, CPU-capable, unmeasured). Greedy decoding is forced at rung 0 whatever generation_config says.
3
+
4
+ Request shape: greedy temperature 0, repetition_penalty 1.10, seed 42,
5
+ repetition_detection (4, 512, 16), chat_template_kwargs reasoning_strength=low, max_tokens 24576.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import base64
10
+ import contextlib
11
+ import json
12
+ import socket
13
+ import subprocess
14
+ import sys
15
+ import time
16
+ import urllib.error
17
+ import urllib.request
18
+ from dataclasses import dataclass, field
19
+ from typing import Any, Callable, Iterator
20
+
21
+ from . import PortError
22
+ from .views import whole_upscale_max_model_len
23
+
24
+ GLIMMER_MAX_TOKENS = 24576
25
+ GLIMMER_MAX_MODEL_LEN = 36864
26
+ REPETITION_STOP = (4, 512, 16) # (min_pattern_size, max_pattern_size, min_count)
27
+ REPETITION_PENALTY = 1.10
28
+ CHAT_TEMPLATE_KWARGS = {"reasoning_strength": "low", "current_date": "2026-10-16"}
29
+ REPETITION_STOP_REASON = "repetition_detected"
30
+ LOOP_STOP = "loop_stop"
31
+ PROBE_MAX_TOKENS = 1024
32
+ PROBE_TOP_LOGPROBS = 20
33
+ GREEDY_SEED = 42
34
+
35
+
36
+ class EngineError(RuntimeError):
37
+ """A transport or server failure (typed as an infra outcome by the caller)."""
38
+
39
+ def __init__(self, msg: str, kind: str = "error"):
40
+ super().__init__(msg)
41
+ self.kind = kind
42
+
43
+
44
+ def repetition_detection() -> dict:
45
+ mn, mx, cnt = REPETITION_STOP
46
+ return {"max_pattern_size": mx, "min_pattern_size": mn, "min_count": cnt}
47
+
48
+
49
+ def data_uri_png(png: bytes) -> str:
50
+ return "data:image/png;base64," + base64.b64encode(png).decode("ascii")
51
+
52
+
53
+ def _messages(png: bytes, prompt: str) -> list[dict]:
54
+ return [{"role": "user", "content": [
55
+ {"type": "image_url", "image_url": {"url": data_uri_png(png)}},
56
+ {"type": "text", "text": prompt}]}]
57
+
58
+
59
+ def build_read_payload(served_name: str, png: bytes, prompt: str, temperature: float, seed: int,
60
+ max_tokens: int = GLIMMER_MAX_TOKENS) -> dict:
61
+ """The page-read request. temperature is 0.0 on the first pass (greedy); the ladder raises it."""
62
+ return {"model": served_name, "messages": _messages(png, prompt), "max_tokens": int(max_tokens),
63
+ "temperature": float(temperature), "repetition_penalty": REPETITION_PENALTY, "seed": int(seed),
64
+ "repetition_detection": repetition_detection(), "chat_template_kwargs": dict(CHAT_TEMPLATE_KWARGS)}
65
+
66
+
67
+ def build_probe_payload(served_name: str, png: bytes, prompt: str, logprobs: bool = True) -> dict:
68
+ p = {"model": served_name, "messages": _messages(png, prompt), "max_tokens": PROBE_MAX_TOKENS,
69
+ "temperature": 0.0, "repetition_penalty": REPETITION_PENALTY, "seed": GREEDY_SEED,
70
+ "repetition_detection": repetition_detection(), "chat_template_kwargs": dict(CHAT_TEMPLATE_KWARGS)}
71
+ if logprobs:
72
+ p["logprobs"] = True
73
+ p["top_logprobs"] = PROBE_TOP_LOGPROBS
74
+ return p
75
+
76
+
77
+ def decode_response(body: dict) -> dict:
78
+ """OpenAI-style chat body -> {content, finish_reason, logprob_entries, prompt_tokens, completion_tokens}.
79
+ A native repetition stop is typed `loop_stop` (truncation class), never a clean `stop`."""
80
+ ch = (body.get("choices") or [{}])[0]
81
+ msg = ch.get("message") or {}
82
+ finish = ch.get("finish_reason")
83
+ if ch.get("stop_reason") == REPETITION_STOP_REASON:
84
+ finish = LOOP_STOP
85
+ lp = ch.get("logprobs")
86
+ usage = body.get("usage") or {}
87
+ return {"content": msg.get("content") or "", "finish_reason": finish,
88
+ "logprob_entries": lp.get("content") if isinstance(lp, dict) else None,
89
+ "prompt_tokens": usage.get("prompt_tokens"), "completion_tokens": usage.get("completion_tokens")}
90
+
91
+
92
+ class EndpointClient:
93
+ """POST /v1/chat/completions to an OpenAI-compatible server."""
94
+
95
+ def __init__(self, base_url: str, api_key: str | None = None):
96
+ self.base_url = base_url.rstrip("/")
97
+ self.api_key = api_key
98
+
99
+ def chat(self, payload: dict, timeout: float) -> dict:
100
+ data = json.dumps(payload).encode("utf-8")
101
+ headers = {"Content-Type": "application/json"}
102
+ if self.api_key:
103
+ headers["Authorization"] = "Bearer " + self.api_key
104
+ req = urllib.request.Request(self.base_url + "/v1/chat/completions", data=data, headers=headers, method="POST")
105
+ try:
106
+ with urllib.request.urlopen(req, timeout=timeout) as resp: # noqa: S310 (user-chosen endpoint)
107
+ return json.loads(resp.read().decode("utf-8"))
108
+ except urllib.error.HTTPError as exc:
109
+ raise EngineError(f"HTTP {exc.code}", "http_error") from None
110
+ except (socket.timeout, TimeoutError):
111
+ raise EngineError("request timed out", "timeout") from None
112
+ except urllib.error.URLError as exc:
113
+ if isinstance(exc.reason, (socket.timeout, TimeoutError)):
114
+ raise EngineError("request timed out", "timeout") from None
115
+ raise EngineError(f"{type(exc.reason).__name__}: {exc.reason}", "error") from None
116
+ except (OSError, ValueError) as exc:
117
+ raise EngineError(f"{type(exc).__name__}: {exc}", "error") from None
118
+
119
+
120
+ class Reader:
121
+ """Page reads and orientation asks over any client with `chat(payload, timeout) -> body`."""
122
+
123
+ def __init__(self, client, served_name: str, max_tokens: int = GLIMMER_MAX_TOKENS, request_timeout: float = 1800.0):
124
+ self.client = client
125
+ self.served_name = served_name
126
+ self.max_tokens = max_tokens
127
+ self.request_timeout = request_timeout
128
+
129
+ def _run(self, payload: dict, timeout: float) -> dict:
130
+ t = time.monotonic()
131
+ try:
132
+ body = self.client.chat(payload, max(1.0, min(self.request_timeout, timeout)))
133
+ out = decode_response(body)
134
+ out.update(error=None, latency_s=round(time.monotonic() - t, 3))
135
+ return out
136
+ except EngineError as exc:
137
+ return {"content": "", "finish_reason": exc.kind, "error": str(exc), "logprob_entries": None,
138
+ "latency_s": round(time.monotonic() - t, 3)}
139
+ except (socket.timeout, TimeoutError) as exc:
140
+ return {"content": "", "finish_reason": "timeout", "error": str(exc) or "timeout",
141
+ "logprob_entries": None, "latency_s": round(time.monotonic() - t, 3)}
142
+
143
+ def call(self, png: bytes, prompt: str, temperature: float, seed: int, timeout: float) -> dict:
144
+ return self._run(build_read_payload(self.served_name, png, prompt, temperature, seed, self.max_tokens), timeout)
145
+
146
+ def ask(self, png: bytes, prompt: str, logprobs: bool = True) -> dict:
147
+ return self._run(build_probe_payload(self.served_name, png, prompt, logprobs), self.request_timeout)
148
+
149
+
150
+ # ---------------------------------------------------------------- local vLLM server
151
+ def server_argv(model_dir: str, served_name: str, port: int, image_tokens: int, tensor_parallel: int,
152
+ max_tokens: int = GLIMMER_MAX_TOKENS, reasoning_plugin: str | None = None,
153
+ python: str | None = None) -> list[str]:
154
+ """The local vLLM server flags, plus tensor parallelism. GPU memory use is left to vLLM's default; to control it, serve
155
+ the model yourself and use `--engine endpoint`."""
156
+ argv = [python or sys.executable, "-m", "vllm.entrypoints.openai.api_server", "--model", str(model_dir),
157
+ "--served-model-name", served_name, "--host", "127.0.0.1", "--port", str(port),
158
+ "--max-model-len", str(whole_upscale_max_model_len(image_tokens, max_tokens, GLIMMER_MAX_MODEL_LEN)),
159
+ "--max-num-seqs", "64", "--safetensors-load-strategy", "prefetch", "--mm-encoder-attn-backend", "FLASHINFER"]
160
+ if tensor_parallel > 1:
161
+ argv += ["--tensor-parallel-size", str(tensor_parallel)]
162
+ if reasoning_plugin:
163
+ argv += ["--reasoning-parser-plugin", str(reasoning_plugin)]
164
+ argv += ["--reasoning-parser", "muse_glimmer", "--mm-processor-kwargs",
165
+ json.dumps({"max_image_tokens": int(image_tokens)})]
166
+ return argv
167
+
168
+
169
+ def free_port() -> int:
170
+ with socket.socket() as s:
171
+ s.bind(("127.0.0.1", 0))
172
+ return s.getsockname()[1]
173
+
174
+
175
+ @dataclass
176
+ class EngineSpec:
177
+ kind: str # vllm | endpoint | transformers
178
+ served_name: str
179
+ model_dir: str | None = None
180
+ url: str | None = None
181
+ api_key: str | None = None
182
+ tensor_parallel: int = 1
183
+ image_tokens: int = 4096
184
+ max_tokens: int = GLIMMER_MAX_TOKENS
185
+ reasoning_plugin: str | None = None
186
+ ready_timeout_s: float = 1800.0
187
+ request_timeout_s: float = 1800.0
188
+ spawn: Callable[[list[str]], Any] | None = field(default=None, repr=False)
189
+ probe_ready: Callable[[str], bool] | None = field(default=None, repr=False)
190
+
191
+
192
+ def _http_ready(url: str) -> bool:
193
+ try:
194
+ with urllib.request.urlopen(url + "/v1/models", timeout=5) as r: # noqa: S310 (loopback)
195
+ return r.status == 200
196
+ except (OSError, ValueError):
197
+ return False
198
+
199
+
200
+ @contextlib.contextmanager
201
+ def open_reader(spec: EngineSpec) -> Iterator[Reader]:
202
+ """Yield a Reader for the spec; a spawned server or a loaded model is released on exit."""
203
+ if spec.kind == "endpoint":
204
+ if not spec.url:
205
+ raise PortError("--engine endpoint needs --endpoint-url")
206
+ yield Reader(EndpointClient(spec.url, spec.api_key), spec.served_name, spec.max_tokens, spec.request_timeout_s)
207
+ return
208
+ if spec.kind == "vllm":
209
+ if not spec.model_dir:
210
+ raise PortError("--engine vllm needs --model-dir (and --orient-model-dir for --orient-judge base)")
211
+ port = free_port()
212
+ argv = server_argv(spec.model_dir, spec.served_name, port, spec.image_tokens, spec.tensor_parallel,
213
+ spec.max_tokens, spec.reasoning_plugin)
214
+ proc = (spec.spawn or (lambda a: subprocess.Popen(a)))(argv) # noqa: S603 (argv list, no shell)
215
+ url = f"http://127.0.0.1:{port}"
216
+ ready = spec.probe_ready or _http_ready
217
+ try:
218
+ deadline = time.monotonic() + spec.ready_timeout_s
219
+ while not ready(url):
220
+ if getattr(proc, "poll", lambda: None)() is not None:
221
+ raise PortError("the vLLM server exited before it was ready")
222
+ if time.monotonic() > deadline:
223
+ raise PortError(f"the vLLM server was not ready after {spec.ready_timeout_s:.0f} s")
224
+ time.sleep(2.0)
225
+ yield Reader(EndpointClient(url), spec.served_name, spec.max_tokens, spec.request_timeout_s)
226
+ finally:
227
+ with contextlib.suppress(Exception):
228
+ proc.terminate()
229
+ proc.wait(timeout=60)
230
+ return
231
+ if spec.kind == "transformers":
232
+ if not spec.model_dir:
233
+ raise PortError("--engine transformers needs --model-dir")
234
+ yield Reader(TransformersClient(spec.model_dir, spec.image_tokens), spec.served_name, spec.max_tokens,
235
+ spec.request_timeout_s)
236
+ return
237
+ raise PortError(f"unknown engine {spec.kind!r}")
238
+
239
+
240
+ # ---------------------------------------------------------------- transformers (local, unmeasured)
241
+ def generation_kwargs(payload: dict) -> dict:
242
+ """HF generate() kwargs from a request payload. temperature 0 is greedy: do_sample False and every sampling knob
243
+ cleared, so a generation_config with do_sample true / temperature 1.0 / top_k 64 / top_p 0.95 never applies."""
244
+ temp = float(payload.get("temperature") or 0.0)
245
+ kw: dict[str, Any] = {"max_new_tokens": int(payload["max_tokens"]),
246
+ "repetition_penalty": float(payload.get("repetition_penalty") or 1.0)}
247
+ if temp <= 0.0:
248
+ kw.update(do_sample=False, temperature=None, top_p=None, top_k=None)
249
+ else:
250
+ kw.update(do_sample=True, temperature=temp, top_p=None, top_k=None)
251
+ return kw
252
+
253
+
254
+ class TransformersClient:
255
+ """A local chat client on transformers. Correctness path for a few pages: it returns the raw decoded text (no
256
+ server-side reasoning-channel split, no repetition_detection stop); use the vllm or endpoint engine for real runs."""
257
+
258
+ def __init__(self, model_dir: str, image_tokens: int = 4096):
259
+ self.model_dir = model_dir
260
+ self.image_tokens = int(image_tokens)
261
+ self._model = None
262
+ self._proc = None
263
+
264
+ def _load(self):
265
+ if self._model is None:
266
+ import torch
267
+ from transformers import AutoModelForImageTextToText, AutoProcessor
268
+ self._proc = AutoProcessor.from_pretrained(self.model_dir, max_image_tokens=self.image_tokens)
269
+ self._model = AutoModelForImageTextToText.from_pretrained(self.model_dir, torch_dtype=torch.bfloat16)
270
+ self._model.eval()
271
+ return self._model, self._proc
272
+
273
+ def chat(self, payload: dict, timeout: float) -> dict:
274
+ import io
275
+
276
+ import torch
277
+ from PIL import Image
278
+ model, proc = self._load()
279
+ part = payload["messages"][0]["content"]
280
+ uri = next(p["image_url"]["url"] for p in part if p["type"] == "image_url")
281
+ im = Image.open(io.BytesIO(base64.b64decode(uri.split(",", 1)[1]))).convert("RGB")
282
+ text = next(p["text"] for p in part if p["type"] == "text")
283
+ msgs = [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": text}]}]
284
+ prompt = proc.apply_chat_template(msgs, add_generation_prompt=True, tokenize=False,
285
+ **(payload.get("chat_template_kwargs") or {}))
286
+ inputs = proc(text=[prompt], images=[im], return_tensors="pt")
287
+ want_lp = bool(payload.get("logprobs"))
288
+ if payload.get("seed") is not None:
289
+ torch.manual_seed(int(payload["seed"]))
290
+ with torch.no_grad():
291
+ out = model.generate(**inputs, **generation_kwargs(payload), output_scores=want_lp,
292
+ return_dict_in_generate=True)
293
+ new = out.sequences[0][inputs["input_ids"].shape[1]:]
294
+ content = proc.tokenizer.decode(new, skip_special_tokens=True)
295
+ hit_max = new.shape[0] >= int(payload["max_tokens"])
296
+ choice: dict[str, Any] = {"message": {"content": content}, "finish_reason": "length" if hit_max else "stop"}
297
+ if want_lp:
298
+ entries = []
299
+ for step, tok in zip(out.scores, new):
300
+ lps = torch.log_softmax(step[0].float(), dim=-1)
301
+ top = torch.topk(lps, PROBE_TOP_LOGPROBS)
302
+ entries.append({"token": proc.tokenizer.decode([int(tok)]), "logprob": float(lps[int(tok)]),
303
+ "top_logprobs": [{"token": proc.tokenizer.decode([int(i)]), "logprob": float(v)}
304
+ for v, i in zip(top.values, top.indices)]})
305
+ choice["logprobs"] = {"content": entries}
306
+ return {"choices": [choice], "usage": {"prompt_tokens": int(inputs["input_ids"].shape[1]),
307
+ "completion_tokens": int(new.shape[0])}}
inference/wasabi_read/identity.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Package identity: code version, prompt pins, model files, settings; the per-page resume key.
2
+ """
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from . import CODE_VERSION, PortError
11
+ from .inputs import sha256_file
12
+
13
+ PROMPT_DIR = Path(__file__).resolve().parent / "prompts"
14
+ #: sha256 of the shipped prompt files; a changed byte refuses.
15
+ PROMPT_PINS = {
16
+ "draft.txt": "1f80d2ca0bcb5c815ab15f1fe8d6a7fc16d2c2c305ffeabcec90eca4292d97f8",
17
+ "orient-upright.txt": "ad089da4c37eb9a25a5bf56dd4124497d2258c282ae0b593112984e10cd7d159",
18
+ }
19
+ DRAFT_PROMPT_ID = "wasabi-draft-v1"
20
+
21
+ #: Per-file pins of the files the model needs (the release SHA256SUMS). Extra files (README, notices)
22
+ #: do not change what is served, so a folder is accepted when every pinned file matches.
23
+ MODEL_FILE_PINS = {
24
+ "chat_template.jinja": "114f55ebdc1804c1af371197b9fdf2d6bb925966c9dfe46b73782a71bc07965e",
25
+ "config.json": "1c235df3179388bb56e522a25543d1f9e417a25e71b162887378a4362c5e4dbc",
26
+ "generation_config.json": "519ca0cad3bf6cb10c4f74dfb64786f651533bae2f316c609d66e0bcf5adfde6",
27
+ "model-00001-of-00002.safetensors": "0a5fdba915e499084969163518830e320040b0f2e03eb43843bbb71be450c5a7",
28
+ "model-00002-of-00002.safetensors": "20dfe7774a3ba1194b853e54fac1fb589bdc28872198b6e80c6c37ea32ef21b4",
29
+ "model.safetensors.index.json": "79f6028c3b5544f6be46607b8580d7376bf68bdc66647480fd3bfa520ad9efa3",
30
+ "processor_config.json": "97e2a486dd9866b81f40cf4b8bc0c9ced9a7cd8a5bc65aa4cc2f4de0712dae77",
31
+ "tokenizer.json": "c9dbee66967b58f31a7c27f723c3760da3526ccd0427578e8905b0abb0031c4d",
32
+ "tokenizer_config.json": "228f829a2d2d0d7793eb5bfdc0c20b2bbee27a9adff0b38c65edca4e7380420c",
33
+ }
34
+
35
+
36
+ def load_prompt(name: str, prompt_dir: Path | None = None, pins: dict | None = None) -> str:
37
+ """The prompt text, refused unless its sha256 matches the pin."""
38
+ pins = PROMPT_PINS if pins is None else pins
39
+ path = Path(prompt_dir or PROMPT_DIR) / name
40
+ if not path.is_file():
41
+ raise PortError(f"prompt file missing: {path}")
42
+ data = path.read_bytes()
43
+ got = hashlib.sha256(data).hexdigest()
44
+ if got != pins.get(name):
45
+ raise PortError(f"prompt {name} sha256 {got} != pinned {pins.get(name)}")
46
+ return data.decode("utf-8")
47
+
48
+
49
+ def tree_sha(entries: list[dict]) -> str:
50
+ digest = hashlib.sha256()
51
+ for entry in sorted(entries, key=lambda e: e["path"]):
52
+ digest.update((f"{entry['path']}\0{entry['sha256']}\n").encode("utf-8"))
53
+ return digest.hexdigest()
54
+
55
+
56
+ def check_model_tree(model_dir: Path, pins: dict | None = None) -> dict:
57
+ """Verify a model folder: every pinned file present with the pinned sha256 (a mismatch refuses).
58
+ Returns the digest of the pinned files."""
59
+ pins = MODEL_FILE_PINS if pins is None else pins
60
+ model_dir = Path(model_dir)
61
+ if not model_dir.is_dir():
62
+ raise PortError(f"model directory does not exist: {model_dir}")
63
+ # Only the files that are served identify the model: an output directory, caches or notes inside the folder
64
+ # never change the identity. With no pins (a base-model judge folder) every top-level file is used.
65
+ names = sorted(pins) if pins else sorted(p.name for p in model_dir.iterdir() if p.is_file())
66
+ by_path = {rel: sha256_file(model_dir / rel) for rel in names if (model_dir / rel).is_file()}
67
+ entries = [{"path": rel, "sha256": sha} for rel, sha in by_path.items()]
68
+ for rel, want in pins.items():
69
+ if rel not in by_path:
70
+ raise PortError(f"model file missing: {rel} in {model_dir}")
71
+ if by_path[rel] != want:
72
+ raise PortError(f"model file {rel} sha256 {by_path[rel]} != pinned {want}")
73
+ return {"tree_sha256": tree_sha(entries), "files": len(entries), "pinned_files": len(pins)}
74
+
75
+
76
+ def package_identity(settings: dict[str, Any], model: dict[str, Any]) -> dict[str, Any]:
77
+ """Everything that changes what a page's Markdown would be. `settings` carries view/token/judge/uvdoc fields."""
78
+ return {
79
+ "schema": "wasabi-read-identity-v1",
80
+ "code_version": CODE_VERSION,
81
+ "draft_prompt_sha256": PROMPT_PINS["draft.txt"],
82
+ "draft_prompt_id": DRAFT_PROMPT_ID,
83
+ "orient_prompt_sha256": PROMPT_PINS["orient-upright.txt"],
84
+ "model": model,
85
+ "settings": settings,
86
+ }
87
+
88
+
89
+ def identity_sha(identity: dict[str, Any]) -> str:
90
+ text = json.dumps(identity, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
91
+ return hashlib.sha256(text.encode("ascii")).hexdigest()
92
+
93
+
94
+ def page_key(input_sha256: str, identity_digest: str) -> str:
95
+ """The resume key of one page: its input bytes and the package identity."""
96
+ return hashlib.sha256(f"{input_sha256}:{identity_digest}".encode("ascii")).hexdigest()
inference/wasabi_read/inputs.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Input scan: .jpg/.jpeg/.png under a directory, unique stems (case-insensitive), sorted order.
2
+ """
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ from pathlib import Path
7
+
8
+ from . import PortError
9
+
10
+ IMAGE_SUFFIXES = {".jpg", ".jpeg", ".png"}
11
+ IMAGE_EXTENSIONS = ".jpg,.jpeg,.png"
12
+
13
+
14
+ def sha256_file(path: Path) -> str:
15
+ digest = hashlib.sha256()
16
+ with Path(path).open("rb") as stream:
17
+ for block in iter(lambda: stream.read(1024 * 1024), b""):
18
+ digest.update(block)
19
+ return digest.hexdigest()
20
+
21
+
22
+ def collect_images(input_dir: Path) -> list[Path]:
23
+ input_dir = Path(input_dir)
24
+ if not input_dir.is_dir():
25
+ raise PortError(f"input directory does not exist: {input_dir}")
26
+ images = sorted(
27
+ (p for p in input_dir.rglob("*") if p.is_file() and p.suffix.lower() in IMAGE_SUFFIXES),
28
+ key=lambda p: p.as_posix().casefold(),
29
+ )
30
+ if not images:
31
+ raise PortError(f"no supported images found; supported suffixes: {IMAGE_EXTENSIONS}")
32
+ ids: dict[str, Path] = {}
33
+ for image in images:
34
+ folded = image.stem.casefold()
35
+ if folded in ids:
36
+ raise PortError(f"duplicate image stem {image.stem!r}: {ids[folded]} and {image}")
37
+ ids[folded] = image
38
+ return images
inference/wasabi_read/orient.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """4-way upright probe, floored decision, rotation, decision cache.
2
+
3
+ Angle convention: `angle` = the counter-clockwise turn (PIL Transpose.ROTATE_<angle>) that makes the page upright.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import json
8
+ import math
9
+ from pathlib import Path
10
+ from typing import Callable
11
+
12
+ ORIENT_VARIANT = "upright-4way"
13
+ #: The turn floor per judge: the Wasabi self-judge (the default) turns a page only at margin >= 5.0; the base
14
+ #: model judge keeps its 2.0.
15
+ ORIENT_FLOORS = {"self": 5.0, "base": 2.0}
16
+ #: The judge server's processor geometry (max_image_tokens) for every probe request, whichever judge.
17
+ ORIENT_IMAGE_TOKENS = 4096
18
+ #: How a probe image is made from the input file: EXIF orientation applied, RGB, rotated, PNG-encoded.
19
+ ORIENT_PREPROCESS = "exif_transpose+rgb+pil_transpose+png"
20
+ ORI_LABELS = (0, 90, 180, 270)
21
+ ORIENT_MAX_TOKENS = 1024
22
+ ORIENT_TOP_LOGPROBS = 20
23
+ YES_WORDS = frozenset({"yes", chr(0x306F) + chr(0x3044)}) # ha-i
24
+ NO_WORDS = frozenset({"no", chr(0x3044) * 2 + chr(0x3048)}) # i-i-e
25
+ CHANNEL_TERMINATORS_PROBE = ("<|eom|>", "<|eot|>", "<|end_of_text|>")
26
+ _ORI_TRANSPOSE_NAMES = {90: "ROTATE_90", 180: "ROTATE_180", 270: "ROTATE_270"}
27
+
28
+
29
+ def load_upright(path: Path):
30
+ """Pixels with EXIF orientation applied (normalization only; the visual probe still runs on every page)."""
31
+ from PIL import Image, ImageOps
32
+ with Image.open(path) as im:
33
+ return ImageOps.exif_transpose(im).convert("RGB")
34
+
35
+
36
+ def ori_correct(im, angle: int):
37
+ from PIL import Image
38
+ if angle == 0:
39
+ return im.copy()
40
+ return im.transpose(getattr(Image.Transpose, _ORI_TRANSPOSE_NAMES[angle]))
41
+
42
+
43
+ def ori_make_item(im, angle: int):
44
+ """The exact inverse of ori_correct: a page whose label is `angle`."""
45
+ return ori_correct(im, (360 - angle) % 360)
46
+
47
+
48
+ def assert_rotation_inverse() -> None:
49
+ from PIL import Image
50
+ im = Image.new("RGB", (5, 3), (0, 0, 0))
51
+ im.putpixel((0, 0), (255, 0, 0))
52
+ im.putpixel((4, 1), (0, 255, 0))
53
+ want = im.tobytes()
54
+ for a in ORI_LABELS:
55
+ back = ori_correct(ori_make_item(im, a), a)
56
+ if back.size != im.size or back.tobytes() != want:
57
+ raise RuntimeError(f"rotation inverse broken at angle {a}")
58
+
59
+
60
+ def _entry_bytes(e: dict) -> bytes:
61
+ b = e.get("bytes")
62
+ if isinstance(b, list):
63
+ return bytes(b)
64
+ return str(e.get("token") or "").encode("utf-8")
65
+
66
+
67
+ def content_token_start(entries: list | None, content: str) -> tuple[int, int] | None:
68
+ """(start, end) of the CONTENT tokens inside a chat logprobs list that may also carry a reasoning turn."""
69
+ target = (content or "").strip().encode("utf-8")
70
+ if not entries or not target:
71
+ return None
72
+ end = len(entries)
73
+ while end > 0 and (str(entries[end - 1].get("token") or "") in CHANNEL_TERMINATORS_PROBE
74
+ or _entry_bytes(entries[end - 1]) == b""):
75
+ end -= 1
76
+ acc = b""
77
+ for k in range(end - 1, -1, -1):
78
+ acc = _entry_bytes(entries[k]) + acc
79
+ s = acc.strip()
80
+ if s == target:
81
+ return k, end
82
+ if len(s) > len(target):
83
+ return None
84
+ return None
85
+
86
+
87
+ def _lse(xs: list[float]) -> float:
88
+ m = max(xs)
89
+ return m + math.log(sum(math.exp(x - m) for x in xs))
90
+
91
+
92
+ def _word(tok: str) -> str:
93
+ return str(tok or "").strip().lower().strip(".!" + chr(0x3002) + chr(0xFF01))
94
+
95
+
96
+ def yes_no_margin(entry: dict) -> tuple[float | None, str]:
97
+ """log P(yes) - log P(no) at the first content token (variants pooled by logsumexp); a side absent from
98
+ top_logprobs is bounded by the lowest listed logprob (kind ..._bounded)."""
99
+ pool = {}
100
+ for t in (entry.get("top_logprobs") or []):
101
+ pool[t.get("token")] = t.get("logprob")
102
+ pool.setdefault(entry.get("token"), entry.get("logprob"))
103
+ vals = [v for v in pool.values() if isinstance(v, (int, float))]
104
+ ys = [v for k, v in pool.items() if _word(k) in YES_WORDS and isinstance(v, (int, float))]
105
+ ns = [v for k, v in pool.items() if _word(k) in NO_WORDS and isinstance(v, (int, float))]
106
+ if not ys and not ns:
107
+ return None, "logprob_absent_yes_no"
108
+ if ys and ns:
109
+ return _lse(ys) - _lse(ns), "logprob_margin"
110
+ floor = min(vals)
111
+ return ((_lse(ys) - floor) if ys else (floor - _lse(ns))), "logprob_margin_bounded"
112
+
113
+
114
+ def parse_yes_no(content: str) -> int | None:
115
+ parts = (content or "").split()
116
+ w = _word(parts[0] if parts else "")
117
+ return 1 if w in YES_WORDS else 0 if w in NO_WORDS else None
118
+
119
+
120
+ def pick_best(scores: dict) -> tuple[int, float, bool]:
121
+ """(chosen, margin, tie): the unique best candidate, else 0 (a tie for best keeps 0)."""
122
+ s = {c: v for c, v in scores.items() if v is not None}
123
+ if not s:
124
+ return 0, 0.0, True
125
+ best = max(s.values())
126
+ win = [c for c, v in s.items() if v == best]
127
+ if len(win) != 1:
128
+ return 0, 0.0, True
129
+ rest = [v for c, v in s.items() if c != win[0]]
130
+ return win[0], (best - max(rest)) if rest else 0.0, False
131
+
132
+
133
+ def decide_upright(resps: dict) -> dict:
134
+ lp, kinds, parsed = {}, {}, {}
135
+ for c in ORI_LABELS:
136
+ r = resps[c]
137
+ parsed[c] = parse_yes_no(r.get("content"))
138
+ span = content_token_start(r.get("logprob_entries"), r.get("content") or "")
139
+ lp[c], kinds[c] = (yes_no_margin(r["logprob_entries"][span[0]]) if span else
140
+ (None, "no_logprobs" if not r.get("logprob_entries") else "content_alignment_failed"))
141
+ if all(lp[c] is not None for c in ORI_LABELS):
142
+ scores = lp
143
+ kind = ("logprob_margin_bounded" if any(k == "logprob_margin_bounded" for k in kinds.values())
144
+ else "logprob_margin")
145
+ else:
146
+ scores = {c: float(parsed[c] or 0) for c in ORI_LABELS}
147
+ kind = "parsed_answer"
148
+ chosen, margin, tie = pick_best(scores)
149
+ return {"status": "ok", "chosen_angle": chosen, "score_kind": kind, "margin": margin, "tie": tie,
150
+ "parse_failed": any(parsed[c] is None for c in ORI_LABELS)}
151
+
152
+
153
+ def orient_turn_decision(chosen_angle, margin, floor: float | None) -> dict:
154
+ """The turn applied from the probe decision alone: a non-zero choice whose margin is None or under the floor
155
+ keeps 0."""
156
+ angle = int(chosen_angle) if chosen_angle is not None else 0
157
+ if floor is not None and angle != 0 and (margin is None or margin < floor):
158
+ return {"applied_angle": 0, "floored": True}
159
+ return {"applied_angle": angle, "floored": False}
160
+
161
+
162
+ def apply_angle(im, angle: int):
163
+ return ori_correct(im, angle)
164
+
165
+
166
+ def probe_page(im, ask: Callable[..., dict], prompt: str, png_of: Callable, floor: float) -> dict:
167
+ """Render the page at 0/90/180/270, ask the fixed yes/no question for each (logprobs on), decide, floor.
168
+ `ask(png_bytes, prompt, logprobs=True)` returns {content, logprob_entries, ...}; `png_of(pil_image)` encodes."""
169
+ resps = {c: ask(png_of(ori_correct(im, c)), prompt, logprobs=True) for c in ORI_LABELS}
170
+ failed = sorted(c for c, r in resps.items() if r.get("error"))
171
+ if failed: # an infra failure is never turned into a cached "keep 0" decision
172
+ raise RuntimeError(f"orientation probe request failed for rotation(s) {failed}: {resps[failed[0]]['error']}")
173
+ dec = decide_upright(resps)
174
+ turn = orient_turn_decision(dec["chosen_angle"], dec["margin"], floor)
175
+ return {"status": dec["status"], "chosen_angle": dec["chosen_angle"], "margin": dec["margin"],
176
+ "tie": dec["tie"], "score_kind": dec["score_kind"], "applied_angle": turn["applied_angle"],
177
+ "floored": turn["floored"], "floor": floor, "variant": ORIENT_VARIANT}
178
+
179
+
180
+ def decision_cache_path(cache_dir: Path, input_sha256: str, orient_ident: str) -> Path:
181
+ """One decision per input bytes and per orientation identity (judge weights or endpoint and revision, prompt
182
+ sha, floor, processor geometry, preprocessing)."""
183
+ return Path(cache_dir) / f"orient-{input_sha256}-{orient_ident}.json"
184
+
185
+
186
+ def orient_cached(im, input_sha256: str, orient_ident: str, cache_dir: Path, ask: Callable[..., dict],
187
+ prompt: str, png_of: Callable, write: Callable[[Path, bytes], None], floor: float) -> dict:
188
+ path = decision_cache_path(cache_dir, input_sha256, orient_ident)
189
+ if path.is_file():
190
+ try:
191
+ cached = json.loads(path.read_text(encoding="ascii"))
192
+ if isinstance(cached, dict) and "applied_angle" in cached:
193
+ return dict(cached, cached=True)
194
+ except ValueError:
195
+ pass
196
+ dec = probe_page(im, ask, prompt, png_of, floor)
197
+ write(path, (json.dumps(dec, sort_keys=True) + "\n").encode("ascii"))
198
+ return dict(dec, cached=False)
inference/wasabi_read/output.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Per-page atomic output, sidecar, skip/resume, single-process lock and fsync'ed journal.
2
+
3
+ Each page is written when it finishes (tmp + fsync + os.replace) so a rerun redoes only missing pages.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import fcntl
8
+ import hashlib
9
+ import json
10
+ import os
11
+ import threading
12
+ from datetime import datetime, timezone
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ from . import PortError
17
+ from .identity import page_key
18
+
19
+ STATE_DIR = ".wasabi-read"
20
+ JOURNAL_NAME = "journal.jsonl"
21
+ JOURNAL_SCHEMA = "wasabi-read-journal-v1"
22
+ SIDECAR_SCHEMA = "wasabi-read-page-v1"
23
+
24
+
25
+ def utc_stamp() -> str:
26
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
27
+
28
+
29
+ def _fsync_dir(path: Path) -> None:
30
+ try:
31
+ fd = os.open(str(path), os.O_RDONLY)
32
+ except OSError:
33
+ return
34
+ try:
35
+ os.fsync(fd)
36
+ except OSError:
37
+ pass
38
+ finally:
39
+ os.close(fd)
40
+
41
+
42
+ def atomic_write_bytes(path: Path, data: bytes, unique: bool = False) -> None:
43
+ """Write <path>.tmp, flush + fsync, os.replace onto <path>. A failure leaves no <path> from this call.
44
+ unique=True adds the pid and thread id to the tmp name (cache files that two pages with identical bytes share)."""
45
+ path = Path(path)
46
+ suffix = f".{os.getpid()}.{threading.get_ident()}.tmp" if unique else ".tmp"
47
+ tmp = path.with_name(path.name + suffix)
48
+ with tmp.open("wb") as handle:
49
+ handle.write(data)
50
+ handle.flush()
51
+ os.fsync(handle.fileno())
52
+ os.replace(tmp, path)
53
+ _fsync_dir(path.parent)
54
+
55
+
56
+ def sha256_bytes(data: bytes) -> str:
57
+ return hashlib.sha256(data).hexdigest()
58
+
59
+
60
+ class OutputStore:
61
+ def __init__(self, out_dir: Path, identity: dict[str, Any], identity_digest: str, overwrite_stale: bool = False):
62
+ self.out_dir = Path(out_dir)
63
+ self.state = self.out_dir / STATE_DIR
64
+ self.identity = identity
65
+ self.identity_digest = identity_digest
66
+ self.overwrite_stale = overwrite_stale
67
+ self._lock_handle = None
68
+
69
+ # ---- lifecycle
70
+ def open(self) -> "OutputStore":
71
+ self.out_dir.mkdir(parents=True, exist_ok=True)
72
+ for sub in ("pages", "cache"):
73
+ (self.state / sub).mkdir(parents=True, exist_ok=True)
74
+ handle = (self.state / ".lock").open("a", encoding="ascii")
75
+ try:
76
+ fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
77
+ except OSError:
78
+ handle.close()
79
+ raise PortError(f"another wasabi_read process is running this output directory: {self.out_dir}") from None
80
+ self._lock_handle = handle
81
+ self.discard_tmp()
82
+ data = (json.dumps(self.identity, indent=1, sort_keys=True, ensure_ascii=True) + "\n").encode("ascii")
83
+ path = self.state / "identity.json"
84
+ if not path.is_file() or path.read_bytes() != data: # an unchanged identity is not rewritten
85
+ atomic_write_bytes(path, data)
86
+ return self
87
+
88
+ def close(self) -> None:
89
+ if self._lock_handle is not None:
90
+ try:
91
+ fcntl.flock(self._lock_handle.fileno(), fcntl.LOCK_UN)
92
+ finally:
93
+ self._lock_handle.close()
94
+ self._lock_handle = None
95
+
96
+ def __enter__(self) -> "OutputStore":
97
+ return self.open()
98
+
99
+ def __exit__(self, *exc) -> None:
100
+ self.close()
101
+
102
+ def discard_tmp(self) -> list[str]:
103
+ """A .tmp left by a killed run is never trusted: it is removed (renamed aside is not needed, it is partial)."""
104
+ gone = []
105
+ for base in (self.out_dir, self.state / "pages", self.state / "cache", self.state):
106
+ for tmp in base.glob("*.tmp"):
107
+ tmp.unlink()
108
+ gone.append(tmp.name)
109
+ return gone
110
+
111
+ # ---- paths
112
+ def md_path(self, stem: str) -> Path:
113
+ return self.out_dir / (stem + ".md")
114
+
115
+ def sidecar_path(self, stem: str) -> Path:
116
+ return self.state / "pages" / (stem + ".json")
117
+
118
+ def cache_path(self, kind: str, name: str) -> Path:
119
+ return self.state / "cache" / f"{kind}-{name}"
120
+
121
+ # ---- resume
122
+ def read_sidecar(self, stem: str) -> dict | None:
123
+ path = self.sidecar_path(stem)
124
+ if not path.is_file():
125
+ return None
126
+ try:
127
+ value = json.loads(path.read_text(encoding="ascii", errors="replace"))
128
+ except ValueError:
129
+ return None
130
+ return value if isinstance(value, dict) else None
131
+
132
+ def page_state(self, stem: str, input_sha256: str) -> str:
133
+ """'done' (output + matching sidecar + matching bytes), 'pending' (nothing usable on disk) or 'stale'
134
+ (an output exists that this package identity / input did not write)."""
135
+ md = self.md_path(stem)
136
+ if not md.is_file() or md.stat().st_size == 0:
137
+ return "pending"
138
+ side = self.read_sidecar(stem)
139
+ want = page_key(input_sha256, self.identity_digest)
140
+ if (side and side.get("page_key") == want and side.get("input_sha256") == input_sha256
141
+ and side.get("md_sha256") == sha256_bytes(md.read_bytes())):
142
+ return "done"
143
+ return "stale"
144
+
145
+ def classify(self, pages: list[tuple[str, str]]) -> dict[str, list[str]]:
146
+ """pages = [(stem, input_sha256)]. Stale pages refuse unless overwrite_stale (then they are pending)."""
147
+ out: dict[str, list[str]] = {"done": [], "pending": [], "stale": []}
148
+ for stem, sha in pages:
149
+ out[self.page_state(stem, sha)].append(stem)
150
+ if out["stale"] and not self.overwrite_stale:
151
+ raise PortError(
152
+ f"{len(out['stale'])} output file(s) were not written by this input/package identity "
153
+ f"(e.g. {out['stale'][0]}.md); rerun with --overwrite-stale to replace them")
154
+ if out["stale"]:
155
+ out["pending"] = sorted(out["pending"] + out["stale"])
156
+ return out
157
+
158
+ # ---- writing
159
+ def write_page(self, stem: str, text: str, input_sha256: str, extra: dict[str, Any]) -> None:
160
+ data = text.encode("utf-8")
161
+ side = {"schema": SIDECAR_SCHEMA, "stem": stem, "input_sha256": input_sha256,
162
+ "page_key": page_key(input_sha256, self.identity_digest), "identity_sha256": self.identity_digest,
163
+ "md_sha256": sha256_bytes(data), "utc": utc_stamp(), **extra}
164
+ atomic_write_bytes(self.sidecar_path(stem),
165
+ (json.dumps(side, indent=1, sort_keys=True, ensure_ascii=True) + "\n").encode("ascii"))
166
+ atomic_write_bytes(self.md_path(stem), data)
167
+
168
+ # ---- journal
169
+ def journal_append(self, record: dict[str, Any]) -> None:
170
+ line = json.dumps({"schema": JOURNAL_SCHEMA, "utc": utc_stamp(), **record},
171
+ sort_keys=True, ensure_ascii=True) + "\n"
172
+ with (self.state / JOURNAL_NAME).open("a", encoding="ascii") as handle:
173
+ handle.write(line)
174
+ handle.flush()
175
+ os.fsync(handle.fileno())
176
+
177
+ def read_journal(self) -> list[dict[str, Any]]:
178
+ path = self.state / JOURNAL_NAME
179
+ rows = []
180
+ if path.is_file():
181
+ for line in path.read_text(encoding="ascii", errors="replace").splitlines():
182
+ try:
183
+ row = json.loads(line)
184
+ except ValueError:
185
+ continue # a torn last line of a killed run
186
+ if isinstance(row, dict):
187
+ rows.append(row)
188
+ return rows
inference/wasabi_read/prompts/draft.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ 文書画像を忠実に転記してください。
2
+ 本文と見出しを含め、画像内に記載された文字内容を最後まで省略せず、ページの読み順に出力してください。
3
+ 表は有効な HTML の <table>...</table> として表現してください。表の構造に LaTeX の表環境(\begin{tabular} など)を使わないでください。
4
+ 独立した数式は、組版可能な LaTeX 数式として表現してください。この LaTeX 形式を表の構造には使わないでください。
5
+ 数式は必ず区切り記号で囲んでください。文中の数式は $...$、独立した数式は単独の行に $$...$$ とし、手書きや写真の紙面でも Unicode の記号だけで書かないでください。
6
+ ルビは <ruby>親文字<rt>よみ</rt></ruby> の形で保持してください。
7
+ 転記済みの内容を繰り返して出力長を埋めないでください。ページ末尾に到達した時点で終了してください。
inference/wasabi_read/prompts/orient-upright.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ Is the text in this image upright, that is, neither turned sideways nor upside down? Answer with only yes or no.
inference/wasabi_read/reliability.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Degeneration check, temperature ladder and typed outcome for one page.
2
+
3
+ `loop_stop` is truncation (length) class.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import gzip
8
+ import time
9
+ from typing import Callable
10
+
11
+ LADDER = (0.1, 0.3, 0.5, 0.8)
12
+ BASE_SEED = 42
13
+ DEGEN_MIN_BYTES = 400
14
+ DEGEN_GZIP_RATIO = 0.18
15
+ LENGTH_CLASS = frozenset({"length", "loop_stop"})
16
+ INFRA_CLASS = frozenset({"time_budget", "error", "timeout", "http_error", "unknown"})
17
+
18
+
19
+ def is_degen(text: str, finish_reason: str | None) -> bool:
20
+ if finish_reason in LENGTH_CLASS:
21
+ return True
22
+ b = (text or "").encode("utf-8", "ignore")
23
+ return len(b) > DEGEN_MIN_BYTES and len(gzip.compress(b)) / max(len(b), 1) < DEGEN_GZIP_RATIO
24
+
25
+
26
+ def outcome_class(cand: dict) -> str:
27
+ fr = cand.get("finish_reason")
28
+ if cand.get("error") is not None or fr in INFRA_CLASS or fr is None:
29
+ return "infra"
30
+ if fr in LENGTH_CLASS:
31
+ return "length"
32
+ return "content"
33
+
34
+
35
+ def rung_params(rung: int) -> tuple[float, int]:
36
+ """(temperature, seed): rung 0 is greedy (temperature 0) with seed 42; rung k is LADDER[k-1] with seed 42+k."""
37
+ if rung == 0:
38
+ return 0.0, BASE_SEED
39
+ if not 1 <= rung <= len(LADDER):
40
+ raise ValueError(f"rung {rung} outside the four-rung ladder")
41
+ return LADDER[rung - 1], BASE_SEED + rung
42
+
43
+
44
+ def read_page(image_id: str, call: Callable[[int, float, int, float], dict], *, page_budget_s: float,
45
+ clock=time.monotonic) -> dict:
46
+ """First pass + ladder for one page. `call(rung, temperature, seed, remaining_s)` returns a candidate dict with at
47
+ least content / finish_reason / error. An infra outcome is retried once (never after time_budget); a
48
+ length-class or degenerate answer is re-asked only through the ladder; the first non-degenerate answer is kept."""
49
+ t0 = clock()
50
+ cands: list[dict] = []
51
+ infra_retries = 0
52
+
53
+ def attempt(rung: int):
54
+ nonlocal infra_retries
55
+ temp, seed = rung_params(rung)
56
+ for infra_try in (0, 1):
57
+ remaining = page_budget_s - (clock() - t0)
58
+ if remaining <= 0:
59
+ c = {"content": "", "finish_reason": "time_budget", "error": "per-page budget exhausted before request"}
60
+ else:
61
+ c = dict(call(rung, temp, seed, remaining))
62
+ c.update({"image_id": image_id, "candidate_index": len(cands), "rung": rung,
63
+ "infra_retry": infra_try, "temperature": temp, "seed": seed})
64
+ c.setdefault("content", "")
65
+ c.setdefault("error", None)
66
+ c["outcome_class"] = outcome_class(c)
67
+ c["degenerate"] = None if c["outcome_class"] == "infra" else is_degen(c["content"], c.get("finish_reason"))
68
+ c["selected"] = False
69
+ cands.append(c)
70
+ if c["outcome_class"] != "infra":
71
+ return c
72
+ if infra_try == 0 and c.get("finish_reason") != "time_budget":
73
+ infra_retries += 1
74
+ continue
75
+ return None
76
+ return None
77
+
78
+ first = attempt(0)
79
+ rec = {"image_id": image_id, "candidates": cands}
80
+ if first is None:
81
+ rec.update(outcome="error", first_index=None, selected_index=None, first_text="", final_text="",
82
+ first_finish_reason=None, final_finish_reason=None, initial_degen=None, final_degen=None,
83
+ retry_attempts=0, retry_adoptions=0, infra_retries=infra_retries, ladder_end="first_pass_infra")
84
+ return rec
85
+ sel = first
86
+ retry_attempts = adoptions = 0
87
+ ladder_end = "healthy_first_pass"
88
+ for rung in range(1, len(LADDER) + 1):
89
+ if not is_degen(sel["content"], sel.get("finish_reason")):
90
+ ladder_end = "selected_non_degenerate" if rung > 1 else "healthy_first_pass"
91
+ break
92
+ retry_attempts += 1
93
+ c = attempt(rung)
94
+ if c is None:
95
+ ladder_end = "infra_ended_ladder"
96
+ break
97
+ if not is_degen(c["content"], c.get("finish_reason")) or len(c["content"]) < len(sel["content"]):
98
+ sel = c
99
+ adoptions += 1
100
+ else:
101
+ ladder_end = ("selected_non_degenerate" if not is_degen(sel["content"], sel.get("finish_reason"))
102
+ else "ladder_exhausted")
103
+ sel["selected"] = True
104
+ rec.update(outcome="ok", first_index=first["candidate_index"], selected_index=sel["candidate_index"],
105
+ first_text=first["content"], final_text=sel["content"],
106
+ first_finish_reason=first.get("finish_reason"), final_finish_reason=sel.get("finish_reason"),
107
+ initial_degen=is_degen(first["content"], first.get("finish_reason")),
108
+ final_degen=is_degen(sel["content"], sel.get("finish_reason")),
109
+ retry_attempts=retry_attempts, retry_adoptions=adoptions,
110
+ infra_retries=infra_retries, ladder_end=ladder_end)
111
+ return rec
112
+
113
+
114
+ def page_verdict(rec: dict) -> tuple[bool, str]:
115
+ """(usable, reason): a page is written only when the call succeeded, the final answer is non-degenerate and
116
+ non-empty. A degenerate, empty or infra-failed page is never written (typed reason for the run report)."""
117
+ if rec.get("outcome") != "ok":
118
+ return False, "infra:" + str(rec.get("ladder_end") or "error")
119
+ if rec.get("final_degen"):
120
+ return False, "degenerate:" + str(rec.get("final_finish_reason"))
121
+ if not (rec.get("final_text") or "").strip():
122
+ return False, "empty"
123
+ return True, "ok"
inference/wasabi_read/views.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Whole-page view enlarged to N image tokens.
2
+ """
3
+ from __future__ import annotations
4
+
5
+ import io
6
+ import math
7
+
8
+ WHOLE_UPSCALE_CELL = 28
9
+ WHOLE_UPSCALE_LEN_MARGIN = 4096
10
+ #: The processor's own cap: a page is sent at its native size (never enlarged) and the server downsamples above it.
11
+ NATIVE_TOKENS = 4096
12
+ ALLOWED_TOKENS = (4096, 8192, 16384)
13
+
14
+
15
+ def whole_upscale_fill_grid(w: int, h: int, budget: int, cell: int = WHOLE_UPSCALE_CELL) -> tuple[int, int]:
16
+ """Largest (cols, rows) with the page's aspect ratio and cols * rows <= budget."""
17
+ if w <= 0 or h <= 0:
18
+ raise ValueError("empty page")
19
+ if budget < 1:
20
+ raise ValueError(f"budget must be >= 1, got {budget}")
21
+ s = math.sqrt(budget * cell * cell / (w * h))
22
+ cols, rows = max(1, math.floor(w * s / cell)), max(1, math.floor(h * s / cell))
23
+ while cols * rows > budget:
24
+ if cols >= rows:
25
+ cols -= 1
26
+ else:
27
+ rows -= 1
28
+ return cols, rows
29
+
30
+
31
+ def whole_upscale_native_grid(w: int, h: int, cell: int = WHOLE_UPSCALE_CELL) -> tuple[int, int]:
32
+ return max(1, w // cell), max(1, h // cell)
33
+
34
+
35
+ def whole_upscale_target(w: int, h: int, tokens: int, cell: int = WHOLE_UPSCALE_CELL) -> dict:
36
+ """Enlarge to the largest cell-aligned size whose grid fits `tokens`, iff that grid is larger than the native
37
+ grid and the native grid is under the budget; otherwise the page is sent native."""
38
+ n_cols, n_rows = whole_upscale_native_grid(w, h, cell)
39
+ f_cols, f_rows = whole_upscale_fill_grid(w, h, tokens, cell)
40
+ enlarge = f_cols * f_rows > n_cols * n_rows and n_cols * n_rows < tokens
41
+ sw, sh = (f_cols * cell, f_rows * cell) if enlarge else (w, h)
42
+ return {"native_wh": [w, h], "sent_wh": [sw, sh], "upscaled": enlarge,
43
+ "scale": round(sw / w, 4) if enlarge else 1.0,
44
+ "native_cells": n_cols * n_rows,
45
+ "expected_cells": f_cols * f_rows if enlarge else min(n_cols * n_rows, tokens)}
46
+
47
+
48
+ def whole_upscale_max_model_len(tokens: int, max_tokens: int, base: int,
49
+ margin: int = WHOLE_UPSCALE_LEN_MARGIN) -> int:
50
+ need = int(tokens) + int(max_tokens) + int(margin)
51
+ return max(int(base), -(-need // 1024) * 1024)
52
+
53
+
54
+ def view_target(w: int, h: int, tokens: int) -> dict:
55
+ """The whole-view resize for a token setting. 4096 = the native whole view: no enlargement (differs from
56
+ whole_upscale_target(4096), which would enlarge a small page to fill 4096)."""
57
+ if tokens not in ALLOWED_TOKENS:
58
+ raise ValueError(f"unsupported whole-view token setting {tokens}; choose from {ALLOWED_TOKENS}")
59
+ if tokens == NATIVE_TOKENS:
60
+ n_cols, n_rows = whole_upscale_native_grid(w, h)
61
+ return {"native_wh": [w, h], "sent_wh": [w, h], "upscaled": False, "scale": 1.0,
62
+ "native_cells": n_cols * n_rows, "expected_cells": min(n_cols * n_rows, tokens)}
63
+ return whole_upscale_target(w, h, tokens)
64
+
65
+
66
+ def png_bytes(im) -> bytes:
67
+ buf = io.BytesIO()
68
+ im.save(buf, format="PNG", optimize=False)
69
+ return buf.getvalue()
70
+
71
+
72
+ def prepare_whole(im, tokens: int):
73
+ """(PIL image to send, record). A page that is not enlarged is returned unchanged."""
74
+ from PIL import Image
75
+ w, h = im.size
76
+ rec = view_target(w, h, int(tokens))
77
+ rec["tokens"] = int(tokens)
78
+ if not rec["upscaled"]:
79
+ return im, rec
80
+ return im.resize(tuple(rec["sent_wh"]), Image.Resampling.LANCZOS), rec