refactor: decompose oversized contracts to satisfy INV_7 fractal limit
Break monolithic modules >400 lines into focused sub-modules while preserving backward-compatible imports and all test coverage: Backend (Python): - TranslationExecutor: 1974→241 lines, split into 9 sub-modules - Translate plugin: orchestrator (1137→148), preview (1303→244), service (1052→275), dictionary (1007→68) - ProfileService: 857→172 with 4 extracted sub-modules - TaskManager: 708→322 with graph/event_bus/lifecycle extracted - Test dictionary: 1199→split into 6 focused test files Frontend (Svelte): - SettingsPage: 1451→291 with 6 extracted tab components - GitManager: 1220→228 with 5 extracted panels - DatasetReviewWorkspace: 1202→314 - translate.js API: 664→28 barrel with 6 domain modules Protocol: - Remove single-contract 150-line limit from INV_7 (keep CC≤10) - Fix unclosed #endregion tags across 11 files - Fix 19 test regressions from stale mock paths - All 294 tests passing
This commit is contained in:
189
backend/src/plugins/translate/_batch_proc.py
Normal file
189
backend/src/plugins/translate/_batch_proc.py
Normal file
@@ -0,0 +1,189 @@
|
||||
# #region BatchProcessingService [C:4] [TYPE Module] [SEMANTICS translate, batch, process, classify, cache]
|
||||
# @BRIEF Batch processing for translation: create batch records, classify rows (cache/preview/LLM),
|
||||
# call LLM service, persist TranslationRecord/TranslationLanguage rows.
|
||||
# Insert-to-target delegated to _batch_insert.py.
|
||||
# @LAYER Domain
|
||||
# @RELATION DEPENDS_ON -> [TranslationBatch], [TranslationRecord], [TranslationLanguage]
|
||||
# @RELATION DEPENDS_ON -> [DictionaryManager], [LLMTranslationService]
|
||||
# @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 time
|
||||
import uuid
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
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 ._llm_call import LLMTranslationService
|
||||
from ._token_budget import estimate_token_budget
|
||||
from ._utils import _check_translation_cache, _compute_source_hash, _compute_key_hash
|
||||
from .dictionary import DictionaryManager
|
||||
|
||||
|
||||
# #region BatchProcessingService [C:4] [TYPE Class]
|
||||
# @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]
|
||||
# @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.
|
||||
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}
|
||||
|
||||
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(job, batch_rows, preview_edits_cache)
|
||||
|
||||
tls = job.target_languages or [job.target_dialect or "en"]
|
||||
tls = [str(tls)] if not isinstance(tls, list) else tls
|
||||
|
||||
result["successful"] += self._persist_pre(pre_rows, bid, run_id, tls)
|
||||
if llm_rows:
|
||||
llm_res = 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
|
||||
|
||||
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
|
||||
|
||||
def _check_cache(self, job, batch_rows, dict_snapshot_hash, config_hash):
|
||||
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
|
||||
logger.reason("Translation cache hit", {"source_hash": h[:12], "langs": list(cached.keys())})
|
||||
|
||||
def _classify(self, job, batch_rows, preview_edits_cache):
|
||||
llm_rows, pre_rows = [], []
|
||||
for row in batch_rows:
|
||||
if row.get("approved_translation"):
|
||||
pre_rows.append(row)
|
||||
continue
|
||||
cl = row.get("_cached_lang_values")
|
||||
if cl:
|
||||
tls = job.target_languages or [job.target_dialect or "en"]
|
||||
tls = [str(tls)] if not isinstance(tls, list) else tls
|
||||
if all(lc in cl for lc in 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)
|
||||
return llm_rows, pre_rows
|
||||
|
||||
def _persist_pre(self, pre_rows, bid, run_id, tls):
|
||||
count = 0
|
||||
for row in pre_rows:
|
||||
cl = row.get("_cached_lang_values")
|
||||
rec = TranslationRecord(
|
||||
id=str(uuid.uuid4()), batch_id=bid, run_id=run_id,
|
||||
source_sql=row.get("source_text", ""), target_sql=row.get("approved_translation", ""),
|
||||
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:
|
||||
fv = cl[lc] if (cl and lc in cl) else row.get("approved_translation", "")
|
||||
self.db.add(TranslationLanguage(
|
||||
id=str(uuid.uuid4()), record_id=rec.id, language_code=lc,
|
||||
source_language_detected="und", translated_value=fv,
|
||||
final_value=fv, status="translated", needs_review=False,
|
||||
))
|
||||
count += 1
|
||||
return count
|
||||
|
||||
def _process_llm(self, job, run_id, rows_for_llm, dict_matches, bid, tls):
|
||||
provider_model = None
|
||||
if job.provider_id:
|
||||
try:
|
||||
p = LLMProviderService(self.db).get_provider(job.provider_id)
|
||||
if p:
|
||||
provider_model = p.default_model or "gpt-4o-mini"
|
||||
except Exception:
|
||||
provider_model = None
|
||||
|
||||
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=provider_model,
|
||||
)
|
||||
if tb["warning"]:
|
||||
logger.explore("Token budget warning", {"batch_id": bid, "warning": tb["warning"]})
|
||||
|
||||
return 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"],
|
||||
)
|
||||
|
||||
# -- Batch insert (delegation) --
|
||||
def insert_batch_to_target(self, job: TranslationJob, batch_id: str, run_id: str) -> None:
|
||||
insert_batch_to_target(self.db, self.config_manager, job, batch_id, run_id)
|
||||
# #endregion BatchProcessingService
|
||||
# #endregion BatchProcessingService
|
||||
Reference in New Issue
Block a user