Translation pipeline fixes (from production error log analysis): Lang detect: - Add "ru" to _COMMON_SOURCE_CODES for Cyrillic source detection - Version detector cache keys (v2:) and include detector version in source hash — stale cache entries from old algorithm are invalidated - Integrate _character_block_fallback into batch_detect() pipeline; only assign Cyrillic fallback when exactly one Cyrillic target exists (multiple ru/uk/be targets stay undetermined for LLM arbitration) Batch processing: - Case-insensitive cache language matching (cached_by_lang lookup) - Propagate needs_review=True for undetected language rows in pre/cache path LLM call (critical — fixes silent error hiding): - Validate LLM row IDs against expected set; log unknown identifiers - Retry only missing rows on incomplete response (bounded by recursion depth) - Exhausted retries → FAILED (new _handle_incomplete_response method) - Parse failures → FAILED instead of SKIPPED (_handle_parse_failure) - NULL/Empty translations → FAILED via new _add_failed helper - Source-language identity mapping preserved as TranslationLanguage entry (carries source_language_detected metadata that _build_insert_rows relies on for detected_src_lang derivation) - finish_reason propagated to parser for truncation diagnostics LLM parse: - Structured incomplete-set logging with expected/received/missing counts Target schema validation: - Handle all non-success SQL Lab statuses (failed, timeout, error, stopped) - Timeout gets explicit message prefix - Route returns HTTP 502 with correct HTTPException passthrough Scheduler persistence fix (production pickle error): - Backup and validation APScheduler jobs now use module-level callbacks (execute_scheduled_backup, execute_scheduled_validation) instead of bound SchedulerService methods — prevents pickle failure from serializing TaskManager + dynamically loaded plugin classes - Callback func identity verified via pickle round-trip smoke test Tests: - Update assertions: FAILED replaces SKIPPED for LLM error paths - Restore source-language contract tests with identity-mapped values - Add scheduler callback identity and args verification tests - Update detector cache key tests for versioned format - Update target schema error route test: 200→502 Orthogonal code review: MEDIUM finding (empty rec.languages when all targets match detected source → _build_insert_rows fallback to "und") fixed by preserving source-language TranslationLanguage entries.
319 lines
16 KiB
Python
319 lines
16 KiB
Python
# #region BatchProcessingService [C:4] [TYPE Module] [SEMANTICS translate, batch, process, classify, cache]
|
|
# @defgroup Translate Module group.
|
|
# @BRIEF Batch processing for translation: classify rows (same-language/cache/preview/LLM),
|
|
# call LLM service, persist TranslationRecord/TranslationLanguage rows.
|
|
# Local language detection (lingua) replaces LLM-based detection.
|
|
# @LAYER Domain
|
|
# @RELATION DEPENDS_ON -> [TranslationBatch], [TranslationRecord], [TranslationLanguage]
|
|
# @RELATION DEPENDS_ON -> [DictionaryManager], [LLMTranslationService], [LanguageDetectService]
|
|
# @RELATION DEPENDS_ON -> [estimate_token_budget], [ConfigManager]
|
|
# @PRE DB session is available. Job configuration is valid.
|
|
# @POST TranslationBatch, TranslationRecord, TranslationLanguage rows created and committed.
|
|
# @SIDE_EFFECT LLM API calls via LLMTranslationService; DB writes.
|
|
# @RATIONALE Extracted from TranslationExecutor. Batch insert delegated to _batch_insert.py.
|
|
# @REJECTED Keeping batch processing inside TranslationExecutor — caused class to exceed INV_7.
|
|
|
|
import asyncio
|
|
from datetime import UTC, datetime
|
|
import time
|
|
from typing import Any
|
|
import uuid
|
|
|
|
from sqlalchemy.orm import Session
|
|
|
|
from ...core.config_manager import ConfigManager
|
|
from ...core.logger import belief_scope, logger
|
|
from ...models.translate import TranslationBatch, TranslationJob, TranslationLanguage, TranslationRecord
|
|
from ...services.llm_provider import LLMProviderService
|
|
from ._batch_insert import insert_batch_to_target
|
|
from ._lang_detect import batch_detect
|
|
from ._llm_call import LLMTranslationService
|
|
from ._token_budget import estimate_token_budget
|
|
from ._utils import _check_translation_cache, _compute_key_hash, _compute_source_hash
|
|
from .dictionary import DictionaryManager
|
|
|
|
|
|
# #region BatchProcessingService [C:4] [TYPE Class]
|
|
# @defgroup Translate Module group.
|
|
# @BRIEF Create batch records, classify rows, process LLM calls, persist results.
|
|
class BatchProcessingService:
|
|
"""Process a batch: classify (cache/preview/LLM), persist, and insert to target."""
|
|
|
|
def __init__(self, db: Session, config_manager: ConfigManager) -> None:
|
|
self.db = db
|
|
self.config_manager = config_manager
|
|
self._llm_service = LLMTranslationService(db)
|
|
|
|
# #region process_batch [C:3] [TYPE Function]
|
|
# @ingroup Translate
|
|
# @BRIEF Process a single batch: create record, classify rows, call LLM, persist.
|
|
# @PRE job and batch_rows are valid.
|
|
# @POST TranslationBatch and TranslationRecord rows are created.
|
|
# @SIDE_EFFECT LLM API call; DB writes.
|
|
async def process_batch(
|
|
self, job: TranslationJob, run_id: str, batch_index: int,
|
|
batch_rows: list[dict[str, Any]],
|
|
dict_snapshot_hash: str | None = None, config_hash: str | None = None,
|
|
preview_edits_cache: dict[str, dict[str, str]] | None = None,
|
|
) -> dict[str, int]:
|
|
"""Process a single batch: classify rows, call LLM (if needed), persist records."""
|
|
with belief_scope("BatchProcessingService.process_batch"):
|
|
batch_start = time.monotonic()
|
|
batch = self._create_batch(run_id, batch_index, batch_rows)
|
|
bid = batch.id
|
|
result = {"successful": 0, "failed": 0, "skipped": 0, "retries": 0}
|
|
|
|
tls = job.target_languages or [job.target_dialect or "en"]
|
|
tls = [str(tls)] if not isinstance(tls, list) else tls
|
|
|
|
# ★ Run local language detection on all rows (heuristic, no LLM)
|
|
await self._detect_languages(batch_rows, tls)
|
|
|
|
source_texts = [r.get("source_text", "") for r in batch_rows if r.get("source_text")]
|
|
rc = batch_rows[0].get("source_data") if batch_rows else None
|
|
dict_matches = DictionaryManager.filter_for_batch(self.db, source_texts, job.id, row_context=rc)
|
|
|
|
self._check_cache(job, batch_rows, dict_snapshot_hash, config_hash)
|
|
llm_rows, pre_rows = self._classify(batch_rows, preview_edits_cache, tls)
|
|
|
|
result["successful"] += self._persist_pre(pre_rows, bid, run_id, tls)
|
|
# Count cache hits: pre_rows that have _cached_lang_values (served from cache, not same-lang/approved)
|
|
result["cache_hits"] = sum(1 for r in pre_rows if r.get("_cached_lang_values"))
|
|
if llm_rows:
|
|
llm_res = await self._process_llm(job, run_id, llm_rows, dict_matches, bid, tls)
|
|
for k in ("successful", "failed", "skipped", "retries"):
|
|
result[k] += llm_res.get(k, 0)
|
|
|
|
batch.successful_records = result["successful"]
|
|
batch.failed_records = result["failed"]
|
|
batch.completed_at = datetime.now(UTC)
|
|
batch.status = "COMPLETED" if result["failed"] == 0 else "COMPLETED_WITH_ERRORS"
|
|
self.db.flush()
|
|
|
|
latency = int((time.monotonic() - batch_start) * 1000)
|
|
logger.reason(f"Batch {batch_index} complete", {"batch_id": bid, "latency_ms": latency, **result})
|
|
return {**result, "batch_id": bid}
|
|
# #endregion process_batch
|
|
|
|
# #region _create_batch [C:2] [TYPE Function] [SEMANTICS translate,batch,create]
|
|
# @ingroup Translate
|
|
# @BRIEF Create a TranslationBatch DB record and flush to get its ID.
|
|
def _create_batch(self, run_id, batch_index, batch_rows):
|
|
b = TranslationBatch(id=str(uuid.uuid4()), run_id=run_id, batch_index=batch_index,
|
|
status="RUNNING", total_records=len(batch_rows), started_at=datetime.now(UTC))
|
|
self.db.add(b)
|
|
self.db.flush()
|
|
return b
|
|
# #endregion _create_batch
|
|
|
|
# #region _check_cache [C:3] [TYPE Function] [SEMANTICS translate,cache,hash,lookup]
|
|
# @ingroup Translate
|
|
# @BRIEF Check translation cache for each batch row, attach _cached_lang_values.
|
|
# @POST Rows with cache hits have _cached_lang_values dict set.
|
|
# @SIDE_EFFECT Modifies batch_rows in-place. Emits aggregated log.
|
|
def _check_cache(self, job, batch_rows, dict_snapshot_hash, config_hash):
|
|
cache_hits = 0
|
|
for row in batch_rows:
|
|
if row.get("approved_translation"):
|
|
continue
|
|
st = row.get("source_text", "")
|
|
if not st:
|
|
continue
|
|
ctx = list(job.context_columns or [])
|
|
h = _compute_source_hash(st, row.get("source_data"), dict_snapshot_hash, config_hash, ctx)
|
|
row["_source_hash"] = h
|
|
cached = _check_translation_cache(self.db, h)
|
|
if cached:
|
|
row["_cached_lang_values"] = cached
|
|
cache_hits += 1
|
|
if cache_hits > 0:
|
|
logger.reason(
|
|
"Translation cache hits",
|
|
{"batch_rows": len(batch_rows), "cache_hits": cache_hits},
|
|
)
|
|
# #endregion _check_cache
|
|
|
|
# #region _detect_languages [C:2] [TYPE Function] [SEMANTICS translate,language,detect,lingua]
|
|
# @ingroup Translate
|
|
# @BRIEF Run local language detection on all batch rows (no LLM).
|
|
async def _detect_languages(self, batch_rows: list[dict], target_languages: list[str]) -> None:
|
|
"""Run local language detection on all batch rows (no LLM).
|
|
|
|
Attaches '_detected_lang' (BCP-47 code or 'und') to each row dict.
|
|
Uses batch_detect() for efficient multi-text processing, offloaded
|
|
to a thread to avoid blocking the event loop.
|
|
"""
|
|
texts = [row.get("source_text", "") for row in batch_rows]
|
|
results = await asyncio.to_thread(batch_detect, texts, target_languages)
|
|
for row, lang in zip(batch_rows, results):
|
|
row["_detected_lang"] = lang
|
|
# #endregion _detect_languages
|
|
|
|
# #region _classify [C:4] [TYPE Function] [SEMANTICS translate,classify,cache,same-lang]
|
|
# @ingroup Translate
|
|
# @BRIEF Classify batch rows into pre_rows (no LLM needed) and llm_rows.
|
|
# @POST Returns (llm_rows, pre_rows). Cached rows go to pre_rows only when
|
|
# all non-source target languages are present in cache.
|
|
# @RATIONALE Non-source tls filtering: tls may include the source language
|
|
# (e.g. ["ru","en","fr","zh"]) but cache only has translations
|
|
# (en/fr/zh). We exclude detected source language from the
|
|
# cache-completeness check via non_source_tls.
|
|
def _classify(self, batch_rows, preview_edits_cache, tls):
|
|
llm_rows, pre_rows = [], []
|
|
tls_lower = [str(t).lower() for t in tls]
|
|
for row in batch_rows:
|
|
# ★ Same-language pre-filter: only short-circuit when ALL targets
|
|
# match the detected language. If only SOME match, still process
|
|
# other targets via cache or LLM.
|
|
dl = row.get("_detected_lang")
|
|
if dl and str(dl).lower() not in ("und", "") and str(dl).lower() in tls_lower:
|
|
non_matching = [t for t in tls if str(t).lower() != str(dl).lower()]
|
|
if not non_matching:
|
|
# All targets are the same as detected language — no translation needed
|
|
row["_same_language"] = True
|
|
pre_rows.append(row)
|
|
continue
|
|
# Partial match: mark same-language for later use, but don't skip
|
|
row["_same_language"] = True
|
|
|
|
if row.get("approved_translation"):
|
|
pre_rows.append(row)
|
|
continue
|
|
cl = row.get("_cached_lang_values")
|
|
if cl:
|
|
# Exclude source language from cache-completeness check:
|
|
# tls may include the source language (e.g. ["ru","en","fr","zh"])
|
|
# but cache only contains translations (en/fr/zh), not the source.
|
|
dl = row.get("_detected_lang") or ""
|
|
non_source_tls = [lc for lc in tls if str(lc).lower() != str(dl).lower()]
|
|
if non_source_tls and all(lc in cl for lc in non_source_tls):
|
|
pre_rows.append(row)
|
|
continue
|
|
if preview_edits_cache:
|
|
sd = row.get("source_data") or {}
|
|
if sd:
|
|
kh = _compute_key_hash(sd)
|
|
pe = preview_edits_cache.get(kh)
|
|
if pe:
|
|
fe = next(iter(pe.values()), None)
|
|
if fe:
|
|
row["approved_translation"] = fe
|
|
pre_rows.append(row)
|
|
continue
|
|
llm_rows.append(row)
|
|
logger.reason("Batch classified",
|
|
{"tls": tls, "pre": len(pre_rows), "llm": len(llm_rows),
|
|
"total": len(pre_rows) + len(llm_rows)})
|
|
return llm_rows, pre_rows
|
|
# #endregion _classify
|
|
|
|
# #region _persist_pre [C:3] [TYPE Function] [SEMANTICS translate,persist,record,language]
|
|
# @ingroup Translate
|
|
# @BRIEF Persist pre-classified rows as TranslationRecord + TranslationLanguage.
|
|
def _persist_pre(self, pre_rows, bid, run_id, tls):
|
|
count = 0
|
|
for row in pre_rows:
|
|
cl = row.get("_cached_lang_values")
|
|
detected_lang = row.get("_detected_lang", "und") or "und"
|
|
source_text = row.get("source_text", "")
|
|
is_same = row.get("_same_language")
|
|
needs_review = str(detected_lang).lower() == "und"
|
|
|
|
# target_sql: prefer approved_translation, then first cached value, then source
|
|
primary_cached = next(iter(cl.values()), "") if cl else ""
|
|
target_sql = row.get("approved_translation") or primary_cached or source_text
|
|
|
|
rec = TranslationRecord(
|
|
id=str(uuid.uuid4()), batch_id=bid, run_id=run_id,
|
|
source_sql=source_text, target_sql=target_sql,
|
|
source_object_type="table_row", source_object_id=row.get("row_index"),
|
|
source_object_name=row.get("source_object_name", ""),
|
|
source_data=row.get("source_data"), source_hash=row.get("_source_hash"),
|
|
status="SUCCESS",
|
|
)
|
|
self.db.add(rec)
|
|
for lc in tls:
|
|
if is_same and str(lc).lower() == str(detected_lang).lower():
|
|
# Same language: use source text as-is (no translation needed)
|
|
fv = source_text
|
|
elif cl:
|
|
cached_by_lang = {
|
|
str(code).lower(): value for code, value in cl.items()
|
|
}
|
|
cached_value = cached_by_lang.get(str(lc).lower())
|
|
if cached_value is None:
|
|
# No translation available — skip this language.
|
|
continue
|
|
fv = cached_value
|
|
else:
|
|
# No translation available — skip this language
|
|
continue
|
|
self.db.add(TranslationLanguage(
|
|
id=str(uuid.uuid4()), record_id=rec.id, language_code=lc,
|
|
source_language_detected=detected_lang, translated_value=fv,
|
|
final_value=fv, status="translated", needs_review=needs_review,
|
|
))
|
|
count += 1
|
|
return count
|
|
# #endregion _persist_pre
|
|
|
|
# #region _process_llm [C:4] [TYPE Function] [SEMANTICS translate,llm,call,batch]
|
|
# @ingroup Translate
|
|
# @BRIEF Process LLM translation for a batch: estimate budget, call LLM, return results.
|
|
async def _process_llm(self, job, run_id, rows_for_llm, dict_matches, bid, tls):
|
|
# Resolve provider token config (DB values take priority over PROVIDER_DEFAULTS)
|
|
token_config = {"model": None, "context_window": None, "max_output_tokens": None}
|
|
if job.provider_id:
|
|
try:
|
|
token_config = LLMProviderService(self.db).get_provider_token_config(job.provider_id)
|
|
except Exception:
|
|
pass
|
|
|
|
tb = estimate_token_budget(
|
|
source_rows=rows_for_llm, target_languages=tls,
|
|
source_column="source_text", context_columns=None,
|
|
dictionary_entries=dict_matches, batch_size=len(rows_for_llm),
|
|
provider_info=token_config["model"],
|
|
context_window=token_config["context_window"],
|
|
max_output_tokens=token_config["max_output_tokens"],
|
|
)
|
|
if tb["warning"]:
|
|
logger.explore("Token budget warning", {"batch_id": bid, "warning": tb["warning"]})
|
|
|
|
max_rows_by_out = tb.get("max_rows_by_output", 0)
|
|
|
|
logger.reason(
|
|
f"LLM process batch start", {
|
|
"batch_id": bid, "llm_rows": len(rows_for_llm),
|
|
"provider_model": token_config["model"],
|
|
"max_output_needed": tb.get("max_output_needed"),
|
|
"estimated_input_tokens": tb.get("estimated_input_tokens"),
|
|
"max_rows_by_output": max_rows_by_out,
|
|
"context_window": token_config["context_window"],
|
|
"max_output_tokens": token_config["max_output_tokens"],
|
|
},
|
|
)
|
|
|
|
result = await self._llm_service.call_llm_for_batch(
|
|
job=job, run_id=run_id, batch_rows=rows_for_llm,
|
|
dict_matches=dict_matches, batch_id=bid,
|
|
max_tokens=tb["max_output_needed"],
|
|
)
|
|
|
|
logger.reason(
|
|
f"LLM process batch complete", {
|
|
"batch_id": bid, **result,
|
|
},
|
|
)
|
|
return result
|
|
# #endregion _process_llm
|
|
|
|
# #region insert_batch_to_target [C:4] [TYPE Function] [SEMANTICS translate,batch,insert,target]
|
|
# @ingroup Translate
|
|
# @BRIEF Insert batch records into the target table via SQL Lab or direct DB.
|
|
async def insert_batch_to_target(self, job: TranslationJob, batch_id: str, run_id: str) -> None:
|
|
await insert_batch_to_target(self.db, self.config_manager, job, batch_id, run_id)
|
|
# #endregion insert_batch_to_target
|
|
# #endregion BatchProcessingService
|
|
# #endregion BatchProcessingService
|