Spaces:
Running
Running
Commit
·
6fbb505
1
Parent(s):
fc80c0b
Added application file
Browse files- app.py +37 -0
- translator.py +34 -0
app.py
ADDED
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
|
3 |
+
|
4 |
+
|
5 |
+
from translator import Translator
|
6 |
+
import gradio as gr
|
7 |
+
import os
|
8 |
+
|
9 |
+
|
10 |
+
# Load the API key from an environment variable or a file
|
11 |
+
fanar_api_key = os.getenv("FANAR_API_KEY")
|
12 |
+
langpair = "en-ar" # also pass this as an option to the interface. The user should be able to choose the language pair
|
13 |
+
|
14 |
+
translator = Translator(api_key=fanar_api_key, langpair=langpair, model="Fanar-Shaheen-MT-1")
|
15 |
+
|
16 |
+
def translate_text(text):
|
17 |
+
return translator.translate(text)
|
18 |
+
|
19 |
+
with gr.Blocks() as demo:
|
20 |
+
gr.Markdown("# Fanar Translator")
|
21 |
+
gr.Markdown("## Translate text into Arabic Using the State of the Art Fanar Shaheen MT Model")
|
22 |
+
|
23 |
+
with gr.Row():
|
24 |
+
input_box = gr.Textbox(label="Input Text", placeholder="Enter text to translate here...", lines=4)
|
25 |
+
with gr.Row():
|
26 |
+
output_box = gr.Textbox(label="Output Text", placeholder="Translated text will appear here...", lines=4, interactive=False)
|
27 |
+
|
28 |
+
translate_button = gr.Button("Translate")
|
29 |
+
translate_button.click(translate_text, inputs=input_box, outputs=output_box)
|
30 |
+
|
31 |
+
|
32 |
+
|
33 |
+
|
34 |
+
demo.launch()
|
35 |
+
|
36 |
+
|
37 |
+
|
translator.py
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
import requests
|
3 |
+
|
4 |
+
class Translator:
|
5 |
+
def __init__(self, api_key, base_url="https://api.fanar.qa/v1/translations", langpair="ar-en", model="Fanar-Shaheen-MT-1"):
|
6 |
+
self.api_key = api_key
|
7 |
+
self.base_url = base_url
|
8 |
+
self.langpair = langpair
|
9 |
+
self.model = model
|
10 |
+
|
11 |
+
def translate(self, text):
|
12 |
+
headers = {
|
13 |
+
'Content-Type': 'application/json',
|
14 |
+
'Authorization': f'Bearer {self.api_key}',
|
15 |
+
"User-Agent": "curl/7.81.0"
|
16 |
+
}
|
17 |
+
|
18 |
+
data = {
|
19 |
+
"text": text,
|
20 |
+
"langpair": self.langpair,
|
21 |
+
"model": self.model
|
22 |
+
}
|
23 |
+
|
24 |
+
res = requests.post(self.base_url, headers=headers, json=data)
|
25 |
+
if res.status_code != 200:
|
26 |
+
raise Exception(f"Error: API request failed with status code {res.status_code}. Details: {res.text}")
|
27 |
+
|
28 |
+
data = res.json()
|
29 |
+
if "text" not in data: # modify to account for API failures. Not very important since we need to run locally.
|
30 |
+
raise Exception(f"Error: 'text' not found in response: {data}")
|
31 |
+
|
32 |
+
return data["text"]
|
33 |
+
|
34 |
+
|