Ra-Is commited on
Commit
e5c2107
1 Parent(s): e1b3d3f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +12 -3
app.py CHANGED
@@ -5,6 +5,12 @@ import os
5
 
6
  # Define the function to call the API
7
  def translate(text, lang):
 
 
 
 
 
 
8
  url = os.getenv("TRANSLATION_URL")
9
  payload = json.dumps({
10
  "text": text,
@@ -17,15 +23,18 @@ def translate(text, lang):
17
  # Make the API request
18
  response = requests.request("POST", url, headers=headers, data=payload)
19
 
20
- # Parse the response and extract the translation
21
  response_data = response.json() # Parse the JSON response
22
- translation = response_data.get("translation", "Translation not found") # Get the translation
 
 
23
 
 
24
  return translation
25
 
26
  # Create the Gradio interface with a textbox and dropdown
27
  textbox = gr.Textbox(placeholder="Enter text to translate...")
28
- dropdown = gr.Dropdown(choices=["english-twi", "twi-english"], label="Select Translation Language")
29
 
30
  # Pass both inputs to the translate function
31
  demo = gr.Interface(fn=translate, inputs=[textbox, dropdown], outputs="text")
 
5
 
6
  # Define the function to call the API
7
  def translate(text, lang):
8
+ if not lang:
9
+ return "Error: Please select a translation language."
10
+
11
+ if not text:
12
+ return "Error: Please enter text for translation."
13
+
14
  url = os.getenv("TRANSLATION_URL")
15
  payload = json.dumps({
16
  "text": text,
 
23
  # Make the API request
24
  response = requests.request("POST", url, headers=headers, data=payload)
25
 
26
+ # Parse the response and handle potential errors
27
  response_data = response.json() # Parse the JSON response
28
+ if "errors" in response_data:
29
+ lang_error = response_data["errors"].get("lang", ["An error occurred"])[0]
30
+ return f"Error: {lang_error}" # Return the error message
31
 
32
+ translation = response_data.get("translation", "Translation not found") # Get the translation
33
  return translation
34
 
35
  # Create the Gradio interface with a textbox and dropdown
36
  textbox = gr.Textbox(placeholder="Enter text to translate...")
37
+ dropdown = gr.Dropdown(choices=["", "english-twi", "twi-english"], label="Select Translation Language", value="") # Include a default empty option
38
 
39
  # Pass both inputs to the translate function
40
  demo = gr.Interface(fn=translate, inputs=[textbox, dropdown], outputs="text")