Spaces:
Sleeping
Sleeping
Update app.py
Browse files85 unmodified lines868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714841 unmodified lines19019119219319419519619719819920020120220320420520620720820921021121221321494 unmodified lines30931031131231331431585 unmodified linesreturn "en"def protect_terms(text: str, protected_terms: list) -> tuple[str, dict]:"""Replace protected terms with placeholders using more robust patterns."""modified_text = textreplacements = {}for i, term in enumerate(protected_terms):# Create a unique placeholderplaceholder = f"PROTECTEDTERM{i}PLACEHOLDER"replacements[placeholder] = term# Use multiple patterns to catch the termpatterns = [# Exact match with word boundariesr'\b' + re.escape(term) + r'\b',# Case insensitive matchr'(?i)\b' + re.escape(term) + r'\b',# Match with potential spaces/punctuationre.escape(term).replace(r'\ ', r'\s+'),]for pattern in patterns:if re.search(pattern, modified_text):modified_text = re.sub(pattern, placeholder, modified_text)logger.debug(f"Protected term '{term}' replaced with '{placeholder}'")breakreturn modified_text, replacementsdef restore_terms(text: str, replacements: dict) -> str:"""Restore protected terms in the translated text with fuzzy matching."""restored_text = textfor placeholder, original_term in replacements.items():# Direct replacementif placeholder in restored_text:restored_text = restored_text.replace(placeholder, original_term)logger.debug(f"Restored '{placeholder}' to '{original_term}'")else:# Try to find partial matches or corrupted placeholders# Sometimes translation models might alter the placeholder slightlywords = restored_text.split()for i, word in enumerate(words):# Check if word contains part of our placeholderif "PROTECTEDTERM" in word and "PLACEHOLDER" in word:words[i] = original_termlogger.debug(f"Fuzzy restored corrupted placeholder '{word}' to '{original_term}'")# Also check for common corruptionselif word.upper().replace(".", "").replace(",", "") == placeholder.upper():words[i] = original_termlogger.debug(f"Restored corrupted '{word}' to '{original_term}'")restored_text = " ".join(words)# Clean up any remaining artifacts (dots, extra spaces)restored_text = re.sub(r'\s*\.\s*\.\s*\.\s*\.+', '', restored_text) # Remove multiple dotsrestored_text = re.sub(r'\s+', ' ', restored_text) # Normalize spacesrestored_text = restored_text.strip()return restored_text# FastAPI endpoints41 unmodified lines# Protect terms before translationmodified_text, replacements = protect_terms(text, PROTECTED_TERMS)logger.debug(f"Original text: '{text}'")logger.debug(f"Modified text: '{modified_text}'")logger.debug(f"Replacements: {replacements}")# Perform translation with more conservative settingsresult = translator(modified_text,max_length=512,num_beams=2, # Reduced from 4 to be more conservativedo_sample=False,early_stopping=True,no_repeat_ngram_size=2)translated_text = result[0]["translation_text"]logger.debug(f"Raw translation: '{translated_text}'")# Restore protected termsfinal_text = restore_terms(translated_text, replacements)logger.debug(f"Final text after restoration: '{final_text}'")return TranslationResponse(translated_text=final_text,94 unmodified linesgr.Examples(examples=[["สวัสดีครับ ยินดีที่ได้รู้จัก การพัฒนา 2030 Aspirations เป็นเป้าหมายสำคัญ", "th"],["ฉันเลือกทานอาหารที่ดีต่อสุขภาพร่างกายเพื่อเป็นส่วนหนึ่งในการสนับสนุน 2030 Aspirations", "th"],["こんにちは、はじめまして。Griffith大学での研究が進んで��ます。", "ja"],["你好,很高兴认识你。我们正在为2030 Aspirations制定计划。", "zh"],["Xin chào, rất vui được gặp bạn. Griffith là trường đại học tuyệt vời.", "vi"],85 unmodified lines868788899091929394959697989910010110210310410541 unmodified lines14714814915015115215315415515615715815994 unmodified lines25425525625725825985 unmodified linesreturn "en"def protect_terms(text: str, protected_terms: list) -> tuple[str, dict]:"""Replace protected terms with placeholders."""modified_text = textreplacements = {}for i, term in enumerate(protected_terms):placeholder = f"__PROTECTED_{i}__"replacements[placeholder] = termmodified_text = re.sub(r'\b' + re.escape(term) + r'\b', placeholder, modified_text, flags=re.IGNORECASE)return modified_text, replacementsdef restore_terms(text: str, replacements: dict) -> str:"""Restore protected terms in the translated text."""restored_text = textfor placeholder, term in replacements.items():restored_text = restored_text.replace(placeholder, term)return restored_text# FastAPI endpoints41 unmodified lines# Protect terms before translationmodified_text, replacements = protect_terms(text, PROTECTED_TERMS)# Perform translationresult = translator(modified_text, max_length=512, num_beams=4)translated_text = result[0]["translation_text"]# Restore protected termsfinal_text = restore_terms(translated_text, replacements)return TranslationResponse(translated_text=final_text,94 unmodified linesgr.Examples(examples=[["สวัสดีครับ ยินดีที่ได้รู้จัก การพัฒนา 2030 Aspirations เป็นเป้าหมายสำคัญ", "th"],["こんにちは、はじめまして。Griffith大学での研究が進んで��ます。", "ja"],["你好,很高兴认识你。我们正在为2030 Aspirations制定计划。", "zh"],["Xin chào, rất vui được gặp bạn. Griffith là trường đại học tuyệt vời.", "vi"],
app.py+8-64