sameernotes commited on
Commit
2854bbf
·
verified ·
1 Parent(s): a75bfa0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -20
app.py CHANGED
@@ -3,7 +3,8 @@ from typing import List
3
 
4
  from fastapi import FastAPI, HTTPException, status
5
  from pydantic import BaseModel
6
- import requests # Import the requests library
 
7
 
8
  app = FastAPI()
9
 
@@ -13,6 +14,7 @@ if not GEMINI_API_KEY:
13
  raise ValueError("The GEMINI_API_KEY environment variable is not set.")
14
 
15
  # Gemini API endpoint (using the v1beta endpoint for text generation)
 
16
  GEMINI_API_URL = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash-lite:generateContent?key=" + GEMINI_API_KEY
17
 
18
 
@@ -22,7 +24,7 @@ class TranslationRequest(BaseModel):
22
  source_language: str = None
23
 
24
 
25
- class TranslationResponse(BaseModel):
26
  translated_text: str
27
  source_language: str
28
  target_language: str
@@ -34,7 +36,7 @@ def detect_language_and_options(text: str):
34
  """Detects the language and provides translation options using the requests library."""
35
 
36
  prompt = f"""Please identify the language of the text provided and then offer translation options as numbered choices (1-5). Use this format: "The text is in [Language]. Choose a language to translate to: 1. [Option 1], 2. [Option 2], 3. [Option 3], 4. [Option 4], 5. [Option 5]"
37
-
38
  Input Text: {text}""" # Include the input text in the prompt
39
 
