pyocr-toolkit 0.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pyocr_toolkit/__init__.py +3 -0
- pyocr_toolkit/__main__.py +3 -0
- pyocr_toolkit/api.py +603 -0
- pyocr_toolkit/cli.py +315 -0
- pyocr_toolkit/compare.py +142 -0
- pyocr_toolkit/config.py +86 -0
- pyocr_toolkit/credentials.py +108 -0
- pyocr_toolkit/documents.py +326 -0
- pyocr_toolkit/env.example +48 -0
- pyocr_toolkit/jobs.py +205 -0
- pyocr_toolkit/llm/__init__.py +44 -0
- pyocr_toolkit/llm/anthropic_provider.py +188 -0
- pyocr_toolkit/llm/base.py +126 -0
- pyocr_toolkit/llm/catalog.py +337 -0
- pyocr_toolkit/llm/gemini_provider.py +98 -0
- pyocr_toolkit/llm/openai_provider.py +183 -0
- pyocr_toolkit/llm/prompts.py +61 -0
- pyocr_toolkit/search.py +88 -0
- pyocr_toolkit/service.py +269 -0
- pyocr_toolkit/static/common.js +538 -0
- pyocr_toolkit/static/compare.js +157 -0
- pyocr_toolkit/static/document.js +89 -0
- pyocr_toolkit/static/jobs.js +13 -0
- pyocr_toolkit/static/library.js +28 -0
- pyocr_toolkit/static/models.js +98 -0
- pyocr_toolkit/static/providers.js +44 -0
- pyocr_toolkit/static/reader.js +78 -0
- pyocr_toolkit/static/search.js +34 -0
- pyocr_toolkit/static/styles.css +819 -0
- pyocr_toolkit/static/workspace.js +420 -0
- pyocr_toolkit/static/workspaces.js +81 -0
- pyocr_toolkit/templates/_doc_card.html +30 -0
- pyocr_toolkit/templates/_doctabs.html +14 -0
- pyocr_toolkit/templates/_icons.html +55 -0
- pyocr_toolkit/templates/_llm_picker.html +12 -0
- pyocr_toolkit/templates/base.html +97 -0
- pyocr_toolkit/templates/compare.html +84 -0
- pyocr_toolkit/templates/document.html +80 -0
- pyocr_toolkit/templates/error.html +11 -0
- pyocr_toolkit/templates/help.html +244 -0
- pyocr_toolkit/templates/home.html +90 -0
- pyocr_toolkit/templates/jobs.html +15 -0
- pyocr_toolkit/templates/library.html +44 -0
- pyocr_toolkit/templates/models.html +67 -0
- pyocr_toolkit/templates/providers.html +104 -0
- pyocr_toolkit/templates/reader.html +28 -0
- pyocr_toolkit/templates/search.html +22 -0
- pyocr_toolkit/templates/workspace.html +109 -0
- pyocr_toolkit/templates/workspace_detail.html +42 -0
- pyocr_toolkit/templates/workspaces.html +42 -0
- pyocr_toolkit/web.py +186 -0
- pyocr_toolkit/workspaces.py +330 -0
- pyocr_toolkit-0.3.0.dist-info/METADATA +483 -0
- pyocr_toolkit-0.3.0.dist-info/RECORD +57 -0
- pyocr_toolkit-0.3.0.dist-info/WHEEL +4 -0
- pyocr_toolkit-0.3.0.dist-info/entry_points.txt +3 -0
- pyocr_toolkit-0.3.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Google Gemini via the ``google-genai`` SDK."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from google import genai
|
|
6
|
+
from google.genai import errors, types
|
|
7
|
+
|
|
8
|
+
from ..config import Settings
|
|
9
|
+
from . import catalog
|
|
10
|
+
from .base import Provider, ProviderError, TranscriptionRequest, TranscriptionResult
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class GeminiProvider(Provider):
|
|
14
|
+
id = "gemini"
|
|
15
|
+
label = "Google Gemini"
|
|
16
|
+
docs_url = "https://aistudio.google.com/apikey"
|
|
17
|
+
can_list_models = True
|
|
18
|
+
env_vars = [
|
|
19
|
+
("GEMINI_API_KEY", True, "API key from Google AI Studio (GOOGLE_API_KEY also works)"),
|
|
20
|
+
("GEMINI_MODEL", False, "default model, e.g. gemini-3.8-flash"),
|
|
21
|
+
]
|
|
22
|
+
suggested_models = catalog.recommended("gemini")
|
|
23
|
+
|
|
24
|
+
def __init__(self, settings: Settings) -> None:
|
|
25
|
+
self.settings = settings
|
|
26
|
+
self._client: genai.Client | None = None
|
|
27
|
+
|
|
28
|
+
@property
|
|
29
|
+
def api_key(self) -> str | None:
|
|
30
|
+
return self.settings.gemini_api_key or self.settings.google_api_key
|
|
31
|
+
|
|
32
|
+
@property
|
|
33
|
+
def default_model(self) -> str | None:
|
|
34
|
+
return self.settings.gemini_model
|
|
35
|
+
|
|
36
|
+
def missing_settings(self) -> list[str]:
|
|
37
|
+
return [] if self.api_key else ["GEMINI_API_KEY (or GOOGLE_API_KEY)"]
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
def client(self) -> genai.Client:
|
|
41
|
+
if self._client is None:
|
|
42
|
+
self._client = genai.Client(api_key=self.api_key)
|
|
43
|
+
return self._client
|
|
44
|
+
|
|
45
|
+
async def list_models(self) -> list[str] | None:
|
|
46
|
+
try:
|
|
47
|
+
pager = await self.client.aio.models.list(config={"page_size": 100})
|
|
48
|
+
names = []
|
|
49
|
+
async for m in pager:
|
|
50
|
+
actions = m.supported_actions or []
|
|
51
|
+
if actions and "generateContent" not in actions:
|
|
52
|
+
continue # embeddings, TTS-only, ...
|
|
53
|
+
names.append((m.name or "").removeprefix("models/"))
|
|
54
|
+
return sorted(n for n in names if n)
|
|
55
|
+
except (errors.ClientError, errors.ServerError) as exc:
|
|
56
|
+
raise ProviderError(f"{self.label}: could not list models: {exc.code} {exc.message}") from exc
|
|
57
|
+
|
|
58
|
+
async def _transcribe(self, req: TranscriptionRequest, model: str) -> TranscriptionResult:
|
|
59
|
+
try:
|
|
60
|
+
response = await self.client.aio.models.generate_content(
|
|
61
|
+
model=model,
|
|
62
|
+
contents=[
|
|
63
|
+
types.Part.from_bytes(data=req.image, mime_type=req.mime_type),
|
|
64
|
+
req.user_prompt,
|
|
65
|
+
],
|
|
66
|
+
config=types.GenerateContentConfig(
|
|
67
|
+
system_instruction=req.system_prompt,
|
|
68
|
+
# Gemini 2.5 counts thinking tokens against this limit,
|
|
69
|
+
# so leave generous head-room.
|
|
70
|
+
max_output_tokens=max(req.max_output_tokens, 32768),
|
|
71
|
+
),
|
|
72
|
+
)
|
|
73
|
+
except errors.ClientError as exc:
|
|
74
|
+
raise ProviderError(f"{self.label}: {exc.code} {exc.message}") from exc
|
|
75
|
+
except errors.ServerError as exc:
|
|
76
|
+
raise ProviderError(f"{self.label}: server error {exc.code} {exc.message}") from exc
|
|
77
|
+
|
|
78
|
+
warnings: list[str] = []
|
|
79
|
+
finish = None
|
|
80
|
+
if response.candidates:
|
|
81
|
+
finish = response.candidates[0].finish_reason
|
|
82
|
+
finish = getattr(finish, "name", finish)
|
|
83
|
+
if finish == "MAX_TOKENS":
|
|
84
|
+
warnings.append("output hit the max token limit; transcription is truncated")
|
|
85
|
+
elif finish in ("SAFETY", "RECITATION", "PROHIBITED_CONTENT", "BLOCKLIST"):
|
|
86
|
+
raise ProviderError(f"{self.label}: response blocked ({finish})")
|
|
87
|
+
text = response.text or ""
|
|
88
|
+
usage = response.usage_metadata
|
|
89
|
+
return TranscriptionResult(
|
|
90
|
+
text=text.strip(),
|
|
91
|
+
provider=self.id,
|
|
92
|
+
model=model,
|
|
93
|
+
latency_ms=0,
|
|
94
|
+
input_tokens=usage.prompt_token_count if usage else None,
|
|
95
|
+
output_tokens=usage.candidates_token_count if usage else None,
|
|
96
|
+
stop_reason=str(finish) if finish else None,
|
|
97
|
+
warnings=warnings,
|
|
98
|
+
)
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
"""OpenAI, Azure OpenAI and any OpenAI-compatible server (Ollama, vLLM, LM Studio, OpenRouter...)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
|
|
7
|
+
import openai
|
|
8
|
+
|
|
9
|
+
from ..config import Settings
|
|
10
|
+
from . import catalog
|
|
11
|
+
from .base import Provider, ProviderError, TranscriptionRequest, TranscriptionResult
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class _OpenAIChatBase(Provider):
|
|
15
|
+
#: OpenAI's newer models want ``max_completion_tokens``; many
|
|
16
|
+
#: OpenAI-compatible servers only understand the older ``max_tokens``.
|
|
17
|
+
token_param = "max_completion_tokens"
|
|
18
|
+
|
|
19
|
+
def __init__(self, settings: Settings) -> None:
|
|
20
|
+
self.settings = settings
|
|
21
|
+
self._client = None
|
|
22
|
+
|
|
23
|
+
def _make_client(self):
|
|
24
|
+
raise NotImplementedError
|
|
25
|
+
|
|
26
|
+
@property
|
|
27
|
+
def client(self):
|
|
28
|
+
if self._client is None:
|
|
29
|
+
self._client = self._make_client()
|
|
30
|
+
return self._client
|
|
31
|
+
|
|
32
|
+
async def list_models(self) -> list[str] | None:
|
|
33
|
+
try:
|
|
34
|
+
return sorted([m.id async for m in self.client.models.list()])
|
|
35
|
+
except openai.APIError as exc:
|
|
36
|
+
raise ProviderError(f"{self.label}: could not list models: {exc}") from exc
|
|
37
|
+
|
|
38
|
+
async def _transcribe(self, req: TranscriptionRequest, model: str) -> TranscriptionResult:
|
|
39
|
+
data_url = f"data:{req.mime_type};base64,{base64.b64encode(req.image).decode('ascii')}"
|
|
40
|
+
try:
|
|
41
|
+
response = await self.client.chat.completions.create(
|
|
42
|
+
model=model,
|
|
43
|
+
messages=[
|
|
44
|
+
{"role": "system", "content": req.system_prompt},
|
|
45
|
+
{
|
|
46
|
+
"role": "user",
|
|
47
|
+
"content": [
|
|
48
|
+
{"type": "text", "text": req.user_prompt},
|
|
49
|
+
{"type": "image_url", "image_url": {"url": data_url, "detail": "high"}},
|
|
50
|
+
],
|
|
51
|
+
},
|
|
52
|
+
],
|
|
53
|
+
**{self.token_param: req.max_output_tokens},
|
|
54
|
+
)
|
|
55
|
+
except openai.AuthenticationError as exc:
|
|
56
|
+
raise ProviderError(f"{self.label}: authentication failed - check the API key") from exc
|
|
57
|
+
except openai.NotFoundError as exc:
|
|
58
|
+
raise ProviderError(f"{self.label}: model/deployment '{model}' not found") from exc
|
|
59
|
+
except openai.RateLimitError as exc:
|
|
60
|
+
raise ProviderError(f"{self.label}: rate limited, try again shortly") from exc
|
|
61
|
+
except openai.APIStatusError as exc:
|
|
62
|
+
raise ProviderError(f"{self.label}: API error {exc.status_code}: {exc.message}") from exc
|
|
63
|
+
except openai.APIConnectionError as exc:
|
|
64
|
+
raise ProviderError(f"{self.label}: connection error: {exc}") from exc
|
|
65
|
+
|
|
66
|
+
if not response.choices:
|
|
67
|
+
raise ProviderError(f"{self.label}: empty response")
|
|
68
|
+
choice = response.choices[0]
|
|
69
|
+
warnings = []
|
|
70
|
+
if choice.finish_reason == "length":
|
|
71
|
+
warnings.append("output hit the max token limit; transcription is truncated")
|
|
72
|
+
if choice.finish_reason == "content_filter":
|
|
73
|
+
raise ProviderError(f"{self.label}: response blocked by the content filter")
|
|
74
|
+
refusal = getattr(choice.message, "refusal", None)
|
|
75
|
+
if refusal:
|
|
76
|
+
raise ProviderError(f"{self.label}: the model declined this page ({refusal})")
|
|
77
|
+
usage = response.usage
|
|
78
|
+
return TranscriptionResult(
|
|
79
|
+
text=(choice.message.content or "").strip(),
|
|
80
|
+
provider=self.id,
|
|
81
|
+
model=response.model or model,
|
|
82
|
+
latency_ms=0,
|
|
83
|
+
input_tokens=usage.prompt_tokens if usage else None,
|
|
84
|
+
output_tokens=usage.completion_tokens if usage else None,
|
|
85
|
+
stop_reason=choice.finish_reason,
|
|
86
|
+
warnings=warnings,
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class OpenAIProvider(_OpenAIChatBase):
|
|
91
|
+
id = "openai"
|
|
92
|
+
label = "OpenAI"
|
|
93
|
+
docs_url = "https://platform.openai.com/api-keys"
|
|
94
|
+
can_list_models = True
|
|
95
|
+
env_vars = [
|
|
96
|
+
("OPENAI_API_KEY", True, "API key from platform.openai.com"),
|
|
97
|
+
("OPENAI_MODEL", False, "default model, e.g. gpt-6.2-sol"),
|
|
98
|
+
("OPENAI_BASE_URL", False, "only for proxies / gateways"),
|
|
99
|
+
]
|
|
100
|
+
suggested_models = catalog.recommended("openai")
|
|
101
|
+
|
|
102
|
+
@property
|
|
103
|
+
def default_model(self) -> str | None:
|
|
104
|
+
return self.settings.openai_model
|
|
105
|
+
|
|
106
|
+
def missing_settings(self) -> list[str]:
|
|
107
|
+
return [] if self.settings.openai_api_key else ["OPENAI_API_KEY"]
|
|
108
|
+
|
|
109
|
+
def _make_client(self):
|
|
110
|
+
return openai.AsyncOpenAI(
|
|
111
|
+
api_key=self.settings.openai_api_key,
|
|
112
|
+
base_url=self.settings.openai_base_url,
|
|
113
|
+
timeout=self.settings.llm_timeout_s,
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
class AzureOpenAIProvider(_OpenAIChatBase):
|
|
118
|
+
id = "azure_openai"
|
|
119
|
+
label = "Azure OpenAI"
|
|
120
|
+
model_hint = "Azure deployment name"
|
|
121
|
+
docs_url = "https://learn.microsoft.com/azure/ai-services/openai/"
|
|
122
|
+
env_vars = [
|
|
123
|
+
("AZURE_OPENAI_API_KEY", True, "key of your Azure OpenAI resource"),
|
|
124
|
+
("AZURE_OPENAI_ENDPOINT", True, "https://<resource>.openai.azure.com"),
|
|
125
|
+
("AZURE_OPENAI_DEPLOYMENT", False, "name of a vision-capable deployment (gpt-6.2-sol, gpt-6.1-terra ...)"),
|
|
126
|
+
("AZURE_OPENAI_API_VERSION", False, "default 2024-10-21"),
|
|
127
|
+
]
|
|
128
|
+
|
|
129
|
+
@property
|
|
130
|
+
def default_model(self) -> str | None:
|
|
131
|
+
return self.settings.azure_openai_deployment
|
|
132
|
+
|
|
133
|
+
@property
|
|
134
|
+
def suggested_models(self) -> list[str]: # type: ignore[override]
|
|
135
|
+
return [self.settings.azure_openai_deployment] if self.settings.azure_openai_deployment else []
|
|
136
|
+
|
|
137
|
+
def missing_settings(self) -> list[str]:
|
|
138
|
+
missing = []
|
|
139
|
+
if not self.settings.azure_openai_api_key:
|
|
140
|
+
missing.append("AZURE_OPENAI_API_KEY")
|
|
141
|
+
if not self.settings.azure_openai_endpoint:
|
|
142
|
+
missing.append("AZURE_OPENAI_ENDPOINT")
|
|
143
|
+
return missing
|
|
144
|
+
|
|
145
|
+
def _make_client(self):
|
|
146
|
+
return openai.AsyncAzureOpenAI(
|
|
147
|
+
api_key=self.settings.azure_openai_api_key,
|
|
148
|
+
azure_endpoint=self.settings.azure_openai_endpoint,
|
|
149
|
+
api_version=self.settings.azure_openai_api_version,
|
|
150
|
+
timeout=self.settings.llm_timeout_s,
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
class OpenAICompatibleProvider(_OpenAIChatBase):
|
|
155
|
+
id = "openai_compatible"
|
|
156
|
+
label = "OpenAI-compatible (Ollama, vLLM, ...)"
|
|
157
|
+
docs_url = "https://github.com/ollama/ollama/blob/main/docs/openai.md"
|
|
158
|
+
can_list_models = True
|
|
159
|
+
env_vars = [
|
|
160
|
+
("OPENAI_COMPATIBLE_BASE_URL", True, "e.g. http://localhost:11434/v1 for Ollama"),
|
|
161
|
+
("OPENAI_COMPATIBLE_MODEL", False, "a vision model, e.g. qwen2.5vl:7b or llama3.2-vision"),
|
|
162
|
+
("OPENAI_COMPATIBLE_API_KEY", False, "only if the server needs one (OpenRouter does)"),
|
|
163
|
+
]
|
|
164
|
+
token_param = "max_tokens"
|
|
165
|
+
|
|
166
|
+
@property
|
|
167
|
+
def default_model(self) -> str | None:
|
|
168
|
+
return self.settings.openai_compatible_model
|
|
169
|
+
|
|
170
|
+
@property
|
|
171
|
+
def suggested_models(self) -> list[str]: # type: ignore[override]
|
|
172
|
+
return [self.settings.openai_compatible_model] if self.settings.openai_compatible_model else []
|
|
173
|
+
|
|
174
|
+
def missing_settings(self) -> list[str]:
|
|
175
|
+
return [] if self.settings.openai_compatible_base_url else ["OPENAI_COMPATIBLE_BASE_URL"]
|
|
176
|
+
|
|
177
|
+
def _make_client(self):
|
|
178
|
+
return openai.AsyncOpenAI(
|
|
179
|
+
# Local servers usually ignore the key, but the SDK requires one.
|
|
180
|
+
api_key=self.settings.openai_compatible_api_key or "not-needed",
|
|
181
|
+
base_url=self.settings.openai_compatible_base_url,
|
|
182
|
+
timeout=self.settings.llm_timeout_s,
|
|
183
|
+
)
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Prompts for page transcription.
|
|
2
|
+
|
|
3
|
+
The goal of the default ("verbatim") prompt is to make the LLM behave like a
|
|
4
|
+
very good OCR engine, *not* like an assistant: no fixing typos, no
|
|
5
|
+
summarising, no commentary. That makes its output a fair yardstick for the
|
|
6
|
+
Tesseract / native text layer, and shows what an LLM pipeline would actually
|
|
7
|
+
receive.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
_COMMON_RULES = """\
|
|
13
|
+
Rules:
|
|
14
|
+
- Transcribe ALL visible text: headers, footers, page numbers, captions, footnotes, stamps, \
|
|
15
|
+
watermarks, form labels and handwriting.
|
|
16
|
+
- Copy the text exactly as printed. Do NOT correct spelling, grammar, capitalisation or \
|
|
17
|
+
punctuation, do NOT translate, summarise, reorder or add anything.
|
|
18
|
+
- Keep numbers, dates, currency symbols, codes and IDs character-for-character.
|
|
19
|
+
- Follow natural reading order. For multi-column layouts, finish a column top to bottom \
|
|
20
|
+
before starting the next one.
|
|
21
|
+
- If a word is truly illegible write [illegible]; if a character is uncertain, give your \
|
|
22
|
+
best reading without comment.
|
|
23
|
+
- Output only the transcription: no preamble, no explanation, no code fences."""
|
|
24
|
+
|
|
25
|
+
VERBATIM_SYSTEM = f"""\
|
|
26
|
+
You are a meticulous transcription engine used to audit OCR quality. You receive an image \
|
|
27
|
+
of one document page and return its text exactly as it appears.
|
|
28
|
+
|
|
29
|
+
{_COMMON_RULES}
|
|
30
|
+
- Plain text only. Start a new line wherever the printed line ends. Keep end-of-line \
|
|
31
|
+
hyphenation as printed.
|
|
32
|
+
- For tables write one row per line with cells separated by " | "."""
|
|
33
|
+
|
|
34
|
+
MARKDOWN_SYSTEM = f"""\
|
|
35
|
+
You are a meticulous document transcription engine. You receive an image of one document \
|
|
36
|
+
page and return its full text as Markdown that preserves the structure.
|
|
37
|
+
|
|
38
|
+
{_COMMON_RULES}
|
|
39
|
+
- Use Markdown headings for headings, lists for lists, and GitHub-flavoured Markdown tables \
|
|
40
|
+
for tables (keep every cell, including empty ones).
|
|
41
|
+
- Join lines that belong to the same paragraph; separate paragraphs with a blank line.
|
|
42
|
+
- Describe non-text content only briefly in brackets, e.g. [figure: bar chart], [signature], \
|
|
43
|
+
[logo]."""
|
|
44
|
+
|
|
45
|
+
USER_PROMPT = "Transcribe this page."
|
|
46
|
+
|
|
47
|
+
PROMPT_MODES = {
|
|
48
|
+
"verbatim": {"label": "Verbatim (plain text, line by line)", "system": VERBATIM_SYSTEM},
|
|
49
|
+
"markdown": {"label": "Markdown (keep structure & tables)", "system": MARKDOWN_SYSTEM},
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def resolve_prompt(mode: str, custom_prompt: str | None = None) -> str:
|
|
54
|
+
if mode == "custom":
|
|
55
|
+
if not custom_prompt or not custom_prompt.strip():
|
|
56
|
+
raise ValueError("custom prompt mode needs a prompt")
|
|
57
|
+
return custom_prompt.strip()
|
|
58
|
+
try:
|
|
59
|
+
return PROMPT_MODES[mode]["system"]
|
|
60
|
+
except KeyError as exc:
|
|
61
|
+
raise ValueError(f"unknown prompt mode '{mode}'") from exc
|
pyocr_toolkit/search.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""Search inside a page's text layers.
|
|
2
|
+
|
|
3
|
+
Two kinds of hits are produced:
|
|
4
|
+
|
|
5
|
+
* **Boxes** - for the native text layer and Tesseract OCR we know where every
|
|
6
|
+
word sits on the page, so matches come back with rectangles (PDF points)
|
|
7
|
+
that the UI draws over the page image.
|
|
8
|
+
* **Snippets** - for every source (including LLM transcriptions, which have
|
|
9
|
+
no coordinates) we return the surrounding text with the match marked.
|
|
10
|
+
|
|
11
|
+
Matching is case-insensitive. A multi-word query matches a run of
|
|
12
|
+
consecutive words where the first query word may be a suffix of a page word,
|
|
13
|
+
the last may be a prefix, and the ones in the middle must match exactly -
|
|
14
|
+
so "quick bro" finds "The quick brown fox".
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import re
|
|
20
|
+
import unicodedata
|
|
21
|
+
|
|
22
|
+
from .documents import Word
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _fold(text: str) -> str:
|
|
26
|
+
return unicodedata.normalize("NFKC", text).casefold()
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _strip_punct(token: str) -> str:
|
|
30
|
+
return token.strip(".,;:!?\"'()[]{}<>“”‘’«»")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def find_boxes(words: list[Word], query: str) -> list[list[float]]:
|
|
34
|
+
q = [_fold(t) for t in query.split()]
|
|
35
|
+
if not q or not words:
|
|
36
|
+
return []
|
|
37
|
+
folded = [_fold(w.text) for w in words]
|
|
38
|
+
hits: list[list[float]] = []
|
|
39
|
+
if len(q) == 1:
|
|
40
|
+
for w, f in zip(words, folded):
|
|
41
|
+
if q[0] in f:
|
|
42
|
+
hits.append(w.rect)
|
|
43
|
+
return hits
|
|
44
|
+
n = len(q)
|
|
45
|
+
q = [_strip_punct(t) for t in q]
|
|
46
|
+
stripped = [_strip_punct(f) for f in folded]
|
|
47
|
+
for i in range(len(words) - n + 1):
|
|
48
|
+
window = stripped[i : i + n]
|
|
49
|
+
if (
|
|
50
|
+
window[0].endswith(q[0])
|
|
51
|
+
and window[-1].startswith(q[-1])
|
|
52
|
+
and window[1:-1] == q[1:-1]
|
|
53
|
+
):
|
|
54
|
+
hits.extend(w.rect for w in words[i : i + n])
|
|
55
|
+
return hits
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def find_snippets(text: str, query: str, context: int = 60, limit: int = 20) -> list[dict]:
|
|
59
|
+
"""Return up to ``limit`` snippets around case-insensitive matches.
|
|
60
|
+
|
|
61
|
+
Whitespace in the query matches any run of whitespace in the text, so a
|
|
62
|
+
phrase broken across lines is still found.
|
|
63
|
+
"""
|
|
64
|
+
terms = query.split()
|
|
65
|
+
if not terms:
|
|
66
|
+
return []
|
|
67
|
+
pattern = re.compile(r"\s+".join(re.escape(t) for t in terms), re.IGNORECASE)
|
|
68
|
+
snippets = []
|
|
69
|
+
for m in pattern.finditer(text):
|
|
70
|
+
start, end = m.start(), m.end()
|
|
71
|
+
before = text[max(0, start - context) : start]
|
|
72
|
+
after = text[end : end + context]
|
|
73
|
+
snippets.append({
|
|
74
|
+
"before": ("…" if start > context else "") + before.replace("\n", " "),
|
|
75
|
+
"match": m.group(0).replace("\n", " "),
|
|
76
|
+
"after": after.replace("\n", " ") + ("…" if end + context < len(text) else ""),
|
|
77
|
+
"offset": start,
|
|
78
|
+
})
|
|
79
|
+
if len(snippets) >= limit:
|
|
80
|
+
break
|
|
81
|
+
return snippets
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def count_matches(text: str, query: str) -> int:
|
|
85
|
+
terms = query.split()
|
|
86
|
+
if not terms:
|
|
87
|
+
return 0
|
|
88
|
+
return len(re.findall(r"\s+".join(re.escape(t) for t in terms), text, re.IGNORECASE))
|