Spaces:
Sleeping
Sleeping
File size: 4,809 Bytes
50ea367 39aa8c6 50ea367 a53aff2 39aa8c6 a53aff2 50ea367 39aa8c6 99a65f3 39aa8c6 3476719 39aa8c6 a936231 39aa8c6 50ea367 a53aff2 150948a a53aff2 150948a 39aa8c6 50ea367 a53aff2 39aa8c6 150948a 101fa34 150948a 101fa34 150948a 101fa34 150948a 39aa8c6 50ea367 39aa8c6 150948a 39aa8c6 a53aff2 39aa8c6 3476719 101fa34 39aa8c6 101fa34 39aa8c6 3476719 39aa8c6 101fa34 39aa8c6 101fa34 39aa8c6 150948a 3476719 150948a 39aa8c6 50ea367 3476719 50ea367 39aa8c6 101fa34 39aa8c6 50ea367 150948a 39aa8c6 50ea367 39aa8c6 150948a 39aa8c6 50ea367 3476719 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 | 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()
|