ocr-bench 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
ocr_bench/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """OCR model evaluation toolkit — VLM-as-judge with per-dataset leaderboards."""
2
+
3
+ __version__ = "0.1.0"
ocr_bench/backends.py ADDED
@@ -0,0 +1,238 @@
1
+ """Judge backends — API-based (HF Inference Providers, OpenAI-compatible)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import abc
6
+ from collections import Counter
7
+ from concurrent.futures import ThreadPoolExecutor, as_completed
8
+ from typing import Any
9
+
10
+ import stamina
11
+ import structlog
12
+ from huggingface_hub import InferenceClient
13
+ from openai import OpenAI
14
+
15
+ from ocr_bench.judge import JUDGE_SCHEMA, Comparison, parse_judge_output
16
+
17
+ logger = structlog.get_logger()
18
+
19
+ # Retry on these exception types with exponential backoff + jitter.
20
+ _RETRYABLE = (Exception,)
21
+
22
+
23
+ class JudgeBackend(abc.ABC):
24
+ """Base class for judge backends."""
25
+
26
+ name: str
27
+ concurrency: int = 1
28
+
29
+ @abc.abstractmethod
30
+ def _call_single(self, comp: Comparison) -> dict[str, str]:
31
+ """Run the judge on a single comparison."""
32
+
33
+ def judge(self, comparisons: list[Comparison]) -> list[dict[str, str]]:
34
+ """Run the judge on a list of comparisons (concurrently if supported).
35
+
36
+ Returns a list of parsed results (one per comparison).
37
+ Each result is a dict with ``winner`` and ``reason`` keys,
38
+ or an empty dict on failure.
39
+ """
40
+ if self.concurrency <= 1 or len(comparisons) <= 1:
41
+ return [self._call_single(comp) for comp in comparisons]
42
+
43
+ # Concurrent execution preserving order
44
+ results: list[dict[str, str]] = [{}] * len(comparisons)
45
+ with ThreadPoolExecutor(max_workers=self.concurrency) as pool:
46
+ future_to_idx = {
47
+ pool.submit(self._call_single, comp): i
48
+ for i, comp in enumerate(comparisons)
49
+ }
50
+ for future in as_completed(future_to_idx):
51
+ idx = future_to_idx[future]
52
+ try:
53
+ results[idx] = future.result()
54
+ except Exception as exc:
55
+ logger.warning("judge_call_failed", idx=idx, error=str(exc))
56
+ results[idx] = {}
57
+ return results
58
+
59
+
60
+ DEFAULT_MAX_TOKENS = 1024
61
+
62
+
63
+ class InferenceProviderJudge(JudgeBackend):
64
+ """HF Inference Providers backend (Novita, Together, etc.)."""
65
+
66
+ def __init__(
67
+ self, model: str, provider: str | None = None, max_tokens: int = DEFAULT_MAX_TOKENS,
68
+ ):
69
+ self.name = f"{provider + ':' if provider else ''}{model}"
70
+ self.model = model
71
+ self.max_tokens = max_tokens
72
+ self.client = InferenceClient(model=model, provider=provider) # type: ignore[invalid-argument-type]
73
+
74
+ @stamina.retry(on=_RETRYABLE, attempts=6)
75
+ def _call_single(self, comp: Comparison) -> dict[str, str]:
76
+ response = self.client.chat_completion( # type: ignore[no-matching-overload]
77
+ messages=comp.messages,
78
+ max_tokens=self.max_tokens,
79
+ temperature=0.0,
80
+ response_format={"type": "json_object"},
81
+ extra_body={"chat_template_kwargs": {"enable_thinking": False}},
82
+ )
83
+ raw = response.choices[0].message.content.strip()
84
+ result = parse_judge_output(raw)
85
+ if not result:
86
+ logger.warning("empty_parse", backend=self.name, sample=comp.sample_idx)
87
+ return result
88
+
89
+
90
+ class OpenAICompatibleJudge(JudgeBackend):
91
+ """OpenAI-compatible endpoint (local vLLM server, Ollama, HF IE, etc.)."""
92
+
93
+ def __init__(
94
+ self,
95
+ base_url: str,
96
+ model: str = "default",
97
+ max_tokens: int = DEFAULT_MAX_TOKENS,
98
+ api_key: str = "not-needed",
99
+ extra_body: dict | None = None,
100
+ temperature: float = 0.0,
101
+ concurrency: int = 1,
102
+ ):
103
+ self.name = model if model != "default" else f"openai@{base_url}"
104
+ self.model = model
105
+ self.max_tokens = max_tokens
106
+ self.temperature = temperature
107
+ self.extra_body = extra_body if extra_body is not None else {"guided_json": JUDGE_SCHEMA}
108
+ self.concurrency = concurrency
109
+ self.client = OpenAI(base_url=base_url, api_key=api_key)
110
+
111
+ @stamina.retry(on=_RETRYABLE, attempts=3)
112
+ def _call_single(self, comp: Comparison) -> dict[str, str]:
113
+ response = self.client.chat.completions.create(
114
+ model=self.model,
115
+ messages=comp.messages, # type: ignore[invalid-argument-type]
116
+ max_tokens=self.max_tokens,
117
+ temperature=self.temperature,
118
+ extra_body=self.extra_body,
119
+ )
120
+ raw = response.choices[0].message.content.strip()
121
+ result = parse_judge_output(raw)
122
+ if not result:
123
+ logger.warning("empty_parse", backend=self.name, sample=comp.sample_idx)
124
+ return result
125
+
126
+
127
+ # ---------------------------------------------------------------------------
128
+ # Spec parsing
129
+ # ---------------------------------------------------------------------------
130
+
131
+ DEFAULT_JUDGE = "novita:Qwen/Qwen3.5-35B-A3B"
132
+
133
+
134
+ def parse_judge_spec(
135
+ spec: str, max_tokens: int = DEFAULT_MAX_TOKENS, concurrency: int = 1,
136
+ ) -> JudgeBackend:
137
+ """Parse a judge specification string into a backend.
138
+
139
+ Formats:
140
+ - ``"https://xxx.endpoints.huggingface.cloud"`` → :class:`OpenAICompatibleJudge`
141
+ (HF Inference Endpoints, OpenAI-compatible with HF token auth)
142
+ - ``"http://..."`` or ``"https://..."`` (other) → :class:`OpenAICompatibleJudge`
143
+ - ``"provider:org/model"`` (colon before first ``/``) → :class:`InferenceProviderJudge`
144
+ - anything else → :class:`InferenceProviderJudge` (no provider)
145
+ """
146
+ if spec.startswith("http://") or spec.startswith("https://"):
147
+ # Check for url:model format (e.g. https://...cloud/v1/:org/model)
148
+ url_part = spec
149
+ model_name = "default"
150
+ # Split on /v1/: to separate URL from model name
151
+ if "/v1/:" in spec:
152
+ url_part, model_name = spec.split("/v1/:", 1)
153
+ url_part += "/v1"
154
+
155
+ # HF Inference Endpoints — OpenAI-compatible, auth via HF token
156
+ if ".endpoints.huggingface." in url_part:
157
+ from huggingface_hub import get_token
158
+
159
+ base_url = url_part.rstrip("/")
160
+ if not base_url.endswith("/v1"):
161
+ base_url += "/v1"
162
+ token = get_token() or "not-needed"
163
+ return OpenAICompatibleJudge(
164
+ base_url=base_url,
165
+ model=model_name,
166
+ api_key=token,
167
+ max_tokens=max_tokens,
168
+ temperature=0.7,
169
+ extra_body={"chat_template_kwargs": {"enable_thinking": False}},
170
+ concurrency=concurrency,
171
+ )
172
+ return OpenAICompatibleJudge(
173
+ base_url=url_part, model=model_name, max_tokens=max_tokens,
174
+ concurrency=concurrency,
175
+ )
176
+
177
+ if ":" in spec:
178
+ # provider:model format — colon must come before first slash
179
+ colon_idx = spec.index(":")
180
+ slash_idx = spec.find("/")
181
+ if slash_idx == -1 or colon_idx < slash_idx:
182
+ provider, model = spec.split(":", 1)
183
+ return InferenceProviderJudge(model=model, provider=provider, max_tokens=max_tokens)
184
+
185
+ return InferenceProviderJudge(model=spec, max_tokens=max_tokens)
186
+
187
+
188
+ # ---------------------------------------------------------------------------
189
+ # Jury aggregation
190
+ # ---------------------------------------------------------------------------
191
+
192
+
193
+ def aggregate_jury_votes(
194
+ all_results: list[list[dict[str, str]]],
195
+ judge_names: list[str],
196
+ ) -> list[dict[str, Any]]:
197
+ """Aggregate votes from multiple judges using majority voting.
198
+
199
+ Args:
200
+ all_results: List of result lists, one per judge. Each inner list
201
+ has one dict per comparison.
202
+ judge_names: Names of the judges (same order as *all_results*).
203
+
204
+ Returns:
205
+ Aggregated results with ``winner``, ``reason``, and ``agreement`` fields.
206
+ """
207
+ if not all_results:
208
+ return []
209
+
210
+ n_comparisons = len(all_results[0])
211
+ n_judges = len(all_results)
212
+ aggregated: list[dict[str, Any]] = []
213
+
214
+ for i in range(n_comparisons):
215
+ votes: list[str] = []
216
+ reasons: list[str] = []
217
+ for j in range(n_judges):
218
+ result = all_results[j][i] if i < len(all_results[j]) else {}
219
+ winner = result.get("winner", "")
220
+ if winner:
221
+ votes.append(winner)
222
+ reasons.append(f"{judge_names[j]}: {result.get('reason', '')}")
223
+
224
+ if not votes:
225
+ aggregated.append({"winner": "tie", "reason": "no valid votes", "agreement": "0/0"})
226
+ continue
227
+
228
+ counter = Counter(votes)
229
+ majority_winner, majority_count = counter.most_common(1)[0]
230
+ agreement = f"{majority_count}/{len(votes)}"
231
+
232
+ aggregated.append({
233
+ "winner": majority_winner,
234
+ "reason": "; ".join(reasons),
235
+ "agreement": agreement,
236
+ })
237
+
238
+ return aggregated