import gradio as gr import torch import whisper from transformers import AutoTokenizer, AutoModelForSeq2SeqLM # 1. Initialization and Model Loading (Optimized for Hugging Face Free CPU tier) print("Initializing Hugging Face Space environment...") device = "cpu" print("Loading Whisper STT Model...") whisper_model = whisper.load_model("small", device=device) model_path = "Akariieieie/DialectGo-NLLB" print(f"Loading custom NLLB model from {model_path}...") tokenizer = AutoTokenizer.from_pretrained(model_path) model = AutoModelForSeq2SeqLM.from_pretrained(model_path).to(device) LANG_CODES = { "English": "eng_Latn", "Tagalog": "tgl_Latn", "Cebuano": "ceb_Latn" } # Whisper language ISO mapping to enforce clean audio extraction accuracy WHISPER_LANG_MAPPING = { "English": "en", "Tagalog": "tl", "Cebuano": "tl" } # 2. Unified Processing Function def universal_translator(text, audio_path, source_lang_name, target_lang_name): working_text = text # If an audio file payload is sent (via UI or API), transcribe it first if audio_path is not None: print(f"Audio file detected. Transcribing via Whisper ({source_lang_name})...") whisper_lang = WHISPER_LANG_MAPPING.get(source_lang_name, None) # Guide Whisper with the selected language code for better accuracy if whisper_lang: whisper_result = whisper_model.transcribe(audio_path, language=whisper_lang) else: whisper_result = whisper_model.transcribe(audio_path) working_text = whisper_result["text"].strip() print(f"Transcription result: {working_text}") if not working_text or not working_text.strip(): return "No text or audio input provided.", "No text or audio input provided." # Map friendly names to NLLB language codes src_code = LANG_CODES.get(source_lang_name, "eng_Latn") tgt_code = LANG_CODES.get(target_lang_name, "tgl_Latn") print(f"Translating from {source_lang_name} ({src_code}) → {target_lang_name} ({tgt_code})") # Set source language context tokenizer.src_lang = src_code inputs = tokenizer(working_text, return_tensors="pt").to(device) # FIX: Use lang_code_to_id instead of convert_tokens_to_ids. # convert_tokens_to_ids returns 0 (UNK) if the language code is not found as a # regular vocab token, causing the model to hallucinate in its dominant language (Cebuano). # lang_code_to_id correctly resolves NLLB language codes. if hasattr(tokenizer, 'lang_code_to_id') and tgt_code in tokenizer.lang_code_to_id: forced_bos_token_id = tokenizer.lang_code_to_id[tgt_code] else: # Fallback: try convert_tokens_to_ids and warn if it returns UNK (0) forced_bos_token_id = tokenizer.convert_tokens_to_ids(tgt_code) if forced_bos_token_id == tokenizer.unk_token_id or forced_bos_token_id == 0: print(f"WARNING: Could not resolve token ID for '{tgt_code}'. Translation may be incorrect.") print(f"Resolved forced_bos_token_id for {tgt_code}: {forced_bos_token_id}") with torch.no_grad(): output_tokens = model.generate( **inputs, forced_bos_token_id=forced_bos_token_id, max_new_tokens=256, temperature=0.1 ) translation = tokenizer.batch_decode(output_tokens, skip_special_tokens=True)[0].strip() print(f"Translation result: {translation}") # Return both the transcription text and translation text return working_text, translation # 3. Gradio Interface Layout with gr.Blocks(theme=gr.themes.Base()) as demo: gr.Markdown("# 🇵🇭 DialectGo Unified Translation System") gr.Markdown("This space functions as both a web UI and an active API endpoint for multi-way voice/text translation.") with gr.Row(): with gr.Column(): audio_in = gr.Audio(label="Audio Input (File or Mic)", type="filepath") text_in = gr.Textbox(label="Text Input (Ignored if Audio is provided)", lines=3) src_lang = gr.Dropdown(choices=["English", "Tagalog", "Cebuano"], value="English", label="From") tgt_lang = gr.Dropdown(choices=["English", "Tagalog", "Cebuano"], value="Tagalog", label="To") submit_btn = gr.Button("Process Translation", variant="primary") with gr.Column(): transcription_out = gr.Textbox(label="Transcribed/Source Text", lines=3, interactive=False) output_text = gr.Textbox(label="Translation Result", lines=4, interactive=False) submit_btn.click( fn=universal_translator, inputs=[text_in, audio_in, src_lang, tgt_lang], outputs=[transcription_out, output_text], api_name="translate" ) demo.launch()