Update app.py
Browse files
app.py
CHANGED
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import gradio as gr
|
3 |
+
import json
|
4 |
+
from transformers import pipeline
|
5 |
+
|
6 |
+
pipe = pipeline("translation", model="facebook/nllb-200-distilled-600M",torch_dtype=torch.bfloat16)
|
7 |
+
# Initialize the pipeline
|
8 |
+
try:
|
9 |
+
text_translator = pipeline("translation", model=model_path, torch_dtype=torch.bfloat16)
|
10 |
+
except Exception as e:
|
11 |
+
raise ValueError(f"Error initializing the model. Check the model path: {e}")
|
12 |
+
|
13 |
+
# Load the JSON data for language codes
|
14 |
+
try:
|
15 |
+
with open('language.json', 'r') as file:
|
16 |
+
language_data = json.load(file)
|
17 |
+
except FileNotFoundError:
|
18 |
+
raise FileNotFoundError("The language.json file was not found at the specified path.")
|
19 |
+
except json.JSONDecodeError:
|
20 |
+
raise ValueError("Error decoding the JSON file. Ensure it is formatted correctly.")
|
21 |
+
|
22 |
+
|
23 |
+
# Create a function to get the FLORES-200 code for a given language
|
24 |
+
def get_FLORES_code_from_language(language):
|
25 |
+
for entry in language_data:
|
26 |
+
if entry['Language'].lower() == language.lower():
|
27 |
+
return entry['FLORES-200 code']
|
28 |
+
return None
|
29 |
+
|
30 |
+
|
31 |
+
# Translation function
|
32 |
+
def translate_text(text, destination_language):
|
33 |
+
if not text.strip():
|
34 |
+
return "Input text cannot be empty."
|
35 |
+
|
36 |
+
dest_code = get_FLORES_code_from_language(destination_language)
|
37 |
+
if not dest_code:
|
38 |
+
return f"Language '{destination_language}' is not supported."
|
39 |
+
|
40 |
+
try:
|
41 |
+
translation = text_translator(text, src_lang="eng_Latn", tgt_lang=dest_code)
|
42 |
+
return translation[0]["translation_text"]
|
43 |
+
except Exception as e:
|
44 |
+
return f"Error during translation: {e}"
|
45 |
+
|
46 |
+
|
47 |
+
# Extract available languages from JSON
|
48 |
+
available_languages = [entry['Language'] for entry in language_data]
|
49 |
+
|
50 |
+
# Create the Gradio interface
|
51 |
+
demo = gr.Interface(
|
52 |
+
fn=translate_text,
|
53 |
+
inputs=[
|
54 |
+
gr.Textbox(label="Input text to translate", lines=6),
|
55 |
+
gr.Dropdown(available_languages, label="Select language to translate to")
|
56 |
+
],
|
57 |
+
outputs=gr.Textbox(label="Translated text", lines=6),
|
58 |
+
title="Project 03: Multi Language Translator",
|
59 |
+
description="Translate English text into multiple languages using the NLLB-200 model."
|
60 |
+
)
|
61 |
+
|
62 |
+
# Launch the interface
|
63 |
+
demo.launch()
|