File size: 1,645 Bytes
69f6746
 
 
 
 
 
 
 
691539b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import torch
import gradio as gr

# Use a pipeline as a high-level helper
from transformers import pipeline

pipe = pipeline("translation", model="facebook/nllb-200-distilled-600M", torch_dtype = torch.bfloat16)

def get_fores_code(language):
    # Loop through the list of languages
    for entry in languages['languages']:
        if entry['name'].lower() == language.lower():  # Compare to the 'name' field in the dictionary
            return entry['code']
    return None  # Return None if no match is found


def translate_text(text, destination_language):
    # Convert language name to language code using get_fores_code function
    dest_code = get_fores_code(destination_language) 
    
    # Ensure the code is valid (for debugging purposes)
    print(f"Destination language code: {dest_code}")
    
    # Call the translation pipeline with the correct language codes
    translation = pipe(text, 
                       src_lang='eng_Latn', 
                       tgt_lang=dest_code)  # Pass the actual code (no quotes)
    
    return translation[0]['translation_text']

demo = gr.Interface(fn=translate_text,
                   inputs= [
                       gr.TextArea(label='Insert the text in English to translate'),
                       gr.Dropdown(
                           label='Select the language to translate',
                           choices=[lang['name'] for lang in languages['languages']],  # Extract the 'name' field
                           value='English'
                       )    
                   ],
                   outputs=[gr.TextArea(label='This is the translated text')])

demo.launch()