Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,6 +4,8 @@ from dotenv import load_dotenv
|
|
| 4 |
import json
|
| 5 |
from deep_translator import GoogleTranslator
|
| 6 |
import google.generativeai as genai
|
|
|
|
|
|
|
| 7 |
|
| 8 |
load_dotenv()
|
| 9 |
|
|
@@ -18,36 +20,42 @@ def make_call(data):
|
|
| 18 |
language = items['lang']
|
| 19 |
query = items['text']
|
| 20 |
query = query.lower()
|
| 21 |
-
translated = None
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
respo = {
|
| 53 |
"message": translated,
|
|
|
|
| 4 |
import json
|
| 5 |
from deep_translator import GoogleTranslator
|
| 6 |
import google.generativeai as genai
|
| 7 |
+
import time
|
| 8 |
+
import random
|
| 9 |
|
| 10 |
load_dotenv()
|
| 11 |
|
|
|
|
| 20 |
language = items['lang']
|
| 21 |
query = items['text']
|
| 22 |
query = query.lower()
|
| 23 |
+
translated = None
|
| 24 |
+
|
| 25 |
+
model = genai.GenerativeModel('gemini-pro')
|
| 26 |
+
|
| 27 |
+
retries = 0
|
| 28 |
+
max_retries = 5 # You can adjust this number
|
| 29 |
+
base_delay = 1 # Initial delay in seconds
|
| 30 |
+
|
| 31 |
+
while retries < max_retries:
|
| 32 |
+
try:
|
| 33 |
+
prompt_query = (
|
| 34 |
+
f"Answer this query in a short message with wisdom, love, and compassion, "
|
| 35 |
+
f"in context to Bhagavad Gita, that feels like chatting to a person and "
|
| 36 |
+
f"provide references of shlokas from chapters of Bhagavad Gita which are "
|
| 37 |
+
f"relevant to the query. Keep the answer short, precise, and simple. "
|
| 38 |
+
f"Query: {query}"
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
response = model.generate_content(prompt_query)
|
| 42 |
+
answer = response.text
|
| 43 |
+
translated = GoogleTranslator(source='auto', target=language).translate(answer)
|
| 44 |
+
break # Exit the loop if the call is successful
|
| 45 |
+
except Exception as e:
|
| 46 |
+
if "429 Quota exceeded" in str(e):
|
| 47 |
+
delay = base_delay * (2 ** retries) + random.uniform(0, 1) # Exponential backoff with jitter
|
| 48 |
+
print(f"Quota exceeded. Retrying in {delay:.2f} seconds... (Attempt {retries + 1}/{max_retries})")
|
| 49 |
+
time.sleep(delay)
|
| 50 |
+
retries += 1
|
| 51 |
+
else:
|
| 52 |
+
print(f"API call failed: {e}")
|
| 53 |
+
translated = f"An error occurred while fetching the answer: {e}"
|
| 54 |
+
break # Exit the loop for other errors
|
| 55 |
+
else:
|
| 56 |
+
# This block executes if the loop completes without a successful break (i.e., max_retries reached)
|
| 57 |
+
translated = "Maximum retry attempts reached. Please try again later."
|
| 58 |
+
|
| 59 |
|
| 60 |
respo = {
|
| 61 |
"message": translated,
|