Spaces:
Running on Zero
Running on Zero
abinjoyal commited on
Commit ·
ddea29d
1
Parent(s): 5b7bd7e
fix: translation rate limiter, exponential backoff, and HF fallback
Browse filesFiles changed (2)
- services/translation_service.py+135-25
- test_123_groups_benchmark.pyAdded+119
113 unmodified lines1141151161171181191201211 unmodified line1231241251261271281 unmodified line13013113213313413513613713813914014114214314414514614714814915015117 unmodified lines1691701711721731741751761771781791801811821831841855 unmodified lines191192193194195196197108 unmodified lines3063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563 unmodified lines360361362363364365366367368369370371372113 unmodified linesreturn is_validreturn Truedef translate_with_mymemory(text: str, target_lang: str = "ta", max_retries: int = 2) -> Optional[str]:"""Queries MyMemory Translated API with timeout, retry policy, and strict Tamil validation."""if not text or not text.strip():return None1 unmodified linesrc = "en-GB"for attempt in range(max_retries):try:translator = MyMemoryTranslator(source=src, target=tgt)res = translator.translate(text.strip())1 unmodified lineis_valid, reason = is_meaningful_tamil(res, text)if is_valid:cleaned = sanitize_translation_text(res)logger.info(f"MyMemory translated successfully (attempt {attempt+1}): '{cleaned[:50]}...'")return cleanedelse:logger.warning(f"MyMemory attempt {attempt+1} rejected ({reason}): '{res[:40]}...'")except Exception as e:logger.warning(f"MyMemory attempt {attempt+1} notice: {e}")if "too many requests" in str(e).lower():time.sleep(1.2 * (attempt + 1))if attempt < max_retries - 1:time.sleep(0.5)return Nonedef hf_serverless_translate(text: str, src_lang: str = "en", target_lang: str = "ta") -> Optional[str]:"""Queries Hugging Face Serverless Inference API for instant NLLB translation without GPU queue locks."""if not text or not text.strip():return Nonetoken = os.environ.get("HF_TOKEN", "")17 unmodified linesfor url in endpoints:try:resp = requests.post(url, headers=headers, json=payload, timeout=4)if resp.status_code == 200:result = resp.json()if isinstance(result, list) and len(result) > 0 and "translation_text" in result[0]:translated = result[0]["translation_text"].strip()is_valid, _ = is_meaningful_tamil(translated, text)if is_valid:logger.info(f"HF Serverless NLLB Translated [{src_lang} -> {target_lang}]: {translated[:50]}")return sanitize_translation_text(translated)except Exception:continuereturn None5 unmodified linesif not is_valid:logger.warning(f"Translation validation failed ({reason}) for: '{original[:40]}...'. Output was: '{trans_str[:40]}...'")# Attempt one controlled MyMemory fallbackmm_res = translate_with_mymemory(original, target_lang=target_lang)if mm_res:return mm_res# Return empty string instead of speaking English or gibberish108 unmodified lineselse:uncached_indices.append(i)# 3. Ultra-Fast Parallel Translation: Process uncached sentences using ThreadPoolExecutor(max_workers=3)# Uses max_workers=3 to respect API rate limits (5 req/sec) while keeping total duration under 4-5 seconds.if uncached_indices:logger.info(f"⚡ Ultra-Fast Parallel Translation (max_workers=3) for {len(uncached_indices)} sentence groups...")t_start = time.time()def process_index(i: int) -> tuple:orig = merged_texts[i]# Step A: MyMemory (unblocked, ~0.3s per sentence, proven 100% accurate Tamil)res = translate_with_mymemory(orig, target_lang=target_lang)if not res:# Step B: HF Serverless NLLB fallback (1-2s response)res = hf_serverless_translate(orig, target_lang=target_lang)return i, reswith concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:future_to_idx = {executor.submit(process_index, idx): idx for idx in uncached_indices}for future in concurrent.futures.as_completed(future_to_idx):try:i, trans_res = future.result()if trans_res and contains_target_script(trans_res, target_lang):cleaned_t = sanitize_translation_text(trans_res)raw_translations[i] = cleaned_tself._cache[f"{target_lang}:{merged_texts[i].strip().lower()}"] = cleaned_telse:raw_translations[i] = ""except Exception as exc:idx_fail = future_to_idx[future]logger.warning(f"Translation worker failed for group {idx_fail}: {exc}")raw_translations[idx_fail] = ""logger.info(f"Ultra-Fast Parallel translation completed in {time.time() - t_start:.2f}s")# 5. Format translated segments and validate Tamil scripttranslated_segments = []valid_tamil_count = 0for grp, orig_full, raw_trans in zip(sentence_groups, merged_texts, raw_translations):final_trans = clean_translation_result(raw_trans, orig_full, target_lang=target_lang)is_valid_tamil = contains_target_script(final_trans, target_lang)if is_valid_tamil:valid_tamil_count += 1else:logger.warning(f"Segment validation: No Tamil text available for '{orig_full[:50]}...'. Keeping empty to prevent English audio.")final_trans = ""grp_start = grp[0]["start"]3 unmodified lines"start": grp_start,"end": grp_end,"original_text": orig_full,"translated_text": final_trans})total_elapsed = time.time() - start_timelogger.info(f"Translation step completed in {total_elapsed:.2f}s. "f"Total groups: {len(translated_segments)}, Valid Tamil: {valid_tamil_count}/{len(translated_segments)}")return translated_segments113 unmodified lines1141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611 unmodified line1631641651661671681691701711721 unmodified line17417517617717817918018118218318418518618718818919019119219319419519619719819920020120217 unmodified lines2202212222232242252262272282292302312322332342352362372382392402412422432442455 unmodified lines251252253254255256257108 unmodified lines3663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524533 unmodified lines457458459460461462463464465466467468469470471472473474475476477478479480481482113 unmodified linesreturn is_validreturn Trueimport threading# Thread-safe shared rate limiter for external translation APIsclass SharedRateLimiter:def __init__(self, min_interval_seconds: float = 0.28):self.min_interval = min_interval_secondsself.last_call = 0.0self.lock = threading.Lock()self.consecutive_rate_limits = 0self.circuit_open_until = 0.0def acquire(self) -> bool:"""Throttles calls to stay strictly under the provider's rate limits."""with self.lock:now = time.time()if now < self.circuit_open_until:# Provider is temporarily degraded / in cooldownreturn Falseelapsed = now - self.last_callif elapsed < self.min_interval:time.sleep(self.min_interval - elapsed)self.last_call = time.time()return Truedef record_success(self):with self.lock:self.consecutive_rate_limits = 0def record_rate_limit(self, cooldown_seconds: float = 4.0):with self.lock:self.consecutive_rate_limits += 1if self.consecutive_rate_limits >= 3:self.circuit_open_until = time.time() + cooldown_secondslogger.warning(f"⚠️ MyMemory rate-limit circuit tripped ({self.consecutive_rate_limits} limits). "f"Pausing MyMemory requests for {cooldown_seconds:.1f}s to allow quota reset.")_mymemory_limiter = SharedRateLimiter(min_interval_seconds=0.28)def translate_with_mymemory(text: str, target_lang: str = "ta", max_retries: int = 3) -> Optional[str]:"""Queries MyMemory Translated API with thread-safe rate limiter, bounded exponential backoff, and strict validation."""if not text or not text.strip():return None1 unmodified linesrc = "en-GB"for attempt in range(max_retries):if not _mymemory_limiter.acquire():# Circuit breaker is active: skip immediately to fallback without wasting timereturn Nonetry:translator = MyMemoryTranslator(source=src, target=tgt)res = translator.translate(text.strip())1 unmodified lineis_valid, reason = is_meaningful_tamil(res, text)if is_valid:cleaned = sanitize_translation_text(res)_mymemory_limiter.record_success()logger.info(f"MyMemory translated successfully (attempt {attempt+1}): '{cleaned[:50]}...'")return cleanedelse:logger.warning(f"MyMemory attempt {attempt+1} rejected ({reason}): '{res[:40]}...'")except Exception as e:err_msg = str(e).lower()if "too many requests" in err_msg or "429" in err_msg or "quota" in err_msg:logger.warning(f"MyMemory attempt {attempt+1} rate limit detected: {e}")_mymemory_limiter.record_rate_limit(cooldown_seconds=4.0)# Bounded exponential backoff: 0.4s, 0.8s, 1.6stime.sleep(0.4 * (2 ** attempt))else:logger.warning(f"MyMemory attempt {attempt+1} notice: {e}")time.sleep(0.2)if attempt < max_retries - 1:time.sleep(0.2)return Nonedef hf_serverless_translate(text: str, src_lang: str = "en", target_lang: str = "ta") -> Optional[str]:"""Queries Hugging Face Serverless Inference API for NLLB translation with connection verification and strict validation."""if not text or not text.strip():return Nonetoken = os.environ.get("HF_TOKEN", "")17 unmodified linesfor url in endpoints:try:resp = requests.post(url, headers=headers, json=payload, timeout=6)if resp.status_code == 200:result = resp.json()if isinstance(result, list) and len(result) > 0 and "translation_text" in result[0]:translated = result[0]["translation_text"].strip()is_valid, reason = is_meaningful_tamil(translated, text)if is_valid:logger.info(f"HF Serverless NLLB Translated [{src_lang} -> {target_lang}]: {translated[:50]}")return sanitize_translation_text(translated)else:logger.warning(f"HF Serverless translation rejected ({reason}): '{translated[:40]}...'")elif resp.status_code == 503:logger.info("HF Serverless model loading (503), proceeding to next fallback.")elif resp.status_code in (401, 403):logger.warning(f"HF Serverless authentication failed ({resp.status_code}).")breakexcept requests.exceptions.Timeout:logger.warning("HF Serverless request timed out.")except Exception as hf_err:logger.warning(f"HF Serverless notice: {hf_err}")return None5 unmodified linesif not is_valid:logger.warning(f"Translation validation failed ({reason}) for: '{original[:40]}...'. Output was: '{trans_str[:40]}...'")# Attempt one controlled MyMemory fallbackmm_res = translate_with_mymemory(original, target_lang=target_lang, max_retries=1)if mm_res:return mm_res# Return empty string instead of speaking English or gibberish108 unmodified lineselse:uncached_indices.append(i)provider_stats = {"mymemory": 0, "hf_serverless": 0, "local_nmt": 0, "failed": 0}provider_timing = {"mymemory": 0.0, "hf_serverless": 0.0, "local_nmt": 0.0}# 3. Ultra-Fast Parallel Translation: Process uncached sentences using ThreadPoolExecutor(max_workers=3)# Uses max_workers=3 along with _mymemory_limiter to respect API rate limits (5 req/sec).if uncached_indices:logger.info(f"⚡ Ultra-Fast Parallel Translation (max_workers=3) for {len(uncached_indices)} sentence groups...")t_start = time.time()def process_index(i: int) -> tuple:orig = merged_texts[i]provider_used = Noneres = None# Step A: MyMemory with shared rate limiting and circuit breakert_mm = time.time()res = translate_with_mymemory(orig, target_lang=target_lang)dur_mm = time.time() - t_mmif res and contains_target_script(res, target_lang):provider_used = "mymemory"return i, res, provider_used, dur_mm# Step B: HF Serverless NLLB fallback (if MyMemory rate limited or failed)t_hf = time.time()res = hf_serverless_translate(orig, target_lang=target_lang)dur_hf = time.time() - t_hfif res and contains_target_script(res, target_lang):provider_used = "hf_serverless"return i, res, provider_used, dur_hf# Step C: Local NMT Direct if availableif local_nmt_service and hasattr(local_nmt_service, "translate_text_direct"):t_loc = time.time()try:res = local_nmt_service.translate_text_direct(orig, target_lang=target_lang)dur_loc = time.time() - t_locif res and contains_target_script(res, target_lang):provider_used = "local_nmt"return i, res, provider_used, dur_locexcept Exception:passreturn i, "", "failed", 0.0with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:future_to_idx = {executor.submit(process_index, idx): idx for idx in uncached_indices}for future in concurrent.futures.as_completed(future_to_idx):try:i, trans_res, provider, dur = future.result()provider_stats[provider] = provider_stats.get(provider, 0) + 1if provider in provider_timing:provider_timing[provider] += durif trans_res and contains_target_script(trans_res, target_lang):cleaned_t = sanitize_translation_text(trans_res)raw_translations[i] = cleaned_tself._cache[f"{target_lang}:{merged_texts[i].strip().lower()}"] = cleaned_telse:raw_translations[i] = ""logger.warning(f"⚠️ Sentence group {i} failed all translation providers: '{merged_texts[i][:60]}...'")except Exception as exc:idx_fail = future_to_idx[future]logger.warning(f"Translation worker exception for group {idx_fail}: {exc}")raw_translations[idx_fail] = ""provider_stats["failed"] = provider_stats.get("failed", 0) + 1logger.info(f"Ultra-Fast Parallel translation completed in {time.time() - t_start:.2f}s")# 5. Format translated segments and validate Tamil scripttranslated_segments = []valid_tamil_count = 0failed_indices = []for grp_idx, (grp, orig_full, raw_trans) in enumerate(zip(sentence_groups, merged_texts, raw_translations)):final_trans = clean_translation_result(raw_trans, orig_full, target_lang=target_lang)is_valid_tamil = contains_target_script(final_trans, target_lang)if is_valid_tamil:valid_tamil_count += 1else:failed_indices.append(grp_idx)logger.warning(f"❌ Translation failed for Group {grp_idx}: No Tamil text available for '{orig_full[:50]}...'. Dialogue marked missing.")final_trans = ""grp_start = grp[0]["start"]3 unmodified lines"start": grp_start,"end": grp_end,"original_text": orig_full,"translated_text": final_trans,"translation_status": "success" if is_valid_tamil else "failed"})total_elapsed = time.time() - start_timetotal_groups = len(translated_segments)failed_count = len(failed_indices)success_pct = (valid_tamil_count / total_groups * 100) if total_groups > 0 else 0.0logger.info(f"\n"f"================ TRANSLATION REPORT ================\n"f"Total sentence groups: {total_groups}\n"f"Successful translations: {valid_tamil_count} ({success_pct:.1f}%)\n"f"Failed translations: {failed_count}\n"f"Dialogue missing: {'YES - ' + str(failed_count) + ' groups missing!' if failed_count > 0 else 'NO - 100% complete'}\n"f"Provider breakdown: {provider_stats}\n"f"Provider timing: { {k: round(v, 2) for k, v in provider_timing.items()} } (seconds)\n"f"Total translation time: {total_elapsed:.2f}s\n"f"====================================================")return translated_segments
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119import sysimport osimport time
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from services.translation_service import ( translation_service, is_meaningful_tamil, sanitize_translation_text, contains_target_script)
# 123 realistic sentence groups representing dialogue from a 15-minute anime/action video# (similar to the 4_Part_1.mp4 video from user logs)SENTENCE_SAMPLES = [ "Look closely at the guardian beast, you won't see something like this every day.", "A massive land tortoise, the beast is the size of a small island.", "Its size made it clearly visible as it moved across the wilderness.", "When the monster stopped moving forward, the defenders began to panic.", "Someone leaped from the shell down to the ground.", "This was classified as a B-rank magical beast with immense power.", "After subduing the beast, they modified the shell into a mobile fortress.", "Both the old man and the warrior managed to defend the perimeter.", "He asked why this was happening, seeking an explanation.", "They must obey the command authority without question.", "The monument they are protecting was attacked by ten elite warriors.", "Because they failed to protect the relic, the penalty was enacted.", "This penalty permanently reduces all attributes by fifty percent.", "The protagonist simply watches, noting the danger of the situation.", "He opens his inventory to combine his defensive items.", "The combination was successful, granting plus one to all core stats.", "The divine retribution herald will appear in thirty minutes.", "Thirty minutes is all we have before the secret quest initiates.", "Running away from this dungeon boss will not be an easy task.", "The divine herald raised his golden scepter to unleash a massive area attack.", "He announced that the divine restriction field has now been activated.", "To make matters worse, dodging these light arrows is virtually impossible.", "The spellcasters were disarmed throughout the entire battle zone.", "The players inside the field began shouting in extreme desperation.", "There is no way to save him as the boss spreads his radiant aura.", "He leaps with all his might, holding his twin blades firmly.", "The strike hit dead on, striking one of the boss's glowing eyes.", "Due to the death seal, the boss now only has sixty percent stamina left.", "He keeps running at full speed, looking for another opening.", "He lands another full blow on the herald's remaining wing.", "The darkness begins to swallow the radiant light of the holy scepter.", "Taking advantage of this opening, he charges forward with full momentum.", "With a final decisive strike, the herald's head was severed completely.", "He leveled up three times and earned the rare title Challenger of Divinity.", "This title reduces incoming damage from all holy beings by thirty-five percent.", "He was also rewarded with four thousand gold coins and a rare equipment chest.", "A global server notification arrived announcing the dungeon clear.", "The players were stunned that a solo fighter managed to defeat such a boss.", "Olivia looked up in disbelief, wondering how anyone could solo this raid.", "She asked if she could quickly interview him regarding his secret technique.", "He replied that he simply did what was necessary to survive.", "The rewards were distributed according to the total kill contribution.", "In first place was the Black Reaper with over three thousand monster eliminations.", "Everyone cheered as the battlefield finally returned to peaceful silence."]
# Generate exactly 123 simulated Whisper transcribed segmentssimulated_segments = []current_time = 0.0
for i in range(123): sentence = SENTENCE_SAMPLES[i % len(SENTENCE_SAMPLES)] duration = 5.0 + (i % 3) simulated_segments.append({ "start": round(current_time, 2), "end": round(current_time + duration, 2), "text": sentence }) current_time += duration + 0.5
print("=" * 70)print(f"BENCHMARK TEST: 15-MINUTE VIDEO SIMULATION (123 GROUPS)")print(f"Total simulated video duration: {current_time / 60:.2f} minutes")print(f"Total segments / sentence groups: {len(simulated_segments)}")print("=" * 70)
t_start = time.time()translated_segments = translation_service.translate_segments(simulated_segments, target_lang="ta")t_end = time.time()
# Audit and verify resultstotal_count = len(translated_segments)successful = [s for s in translated_segments if contains_target_script(s.get("translated_text", ""), "ta")]failed = [s for s in translated_segments if not contains_target_script(s.get("translated_text", ""), "ta")]
print("\n" + "=" * 70)print("BENCHMARK AUDIT & VALIDATION RESULTS")print("=" * 70)print(f"Total Groups Processed: {total_count}")print(f"Successful Translations: {len(successful)} ({(len(successful)/total_count)*100:.1f}%)")print(f"Failed Translations: {len(failed)} ({(len(failed)/total_count)*100:.1f}%)")print(f"Total Processing Time: {t_end - t_start:.2f} seconds")print(f"Average Time Per Group: {(t_end - t_start)/total_count:.3f} seconds")print(f"Dialogue Missing: {'YES - WARNING!' if len(failed) > 0 else 'NO - ALL DIALOGUE INTACT'}")
# Verify Tamil script on all successfulall_valid = Truefor idx, s in enumerate(successful[:5]): is_valid, reason = is_meaningful_tamil(s["translated_text"], s["original_text"]) print(f"\n[Sample {idx+1}]") print(f" EN: {s['original_text']}") print(f" TA: {s['translated_text']}") print(f" Valid: {is_valid} ({reason})") if not is_valid: all_valid = False
print("\n" + "=" * 70)if len(successful) >= (total_count * 0.95) and all_valid: print(">>> 123-GROUP TRANSLATION BENCHMARK PASSED SUCCESSFULLY! <<<")else: print(">>> BENCHMARK FINISHED WITH ISSUES <<<")print("=" * 70)
services/translation_service.py+135-25
test_123_groups_benchmark.pyAdded+119