llm_engine¶
llm_engine
¶
LLM Engine for translating text using Gemini or custom endpoints.
_resolve_provider_model
¶
Resolves which LLM provider and model to use.
When both are provided, returns them as-is. Otherwise falls back
to SETTING_LLM_LAST_MODEL, then to the first available model.
ソースコード位置: src/core/llm_engine.py
_strip_think_blocks
¶
Removes <think>...</think> blocks (closed and unclosed) from text.
Reasoning models always emit <think> as the model's first generated
token, never embedded in user-facing content, so the over-eager
"strip from <think> to end" sweep is safe in practice — a literal
<think> substring inside a legitimate translation would be
extraordinarily rare and would already break the JSON parser anyway.
A non-empty result that started with an unclosed <think> is logged
at WARNING so the user has a breadcrumb when the response was
truncated mid-reasoning.
ソースコード位置: src/core/llm_engine.py
_resolve_custom_config
¶
Resolves API key, model name, and endpoint for a Custom provider model.
Looks up the custom provider that contains the given model name. Falls back to the first available custom provider if not found.
| 戻り値 | デスクリプション |
|---|---|
tuple[str, str, str]
|
Tuple of (api_key, model, endpoint). All empty if not configured. |
ソースコード位置: src/core/llm_engine.py
_strip_think_tags
¶
Filters out <think>…</think> blocks from a streaming response.
Some models (e.g. Gemma 4, Qwen3 reasoning, DeepSeek-R1) prepend chain-of-thought reasoning wrapped in think tags. This generator buffers until the closing tag is found (or the stream ends) and yields only the non-think content.
If the stream terminates while still inside a <think> block (model
truncated by max_tokens mid-reasoning), the buffered reasoning
is dropped and a WARNING is logged — symmetric with the
non-streaming _strip_think_blocks so the user always gets a
diagnostic pointing at max_tokens instead of silent empty
output.
ソースコード位置: src/core/llm_engine.py
_guess_image_mime
¶
retry_api_call
¶
Decorator to retry LLM API calls with exponential backoff on transient errors.
ソースコード位置: src/core/llm_engine.py
_get_gemini_safety_settings
¶
Returns Gemini safety settings with all categories set to BLOCK_NONE.
| 戻り値 | デスクリプション |
|---|---|
list[dict[str, str]]
|
List of safety setting dicts disabling content filtering so that |
list[dict[str, str]]
|
translation of sensitive source material is not blocked. |
ソースコード位置: src/core/llm_engine.py
_build_gemini_client
¶
Constructs a google.genai.Client for Gemini.
Reads llm/gemini_use_vertex from settings to decide between the
public Gemini Developer API (API-key auth) and Google Cloud Vertex
AI (project + location + ADC, optionally a service-account JSON).
The same SDK call surface (client.models.generate_content) works
for both — only the constructor differs.
Auth resolution order for Vertex AI:
1. Service-account JSON path from llm/vertex_credentials (if set).
2. Application Default Credentials — gcloud auth application-default
login, the GOOGLE_APPLICATION_CREDENTIALS env var, or GCE
metadata when running on Google Cloud.
Raises ValueError("AUTH_ERROR") when neither path is configured.
ソースコード位置: src/core/llm_engine.py
_gemini_safety_settings_for_sdk
¶
Returns safety settings as types.SafetySetting objects.
Same threshold matrix as :func:_get_gemini_safety_settings but
typed for the SDK.
ソースコード位置: src/core/llm_engine.py
_openai_error_body
¶
Returns the response body from an openai SDK exception.
Handles both the typed body attribute (when the server returned
JSON the SDK could parse) and the raw response.text fallback.
Returns "" when neither is available so callers can still log a
default message.
ソースコード位置: src/core/llm_engine.py
_handle_api_error
¶
Unified error handler for all LLM API providers.
Inspects the exception type and raises a ValueError with an
error-tag string (e.g. "AUTH_ERROR", "TIMEOUT_ERROR"), or
re-raises the original exception if no tag applies. Recognises
openai.APIError (Custom path) and
google.genai.errors.APIError (Gemini path).
| 引数 | デスクリプション |
|---|---|
e
|
The caught exception.
タイプ:
|
provider
|
Provider name for logging ("Gemini" or "Custom").
タイプ:
|
context_name
|
Context label ("Standard" or "Vision").
タイプ:
|
| 発生 | デスクリプション |
|---|---|
ValueError
|
With an error-tag string for known HTTP/network errors. |
Exception
|
Re-raises e for unrecognised error types. |
ソースコード位置: src/core/llm_engine.py
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 | |
_format_glossary_hint
¶
Formats glossary entries as a compact hint for vision/image prompts.
ソースコード位置: src/core/llm_engine.py
_classify_custom_endpoint
¶
Inspects endpoint and returns (explicit_api, base_url).
explicit_api is "chat" or "responses" when the user pasted
a URL that already names the API (i.e. ends with
/chat/completions or /responses); None means the user
pasted a base URL like /v1 and we should auto-derive both paths.
base_url is always the URL stripped of the leaf API segment so
callers can append whichever path they need.
When the user is explicit, the dispatcher honours the choice and
skips the chat→responses auto-fallback — pasting /responses
means "this model needs the Responses API, don't probe chat."
ソースコード位置: src/core/llm_engine.py
_format_lang_pair
¶
Formats the language direction clause for LLM prompts.
When source_lang is empty the clause omits it so the LLM auto-detects the source language.
例:
>>> _format_lang_pair("", "French")
'Translate the following into French.'
>>> _format_lang_pair("English (US)", "French")
'Translate the following from English (US) to French.'
ソースコード位置: src/core/llm_engine.py
_format_glossary_block
¶
Formats glossary entries as a structured block for text prompts.
ソースコード位置: src/core/llm_engine.py
_compress_glossary
¶
Filters glossary to only entries relevant to the current batch.
Uses normalized matching (case-insensitive + accent-insensitive) of each glossary entry's source AND target terms against the concatenated batch text. This handles bidirectional translation and diacritical variants — e.g., glossary ("Hello", "Xin chào") matches text containing "xin chao" (no accents).
Inline HTML tags (<b>, <span ...>, <a href="...">, etc.)
are stripped before matching so that formatted text like
"<b>hello</b> world" still matches the glossary term
"hello world".
| 引数 | デスクリプション |
|---|---|
glossary_entries
|
Full glossary (id, source_text, target_text).
タイプ:
|
texts
|
The batch of text strings being translated.
タイプ:
|
| 戻り値 | デスクリプション |
|---|---|
list[tuple[int, str, str]] | None
|
Filtered glossary entries, or None if no matches. |
ソースコード位置: src/core/llm_engine.py
_format_context_block
¶
Formats prior sentences as a reference-only context block.
Used by Live Translation to give the LLM enough surrounding context (~2 sentences) to disambiguate pronouns, topic continuity, tone, and elliptical phrasing in the current sentence. The returned block is appended to the system prompt with explicit "do not translate" instructions so the model doesn't echo the context back in the response.
Returns an empty string when context is empty / None — most batch-translation paths (file translation, etc.) don't carry conversational context.
ソースコード位置: src/core/llm_engine.py
_build_translation_prompt
¶
_build_translation_prompt(
content_type, source_lang, target_lang, glossary_entries=None, context=None
)
Builds a format-specific translation prompt.
Assembles: role + language pair + format rules + glossary + optional conversational context + output format.
| 引数 | デスクリプション |
|---|---|
content_type
|
One of the CONTENT_* constants from llm.py.
タイプ:
|
source_lang
|
Source language name, or empty for auto-detect.
タイプ:
|
target_lang
|
Target language name.
タイプ:
|
glossary_entries
|
Optional glossary (id, source, target).
タイプ:
|
context
|
Optional list of prior source-text sentences to include as reference-only context (no translation). Used by Live Translation for topic / pronoun continuity.
タイプ:
|
| 戻り値 | デスクリプション |
|---|---|
str
|
The complete prompt text.
タイプ:
|
ソースコード位置: src/core/llm_engine.py
_build_image_translation_prompt
¶
Builds the shared prompt for vision-based image translation.
ソースコード位置: src/core/llm_engine.py
_estimate_tokens
¶
Estimates the number of tokens in a string.
Latin/Cyrillic scripts average ~1 token per 4 characters. CJK characters (U+3000+) are typically 1-2 tokens each, so they are counted individually to avoid underestimating batches that could exceed the model's output token limit.
| 引数 | デスクリプション |
|---|---|
text
|
Input text string.
タイプ:
|
| 戻り値 | デスクリプション |
|---|---|
int
|
Estimated token count (minimum 1).
タイプ:
|
ソースコード位置: src/core/llm_engine.py
_split_by_token_budget
¶
Groups texts into sub-batches that fit within a token budget.
Iterates through texts, accumulating items into a sub-batch. When adding the next item would exceed budget, the current sub-batch is flushed and a new one is started. A single item larger than the budget is kept as its own sub-batch (never split).
| 引数 | デスクリプション |
|---|---|
texts
|
List of text strings to group.
タイプ:
|
budget
|
Maximum estimated tokens per sub-batch.
タイプ:
|
| 戻り値 | デスクリプション |
|---|---|
list[list[str]]
|
list[list[str]]: List of sub-batches. |
ソースコード位置: src/core/llm_engine.py
_is_untranslatable
¶
Checks whether a string needs no translation.
Returns True for pure numbers/symbols, URLs, emails, file paths, and empty/whitespace-only strings. Only matches when the entire string is untranslatable — mixed content (e.g. "Price: $100") is sent to the LLM.
| 引数 | デスクリプション |
|---|---|
text
|
Input string to check.
タイプ:
|
| 戻り値 | デスクリプション |
|---|---|
bool
|
True if the text should be returned as-is.
タイプ:
|
ソースコード位置: src/core/llm_engine.py
_deduplicate_texts
¶
Removes duplicate strings, returning unique texts and an index map.
| 引数 | デスクリプション |
|---|---|
texts
|
Input strings (may contain duplicates).
タイプ:
|
| 戻り値 | デスクリプション |
|---|---|
list[str]
|
Tuple of (unique_texts, dupe_map) where dupe_map maps each |
dict[str, list[int]]
|
unique text to the list of original indices it appeared at. |
ソースコード位置: src/core/llm_engine.py
_restore_duplicates
¶
Expands deduplicated results back to the original ordering.
If unique_translated is shorter than unique_texts (e.g. due to mid-way cancellation), only the translated portion is expanded; remaining positions retain their original values.
| 引数 | デスクリプション |
|---|---|
unique_translated
|
Translated unique texts (same order as unique_texts).
タイプ:
|
unique_texts
|
Original unique texts (keys into dupe_map).
タイプ:
|
dupe_map
|
Maps original text → list of original indices.
タイプ:
|
original_texts
|
The pre-dedup input list; used as fallback so untranslated positions keep their original values.
タイプ:
|
| 戻り値 | デスクリプション |
|---|---|
list[str]
|
Full result list with duplicates restored. |
ソースコード位置: src/core/llm_engine.py
translate_text
¶
translate_text(
texts,
target_lang,
source_lang="",
progress_callback=None,
glossary_entries=None,
content_type=CONTENT_PLAIN_TEXT,
cancel_check=None,
*,
provider=None,
model=None,
context=None,
)
Translates text fragments via the configured LLM provider.
Applies two token-saving optimizations before calling the LLM:
- Filtering — strings that are purely numeric, URLs, emails, file paths, or symbols are returned as-is (no API call).
- Deduplication — identical strings are translated once and the result is copied to all positions where the string appeared.
| 引数 | デスクリプション |
|---|---|
texts
|
List of text strings to translate.
タイプ:
|
target_lang
|
Target language name.
タイプ:
|
source_lang
|
Source language name, or empty for auto-detect.
タイプ:
|
progress_callback
|
Called with 0-100 progress percentage.
タイプ:
|
glossary_entries
|
Optional glossary (id, source, target).
タイプ:
|
content_type
|
One of the CONTENT_* constants indicating the format of the text being translated.
タイプ:
|
cancel_check
|
Optional callable that returns True when the task has been cancelled. Checked between sub-batches.
タイプ:
|
provider
|
LLM provider name override (e.g. "Gemini").
タイプ:
|
model
|
LLM model name override (e.g. "gemini-3-flash-preview").
タイプ:
|
context
|
Optional list of prior source-language sentences included in the system prompt as reference-only context. Used by Live Translation for pronoun / topic continuity across consecutive sentences. Not translated; not returned in results.
タイプ:
|
| 戻り値 | デスクリプション |
|---|---|
list[str]
|
list[str]: Translated text strings (always same length as texts). If cancelled mid-way, untranslated items retain their original values. |
ソースコード位置: src/core/llm_engine.py
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 | |
_translate_gemini
¶
_translate_gemini(
texts,
target_lang,
source_lang,
glossary_entries=None,
content_type=CONTENT_PLAIN_TEXT,
model="",
*,
context=None,
)
Translates text using the Gemini API via the google-genai SDK.
Sends the prompt + JSON-shaped input list, asks for a JSON-schema
response, parses the SDK's typed response.text back into the
{id, translated} items the caller's positional list expects.
context (when provided) is woven into the system prompt as reference-only prior sentences — used by Live Translation for pronoun / topic continuity.
ソースコード位置: src/core/llm_engine.py
1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 | |
_custom_cache_key
¶
Canonical key for _CUSTOM_API_CACHE / _CUSTOM_VARIANT_CACHE.
Routes endpoint through _classify_custom_endpoint so cosmetic
variations (trailing slash, whitespace, missing scheme,
/chat/completions vs /responses vs bare base URL) all collapse
to the same key — otherwise a user who toggles the URL between
https://api.example.com/v1 and https://api.example.com/v1/ in
settings would get two independent cache entries and re-pay the
variant probe each time. A genuine endpoint change (different host
or path prefix) still produces a different key, which is exactly the
invalidation we want.
ソースコード位置: src/core/llm_engine.py
_decode_cache_payload
¶
Parses a loaded JSON payload into (api_entries, variant_entries).
Silently drops malformed entries so a corrupted file (or one written by a different schema version) can't poison the in-memory caches. Returns empty dicts when the payload itself is unusable.
ソースコード位置: src/core/llm_engine.py
_persist_caches
¶
Atomically writes both caches to get_llm_endpoint_cache_path().
Concurrency-safe in three dimensions:
- In-process:
_CACHE_LOCKserialises mutators so two threads can't both pass an!=precheck and both write conflicting values. - Cross-process: re-reads the on-disk file and merges its entries underneath ours before writing, so a sibling process (e.g. the GUI persisting at the same time the CLI does) never loses entries on a dump-and-overwrite. Our in-memory entries take precedence on key collision — the local process is the authoritative source for the choices it just observed.
- Filesystem: writes to a unique tmp path
(
mkstempin the cache dir → process+thread+random suffix) so two writers on the same machine never clobber each other's tmp file before the rename. The rename is atomic on POSIX.
Best-effort: any IO / serialisation failure is logged at WARNING
and swallowed — the in-memory caches still work, the next session
just re-pays the probe. Catches OSError (filesystem failures)
and (TypeError, ValueError) (defensive: a corrupted in-memory
dict shouldn't crash a translation request).
ソースコード位置: src/core/llm_engine.py
1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 | |
_load_persistent_caches
¶
Populates the in-memory caches from disk on import.
Best-effort: a missing / malformed / older-schema file leaves both
caches empty (the next call probes from scratch). Any successful
load adds entries via canonical-key reconstruction (in
_decode_cache_payload) so a stale on-disk key with cosmetic
differences still collapses with later in-session writes.
ソースコード位置: src/core/llm_engine.py
_extract_json_object
¶
Parses a JSON object out of an LLM response.
Handles three cases:
1. Pure JSON — direct json.loads.
2. JSON wrapped in a \`\`\`json fence — strip the fence first.
3. JSON embedded in surrounding prose — extract via balanced-brace regex.
Raises json.JSONDecodeError when no parseable object is found.
ソースコード位置: src/core/llm_engine.py
_parse_translation_results
¶
Maps a JSON {"results": [...]} LLM output back to the input list.
Handles \`\`\`json fences via _extract_json_object. Items
missing from the response fall back to their original text.
ソースコード位置: src/core/llm_engine.py
_build_openai_client
¶
Constructs an openai.OpenAI client targeting endpoint.
Strips any /chat/completions or /responses leaf path so the
SDK's base_url is the version-segment root (e.g. /v1); the
SDK appends the right path per call. Sends the API key under both
Authorization: Bearer (the SDK default) and api-key (Azure's
traditional header) so the same client works against OpenAI /
OpenRouter / vLLM AND Azure OpenAI without per-provider
configuration.
ソースコード位置: src/core/llm_engine.py
_reorder_variants_for_cache_hit
¶
Returns variants with the cached-winner variant moved to position 0.
Both _call_custom_chat_with_fallback and _translate_custom_chat
consult _CUSTOM_VARIANT_CACHE to put the previously-successful
variant first; the remaining variants stay in original order so a
stale cache (provider config changed) still falls through cleanly.
Returns the input list unchanged when the cache key isn't present
OR the cached label isn't in this caller's variant list (e.g. a
label written by the 4-variant translation chain that the 3-variant
one-shot helper doesn't know about).
ソースコード位置: src/core/llm_engine.py
_call_custom_chat_with_fallback
¶
Sends a one-shot chat.completions.create with payload fallback.
Same 3-variant chain as :func:_translate_custom_chat minus the
no_system_role step (one-shot callers don't have a system role
that would need merging). Reuses _CUSTOM_VARIANT_CACHE so the
working variant for (endpoint, model) is shared across every
custom-chat callsite — translation, vision extract, embedded-image
translation, and screen translate all converge on the same answer
after the first discovery.
Variants tried (in original order, reordered to put a cached hit first):
temperature+response_format: json_object— the rich payload most providers accept.temperatureonly — dropsresponse_formatfor providers that reject structured-output mode.minimal— dropstemperaturetoo — for o1/o3/gpt-5.x and other reasoning models that only accept the default1.
Returns the assistant's content string. Raises
ValueError("INVALID_REQUEST") when every variant returns 400.
Other exceptions propagate so the caller's _handle_api_error
wrapper maps them to the standard tag set.
ソースコード位置: src/core/llm_engine.py
1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 | |
_stream_custom_chat_with_fallback
¶
Returns a streaming chat.completions.create(stream=True) iterator.
Streaming sibling of :func:_call_custom_chat_with_fallback. The
400 happens at create() time — before any chunks yield — so
we can try payload variants pre-stream. Once a stream object is
returned, the caller iterates it normally; chunks already yielded
can't be rolled back.
Streaming responses are plain text, so the rich variant
(response_format: json_object) is dropped — only two variants
apply:
temperature_only— original payload (what the existing code sends).minimal— dropstemperaturefor o1/o3/gpt-5.x reasoning models.
Reads but does not write to _CUSTOM_VARIANT_CACHE. If the
non-streaming chain already discovered that (endpoint, model)
needs minimal (or no_system_role, which implies the
provider also rejects the rich payload), skip variant 1 and go
straight to minimal. Streaming doesn't write back because the
cache labels reflect non-streaming payload shapes (with
response_format) that don't apply here — round-tripping a
streaming-discovered label would corrupt non-streaming choices.
Other (non-400) errors propagate so the caller's
_handle_api_error wrapper maps them to the standard tag set.
Raises ValueError("INVALID_REQUEST") when every variant 400s.
ソースコード位置: src/core/llm_engine.py
1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 | |
_translate_custom_chat
¶
_translate_custom_chat(
texts,
api_key,
model,
endpoint,
system_prompt,
input_json,
*,
defer_persist=False,
)
Sends a chat/completions request with progressive payload fallback.
Variants tried in order:
1. Rich payload (response_format: json_object + temperature).
2. Without response_format — for providers that don't honour
structured-output mode.
3. Minimal — drops temperature too — for reasoning models like
o1/o3 that only accept the default.
4. Merges the system message into the user role — for deployments
that reject role: system entirely.
Each fallback is logged at WARNING level so pdf_processor's logger
silencing doesn't hide the diagnostic. Raises INVALID_REQUEST
when every variant returns HTTP 400 (a non-400 error short-circuits
via _handle_api_error so quota / auth / connection problems
propagate immediately).
The first successful variant is cached in _CUSTOM_VARIANT_CACHE
keyed on (endpoint, model) so subsequent calls start from it
instead of re-trying the doomed richer variants. A cache miss on
the cached variant (provider config changed) falls through to the
remaining variants in original order; the cache is rewritten on the
next success.
defer_persist skips the disk write after the in-memory variant
cache is updated. The ambiguous-endpoint dispatcher in
_translate_custom sets it so the cold-start case (chat success
→ variant write → return → api-cache write → persist) does ONE
disk write instead of two. The lock is still acquired for the
in-memory mutation; only the _persist_caches() call is
deferred.
ソースコード位置: src/core/llm_engine.py
1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 | |
_translate_custom_responses
¶
Sends a Responses-API request to the same Custom endpoint.
Required for Azure GPT-5.x reasoning deployments and any other
model where capabilities.chat_completion is False. Body shape
differs from chat/completions: the system prompt goes in the
instructions field and the user message in input. Uses
the SDK's client.responses.create and reads output_text,
falling back to walking output[*] if the SDK didn't synthesise
the convenience field (older / preview shapes).
ソースコード位置: src/core/llm_engine.py
_translate_custom
¶
_translate_custom(
texts,
target_lang,
source_lang,
glossary_entries=None,
content_type=CONTENT_PLAIN_TEXT,
model="",
*,
context=None,
)
Translates text via an OpenAI-compatible custom endpoint.
Dispatches to chat/completions first; if that returns
INVALID_REQUEST after exhausting payload fallbacks, retries on
the responses endpoint (required by Azure GPT-5.x reasoning
models and any model whose capabilities.chat_completion is
False). The successful API choice is cached in
_CUSTOM_API_CACHE per (endpoint, model) so subsequent calls
skip the doomed chat attempt entirely.
context (when provided) is woven into the system prompt as reference-only prior sentences — used by Live Translation for pronoun / topic continuity.
ソースコード位置: src/core/llm_engine.py
2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 | |
_build_streaming_prompt
¶
Builds a plain-text translation prompt for streaming (no JSON).
context (when provided) is a list of prior source-language sentences included as reference-only context for pronoun / topic continuity. Used by Live Translation streaming.
ソースコード位置: src/core/llm_engine.py
stream_translate_text
¶
stream_translate_text(
text,
target_lang,
source_lang="",
glossary_entries=None,
*,
provider=None,
model=None,
context=None,
)
Streams translated text chunks from the configured LLM provider.
context (when provided) is a list of prior source-language sentences fed to the LLM as reference-only context for pronoun / topic continuity (used by Live Translation streaming).
| 返す | デスクリプション |
|---|---|
str
|
Partial text chunks as they arrive from the API.
タイプ::
|
ソースコード位置: src/core/llm_engine.py
_stream_gemini
¶
Streams translation from Gemini via the google-genai SDK iterator.
The SDK's generate_content_stream returns chunks with a
.text accessor that already filters out thought parts and
handles SSE framing internally.
ソースコード位置: src/core/llm_engine.py
_stream_custom
¶
Streams translation from an OpenAI-compatible endpoint via the SDK.
Uses client.chat.completions.create(stream=True) and yields
delta.content strings. The SDK iterator handles SSE framing,
keep-alives and the [DONE] sentinel internally.
ソースコード位置: src/core/llm_engine.py
translate_image_content
¶
translate_image_content(
image_path,
ocr_results,
target_lang,
source_lang="",
progress_callback=None,
glossary_entries=None,
*,
provider=None,
model=None,
)
Translates image content by dispatching to the configured LLM provider.
Note: progress_callback is accepted for API compatibility but is not yet forwarded to the downstream provider functions.
ソースコード位置: src/core/llm_engine.py
_translate_image_gemini
¶
_translate_image_gemini(
image_path,
fragments,
target_lang,
source_lang,
glossary_entries=None,
model="",
)
Translates OCR text fragments on an image via the google-genai SDK.
| 引数 | デスクリプション |
|---|---|
image_path
|
Path to the source image file.
タイプ:
|
fragments
|
OCR fragment dicts, each with at least an
タイプ:
|
target_lang
|
Target language name (e.g. "Vietnamese").
タイプ:
|
source_lang
|
Source language name (e.g. "English").
タイプ:
|
glossary_entries
|
Optional glossary for terminology enforcement.
タイプ:
|
model
|
Gemini model name.
タイプ:
|
| 戻り値 | デスクリプション |
|---|---|
list[dict[str, Any]]
|
List of paragraph dicts with |
list[dict[str, Any]]
|
|
ソースコード位置: src/core/llm_engine.py
2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 | |
_translate_image_custom
¶
_translate_image_custom(
image_path,
fragments,
target_lang,
source_lang,
glossary_entries=None,
model="",
)
Translates image content using an OpenAI-compatible vision API.
| 引数 | デスクリプション |
|---|---|
image_path
|
Path to the source image file.
タイプ:
|
fragments
|
OCR fragment dicts, each with at least a
タイプ:
|
target_lang
|
Target language name (e.g. "Vietnamese").
タイプ:
|
source_lang
|
Source language name (e.g. "English").
タイプ:
|
glossary_entries
|
Optional glossary for terminology enforcement.
タイプ:
|
model
|
Custom model name.
タイプ:
|
| 戻り値 | デスクリプション |
|---|---|
list[dict[str, Any]]
|
List of paragraph dicts with |
list[dict[str, Any]]
|
|
ソースコード位置: src/core/llm_engine.py
2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 | |
_extract_text_gemini
¶
Extracts text from an image using the Gemini Vision API.
ソースコード位置: src/core/llm_engine.py
_extract_text_custom
¶
Extracts text from an image using an OpenAI-compatible vision API.
ソースコード位置: src/core/llm_engine.py
extract_image_text
¶
Extracts text from an image using the configured LLM vision provider.
| 引数 | デスクリプション |
|---|---|
image_path
|
Path to the image file.
タイプ:
|
provider
|
LLM provider name override.
タイプ:
|
model
|
LLM model name override.
タイプ:
|
| 戻り値 | デスクリプション |
|---|---|
str
|
Extracted text as a string. |
ソースコード位置: src/core/llm_engine.py
translate_batch
¶
translate_batch(
values,
target_lang,
src_lang,
progress_callback=None,
glossary_entries=None,
cancel_check=None,
checkpoint_dir=None,
content_type=CONTENT_DATA_VALUES,
*,
provider=None,
model=None,
context=None,
)
Translates a flat list of strings in batches.
Applies file-level deduplication before batching so identical strings are translated only once — ensuring consistent translations regardless of which batch a duplicate falls into.
Processes unique values in groups of TRANSLATION_BATCH_SIZE. On
resume, previously-translated batches are loaded from the checkpoint
and skipped. If checkpoint_dir is None, no caching is
performed and every batch is sent to the LLM.
| 引数 | デスクリプション |
|---|---|
values
|
Strings to translate.
タイプ:
|
target_lang
|
Target language name.
タイプ:
|
src_lang
|
Source language name, or empty for auto-detect.
タイプ:
|
progress_callback
|
Called with 0-100 percentage after each batch.
タイプ:
|
glossary_entries
|
Optional glossary for the LLM.
タイプ:
|
cancel_check
|
Returns
タイプ:
|
checkpoint_dir
|
Directory for saving/loading batch checkpoints.
タイプ:
|
content_type
|
LLM content type hint (default
タイプ:
|
provider
|
LLM provider name override.
タイプ:
|
model
|
LLM model name override.
タイプ:
|
context
|
Optional list of prior source-language sentences fed to the LLM as reference-only context (Live Translation uses this for pronoun / topic continuity).
タイプ:
|
| 戻り値 | デスクリプション |
|---|---|
list[str] | None
|
Translated strings, or |
ソースコード位置: src/core/llm_engine.py
2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 | |