40
  request_data = {
@@ -68,10 +70,14 @@ def detect_language_and_options(text: str):
68
  raise HTTPException(status_code=500, detail=f"Error communicating with Gemini API: {e}")
69
  except Exception as e: #Catch any other unexpected error
70
  raise HTTPException(status_code=500, detail=f"An unexpected error occurred: {e}")
 
71
  def translate_with_gemini(text: str, source_language: str, target_language: str) -> str:
72
- """Translates text using the Gemini API via requests."""
 
 
73
 
74
- prompt = f"Translate the following text from {source_language} to {target_language}:\n\n{text}"
 
75
 
76
  request_data = {
77
  "contents": [{
@@ -82,26 +88,25 @@ def translate_with_gemini(text: str, source_language: str, target_language: str)
82
 
83
  try:
84
  response = requests.post(GEMINI_API_URL, json=request_data)
85
- response.raise_for_status() # Important: Check for HTTP errors
86
  response_json = response.json()
87
 
88
- # Robustly extract the translated text, handling potential errors
89
  try:
90
  translated_text = response_json['candidates'][0]['content']['parts'][0]['text']
91
- return translated_text
92
  except (KeyError, IndexError) as e:
93
  raise HTTPException(status_code=500, detail=f"Error parsing Gemini API response: {e}")
94
-
95
  except requests.exceptions.RequestException as e:
96
  raise HTTPException(status_code=500, detail=f"Error communicating with Gemini API: {e}")
97
  except Exception as e:
98
- raise HTTPException(status_code=500, detail=f"An unexpected error occurred {e}")
 
99
 
100
 
101
 
102
- @app.post("/translate", response_model=TranslationResponse, status_code=status.HTTP_200_OK)
103
  async def translate(request: TranslationRequest):
104
- """Translates text from a source language to a target language."""
105
 
106
  if not request.text:
107
  raise HTTPException(status_code=400, detail="Text to translate cannot be empty.")
@@ -115,19 +120,19 @@ async def translate(request: TranslationRequest):
115
  source_language, _ = detect_language_and_options(request.text)
116
  except HTTPException as e:
117
  raise e
 
118
 
119
- supported_languages = ["English", "Hindi", "Telugu", "Marathi", "Bengali", "Tamil", "Spanish", "French", "German", "Japanese", "Chinese"]
120
  if request.target_language not in supported_languages:
121
- raise HTTPException(status_code=400, detail=f"Target language '{request.target_language}' is not supported.")
 
122
 
123
  try:
124
- translated_text = translate_with_gemini(request.text, source_language, request.target_language)
125
- return TranslationResponse(translated_text=translated_text, source_language=source_language, target_language=request.target_language)
126
- except HTTPException as e:
127
  raise e
128
- except Exception as e:
129
- raise HTTPException(status_code=500,detail=f"An unexpected error occurred {e}")
130
-
131
 
132
 
133
  @app.post("/detect_language", status_code=status.HTTP_200_OK)
 
3
 
4
  from fastapi import FastAPI, HTTPException, status
5
  from pydantic import BaseModel
6
+ import requests
7
+ from fastapi.responses import HTMLResponse # Import HTMLResponse
8
 
9
  app = FastAPI()
10
 
 
14
  raise ValueError("The GEMINI_API_KEY environment variable is not set.")
15
 
16
  # Gemini API endpoint (using the v1beta endpoint for text generation)
17
+ # Using gemini-2.0-flash-lite for speed
18
  GEMINI_API_URL = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash-lite:generateContent?key=" + GEMINI_API_KEY
19
 
20
 
 
24
  source_language: str = None
25
 
26
 
27
+ class TranslationResponse(BaseModel): # Still useful for /detect_language
28
  translated_text: str
29
  source_language: str
30
  target_language: str
 
36
  """Detects the language and provides translation options using the requests library."""
37
 
38
  prompt = f"""Please identify the language of the text provided and then offer translation options as numbered choices (1-5). Use this format: "The text is in [Language]. Choose a language to translate to: 1. [Option 1], 2. [Option 2], 3. [Option 3], 4. [Option 4], 5. [Option 5]"
39
+
40
  Input Text: {text}""" # Include the input text in the prompt
41
 
42
  request_data = {
 
70
  raise HTTPException(status_code=500, detail=f"Error communicating with Gemini API: {e}")
71
  except Exception as e: #Catch any other unexpected error
72
  raise HTTPException(status_code=500, detail=f"An unexpected error occurred: {e}")
73
+
74
  def translate_with_gemini(text: str, source_language: str, target_language: str) -> str:
75
+ """Translates text, requesting HTML, and handles it correctly."""
76
+
77
+ prompt = f"""Translate the following text from {source_language} to {target_language}. Return *only* the translated text. Format the response as HTML. If any part of the translated text should be emphasized (like an example or key phrase), use `<strong>` tags around that part. Do not include ANY additional text like 'Here is the translation:' or similar. Only the translated text, formatted as HTML.
78
 
79
+ Text:
80
+ {text}"""
81
 
82
  request_data = {
83
  "contents": [{
 
88
 
89
  try:
90
  response = requests.post(GEMINI_API_URL, json=request_data)
91
+ response.raise_for_status()
92
  response_json = response.json()
93
 
 
94
  try:
95
  translated_text = response_json['candidates'][0]['content']['parts'][0]['text']
96
+ return translated_text # Return the raw HTML string
97
  except (KeyError, IndexError) as e:
98
  raise HTTPException(status_code=500, detail=f"Error parsing Gemini API response: {e}")
 
99
  except requests.exceptions.RequestException as e:
100
  raise HTTPException(status_code=500, detail=f"Error communicating with Gemini API: {e}")
101
  except Exception as e:
102
+ raise HTTPException(status_code=500, detail=f"An unexpected error occurred: {e}")
103
+
104
 
105
 
106
 
107
+ @app.post("/translate", response_class=HTMLResponse, status_code=status.HTTP_200_OK)
108
  async def translate(request: TranslationRequest):
109
+ """Translates text, returning HTML."""
110
 
111
  if not request.text:
112
  raise HTTPException(status_code=400, detail="Text to translate cannot be empty.")
 
120
  source_language, _ = detect_language_and_options(request.text)
121
  except HTTPException as e:
122
  raise e
123
+ supported_languages = ["Afrikaans","Arabic","Armenian","Azerbaijani","Belarusian","Bosnian","Bulgarian","Catalan","Chinese","Croatian","Czech","Danish","Dutch","English","Estonian","Finnish","French","Galician","German","Greek","Hebrew","Hindi","Hungarian","Icelandic","Indonesian","Italian","Japanese","Kannada","Kazakh","Korean","Latvian","Lithuanian","Macedonian","Malay","Marathi","Maori","Nepali","Norwegian","Persian","Polish","Portuguese","Romanian","Russian","Serbian","Slovak","Slovenian","Spanish","Swahili","Swedish","Tagalog","Tamil","Thai","Turkish","Ukrainian","Urdu","Vietnamese","Welsh",]
124
 
 
125
  if request.target_language not in supported_languages:
126
+ raise HTTPException(status_code=400, detail=f"Target language '{request.target_language}' is not supported. Supported languages are: {', '.join(supported_languages)}")
127
+
128
 
129
  try:
130
+ translated_html = translate_with_gemini(request.text, source_language, request.target_language)
131
+ return translated_html # FastAPI handles the HTMLResponse correctly
132
+ except HTTPException as e: # Catch specific HTTP exceptions
133
  raise e
134
+ except Exception as e: #Catch any other unexpected error
135
+ raise HTTPException(status_code=500, detail=f"An unexpected error occurred: {e}")
 
136
 
137
 
138
  @app.post("/detect_language", status_code=status.HTTP_200_OK)