Repository navigation
Translate API cost optimization (batch, cache, debounce) - #5384
Conversation
…batch API calls - Replace paid Google Cloud detect_language with free langdetect library - Add multi-level cache: in-memory LRU -> Redis (14-day TTL) -> Google API - Batch uncached sentences into single API call (up to MAX_BATCH_SIZE=100) - Fix sentence splitting to not split on commas - Use detected_language_code from translate response (free) Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Return False for inconclusive detection (was True) - Add update_from_translate_response for free detected_lang from API - Normalize locale tags in comparison Co-Authored-By: Claude Opus 4.6 <[email protected]>
…rotection - First appearance: translate immediately - Growing segments: debounce with version counter - Final segments (terminal punctuation): translate immediately - Flush pending translations on disconnect - Fix mixed-language segment skip bug Co-Authored-By: Claude Opus 4.6 <[email protected]>
Covers: sentence splitting, language detection, batch API, Redis cache, return types, language cache, TTL, error fallback, dominant language, mixed-language batches, batch chunking, segment finality, debounce state machine, version safety, same-text skip, flush pending. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Greptile SummaryThis PR rewrites the backend translation pipeline to reduce Google Cloud Translation API costs by an estimated 84–89% through four complementary mechanisms: replacing the paid Key findings:
Confidence Score: 3/5
Important Files Changed
Flowchart%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[Incoming TranscriptSegment] --> B{translation_language set?}
B -- No --> Z[Skip]
B -- Yes --> C{is_in_target_language?\nlangdetect pre-filter}
C -- Yes\n target lang --> Z
C -- No / inconclusive --> D{Same text_hash\nalready pending?}
D -- Yes --> Z
D -- No --> E[Increment version counter\nCancel old debounce task]
E --> F{First appearance\nOR segment_is_final?}
F -- Yes\nimmediate --> G[asyncio.ensure_future\n_translate_segment immediately]
F -- No\ngrowing segment --> H[asyncio.ensure_future\nsleep 1s then _translate_segment]
G --> I[_translate_segment]
H --> I
I --> J{Pre-API stale check:\nversion match?}
J -- Stale --> Z
J -- Current --> K[translate_text_by_sentence]
K --> L{Memory cache hit?}
L -- Hit --> N
L -- Miss --> M{Redis cache hit?}
M -- Hit --> N
M -- Miss --> O[Batch Google Translate API\nup to 100 sentences]
O --> N[Assemble translated text\njoin with space]
N --> P{Post-API stale check:\nversion match?}
P -- Stale --> Z
P -- Current --> Q[Update language_cache\nfrom detected_lang]
Q --> R[Persist to Firestore\nwith translation_persist_lock]
R --> S[WebSocket notify\nTranslationEvent]
S --> T[Prune pending_translations entry]
subgraph Shutdown
U[flush_pending_translations\ntranslation_flushing=True] --> V[Await each pending task\ntimeout 5s each]
V --> W[pending_translations.clear\ntranslation_flushing=False]
W --> X[websocket_active=False]
end
Last reviewed commit: 9af9e41 |
| for j, translation in enumerate(response.translations): | ||
| idx = chunk_indices[j] | ||
| translated_text = translation.translated_text | ||
| detected_lang = translation.detected_language_code or "" | ||
| results[idx] = translated_text | ||
| detected_langs.append(detected_lang) | ||
|
|
||
| # Cache in memory and Redis | ||
| text_hash = hashlib.md5(sentences[idx].encode()).hexdigest() | ||
| self._set_memory_cache(text_hash, dest_language, translated_text, detected_lang) | ||
| cache_translation(text_hash, dest_language, translated_text, detected_lang) | ||
|
|
||
| except Exception as e: | ||
| logger.error(f"Batch translation error: {e}") | ||
| for idx in chunk_indices: | ||
| if results[idx] is None: | ||
| results[idx] = sentences[idx] | ||
|
|
||
| # Determine dominant detected language | ||
| dominant_lang = "" | ||
| if detected_langs: | ||
| lang_counts = Counter(lang for lang in detected_langs if lang) | ||
| if lang_counts: | ||
| dominant_lang = lang_counts.most_common(1)[0][0] | ||
|
|
||
| translated_text = ' '.join(r for r in results if r is not None) |
There was a problem hiding this comment.
Silent sentence drops on batch response count mismatch
The loop for j, translation in enumerate(response.translations) assumes the API always returns exactly as many items as the batch. If response.translations has fewer items than chunk (e.g. due to content filtering or a partial API failure), the leftover results[idx] entries remain None. These are then silently dropped in the final join:
translated_text = ' '.join(r for r in results if r is not None)This causes data loss without logging or fallback to the original text. The existing error-fallback block only triggers on thrown exceptions, not on count mismatches.
A defensive fix would add a bounds check and fall back to the original sentence for any unmatched indices:
for j, translation in enumerate(response.translations):
idx = chunk_indices[j]
translated_text = translation.translated_text
detected_lang = translation.detected_language_code or ""
results[idx] = translated_text
detected_langs.append(detected_lang)
text_hash = hashlib.md5(sentences[idx].encode()).hexdigest()
self._set_memory_cache(text_hash, dest_language, translated_text, detected_lang)
cache_translation(text_hash, dest_language, translated_text, detected_lang)
# Fallback to original for any unmatched indices
for idx in chunk_indices[len(response.translations):]:
if results[idx] is None:
results[idx] = sentences[idx]| translated_text = ' '.join(r for r in results if r is not None) | ||
| return (translated_text, dominant_lang) |
There was a problem hiding this comment.
Space separator breaks CJK target language output
' '.join(...) always inserts a Latin space between translated sentences. For target languages that don't use spaces between sentences — Chinese (zh), Japanese (ja), Thai (th) — this produces incorrect output such as "こんにちは。 元気ですか。" (note the erroneous space).
The old code called translate_text once per segment (no reassembly), so this is a regression introduced by the sentence-batching approach.
Consider joining without a separator for space-free script languages:
CJK_LANGS = {'zh', 'ja', 'th', 'km', 'lo', 'my'}
separator = '' if dest_language.split('-')[0] in CJK_LANGS else ' '
translated_text = separator.join(r for r in results if r is not None)| def _detect_with_langdetect(text: str, hint_language: str = None) -> str | None: | ||
| if hint_language not in LANGDETECT_RELIABLE_LANGUAGES: | ||
| # Normalize locale-tagged language (e.g. "en-US" -> "en") for langdetect compatibility | ||
| base_hint = hint_language.split('-')[0] if hint_language else None | ||
| if base_hint not in LANGDETECT_RELIABLE_LANGUAGES: | ||
| return None | ||
| try: | ||
| return langdetect_detect(text) | ||
| except LangDetectException: | ||
| return None |
There was a problem hiding this comment.
_detect_with_langdetect silently returns None for all languages not in the reliable list (including Chinese)
When base_hint is not in LANGDETECT_RELIABLE_LANGUAGES (e.g., zh for Chinese, zh-TW, mn, hy, etc.), the function returns None immediately without calling langdetect_detect. This means:
detect_languagenever caches theseNoneresults, so every call for a Chinese-target user re-invokes this check on every segment update — a missed optimisation.is_in_target_languagealways returnsFalsefor these users, soupdate_from_translate_responsecorrectly populates the cache asTrueafter the first API call, but on the nextis_in_target_languagecall theTruefast-path is absent (onlyFalseshort-circuits), detection runs again, returnsNone, and the function returnsFalseagain. The cachedTruevalue is effectively never used for non-empty text.
As a result, Chinese/Mongolian/Armenian users receive zero benefit from the language-cache pre-filter: every segment is forwarded to the API regardless of whether it was previously confirmed to be in the target language. The stated "43% cost reduction" may not apply to these languages.
This doesn't break correctness, but it's worth documenting or fixing the fast-path for was_in_target_language is True in TranscriptSegmentLanguageCache.is_in_target_language.
| async def flush_pending_translations(): | ||
| """Flush all pending debounced translations before cleanup.""" | ||
| nonlocal translation_flushing | ||
| translation_flushing = True | ||
| for seg_id, pending in list(pending_translations.items()): | ||
| task = pending.get('task') | ||
| if task and not task.done(): | ||
| try: | ||
| await asyncio.wait_for(task, timeout=5.0) | ||
| except (asyncio.TimeoutError, asyncio.CancelledError): | ||
| pass | ||
| pending_translations.clear() | ||
| translation_flushing = False |
There was a problem hiding this comment.
flush_pending_translations awaits tasks sequentially — consider asyncio.gather
The flush loop awaits each pending task one at a time:
for seg_id, pending in list(pending_translations.items()):
...
await asyncio.wait_for(task, timeout=5.0)In asyncio this is cooperative, so the 1-second debounce sleeps do overlap across tasks. However, the API call portions still execute one after another because _translate_segment acquires translation_persist_lock. With N debounced segments, the total flush time approaches 1s (sleep) + N × (API_latency + DB_write), which can exceed the 5-second per-task budget when a session ends with many in-flight segments.
Using asyncio.gather with a shared timeout would allow the debounce sleeps and API calls to overlap fully:
tasks = [p['task'] for p in pending_translations.values() if p.get('task') and not p['task'].done()]
if tasks:
try:
await asyncio.wait_for(asyncio.gather(*tasks, return_exceptions=True), timeout=5.0)
except (asyncio.TimeoutError, asyncio.CancelledError):
pass| def is_in_target_language(self, segment_id: str, text: str, target_language: str) -> bool: | ||
| # If we already determined it's not the target language, it remains so. | ||
| was_in_target_language = self.cache.get(segment_id, None) | ||
| if was_in_target_language is False: | ||
| return False | ||
|
|
||
| # If no new text to analyze, rely on the previous state. | ||
| # True or None results in True | ||
| if not text: | ||
| return was_in_target_language is not False | ||
|
|
||
| # Use full text detection for better accuracy and performance | ||
| # Use free local langdetect only (no paid API calls) | ||
| # target_language should already be base-normalized (e.g. "en" not "en-US") | ||
| detected_lang = detect_language(text, remove_non_lexical=True, hint_language=target_language) | ||
| if detected_lang and detected_lang != target_language: | ||
| self.cache[segment_id] = False | ||
| return False | ||
|
|
||
| # All text is in the target language or undetectable. | ||
| self.cache[segment_id] = True | ||
| return True | ||
| if detected_lang and detected_lang == target_language: | ||
| self.cache[segment_id] = True | ||
| return True | ||
|
|
||
| # Detection inconclusive (None) — don't assume target language, let translate API decide | ||
| # Don't cache unknown state; segment will be sent to translate API which detects for free | ||
| return False |
There was a problem hiding this comment.
Missing fast-path for True cache entries in is_in_target_language
The False state correctly short-circuits at the top, but True does not:
was_in_target_language = self.cache.get(segment_id, None)
if was_in_target_language is False:
return False
# ... continues to re-run detection even when was_in_target_language is TrueFor a growing segment (same segment_id, new text appended), once the API confirms via update_from_translate_response that a segment is in the target language, was_in_target_language is True, yet the method still calls detect_language every time. If detection is inconclusive (e.g., for Chinese), it always returns False, negating the cached True value entirely.
Adding a short-circuit for confirmed target-language segments would make the behaviour symmetric with the False case and prevent unnecessary langdetect calls:
if was_in_target_language is True:
return TrueThis is safe because update_from_translate_response only writes True when the API has already confirmed the segment language.
Track debounce skips, cache hits, lang_cache skips, API calls, and log summary on session disconnect for live validation. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Log memory cache hits, Redis cache hits, and batch API call counts for observability during live testing. Co-Authored-By: Claude Opus 4.6 <[email protected]>
E2E Translation Test ResultsTest 1: 15-min Podcast Simulation (100 segments, mocked API)
Test 2: Live Google Translate API (10 segments, English → Vietnamese)
Sample translations:
Test 3: Unit Tests66/66 passing — sentence splitting, language detection, batch API, Redis cache, debounce state machine, version safety, mixed-language batches, batch chunking, error fallback. What's Validated
DeployPR branch deployed to dev GKE ( by AI for @beastoin |
E2E Translation Test Results (v3 - Full Stack, Real Google Translate API)Test Setup
Optimization Breakdown
Cache Effectiveness
*5 replay calls from Redis TTL edge cases; in production with 14-day TTL this would be 0. Translation Quality (English → Vietnamese)
Unit Tests
How the optimizations stack |
|
lgtm |
Prod Deployment Verification — PR #5384Status: ✅ Verified on prod Deployment
Translation Optimization — Live Prod EvidenceInstrumentation working:
Sentence cache active:
Error check:
by AI for @beastoin |
Prod Metrics — Early Signal (T+1h)Google Cloud Translation API call reduction: ~87% (same-hour comparison, first full post-deploy hour vs previous day)
If the reduction holds through peak, daily API call volume would drop to ~12% of pre-optimization levels. by AI for @beastoin |
Product Lead — Live Device VerificationProduct lead tested the translation feature on a physical device post-deploy. Screenshot shows:
This confirms the optimized translation pipeline (sentence cache + debounce) is working correctly in production on real user devices. by AI for @beastoin |
Product Lead — Live Device VerificationProduct lead tested translation on a physical device post-deploy:
Confirms the optimized translation pipeline is working correctly in production on real devices. by AI for @beastoin |
Independent Prod Verification — @kenji (physical device + Omi)Status: PASS Test setup: Pixel 7a + Omi device, Japanese NHK news played through speaker Results:
Confirms the optimized translation pipeline (sentence cache + debounce) is fully functional in production with real Omi hardware. by AI for @beastoin |
Independent Prod Verification — Full Report with Screenshots (@kenji)Test Setup
Results — PASSTranslation Quality:
Auto Language Detection: Japanese detected automatically, "translated by omi" badges on all segments Dual-Language Transcript:
Stability: No crashes, no lag, no missing translations. Device connected at 80%+ battery throughout. Summary Quality: Auto-generated summaries coherent and accurate — correctly extracted incident details, suspect response, NHK apology, next steps. VerdictPR #5384 translate API optimization verified end-to-end on physical Omi hardware. Japanese→English pipeline (auto-detect → translate → display) working correctly in production. by AI for @beastoin |



Summary
Closes #4651 (sub-issues #4712, #4713, #4714)
langdetectlibrary + freedetected_language_codefrom translate response.?!and newlinesEstimated total cost reduction: 84-89%
Files changed
backend/utils/translation.py— core translation service rewritebackend/utils/translation_cache.py— simplified language cachebackend/routers/transcribe.py— debounce logic in streaming handlerbackend/tests/unit/test_translation_optimization.py— 66 testsbackend/test.sh— test registrationTest plan
by AI for @beastoin