Spaces:
Sleeping
Sleeping
Delete main.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
from fastapi import FastAPI, Form, BackgroundTasks
from fastapi.responses import Response
from twilio.twiml.messaging_response import MessagingResponse
from twilio.rest import Client
from openai import OpenAI
from langdetect import detect
import os
import google.generativeai as genai
from langdetect import detect
import pycountry
app = FastAPI()
# Twilio credentials
TWILIO_FROM = "whatsapp:+15558005951" # Twilio sandbox number
TWILIO_FROM ='whatsapp:+14155238886'
# Twilio credentials
account_sid = 'AC78af67be29d673f2455d888e73535a17'
auth_token = 'd01614f14649f0c9a1dadc35b754a57c'
client = Client(account_sid, auth_token)
# list of allowed language trnslation
#india_lang_list=['hi','ta','ml','te','kn','mr','gu','bn','pa','ur','as','ne','sa']
india_lang_list=['Hindi','Tamil','Malayalam','Telugu','Kannada','Marati','Gujarati','Bengali','Panjabi','Urdu','Assamese','Nepali','Sanskrit']
def get_lang_or_default(det_lang):
if det_lang in india_lang_list:
return det_lang
else:
return 'English'
# OpenAI client
OPENAI_API_KEY = "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"
#openai.api_key = OPENAI_API_KEY
openai_client = OpenAI(api_key=OPENAI_API_KEY)
GOOGLE_API_KEY = "AIzaSyAhCcsGVTBzDVRWhoiA1ETagR5cPgpBEOw"
genai.configure(api_key=GOOGLE_API_KEY)
def translate_text_with_gemini(text, target_language):
prompt = f"""You are a professional translator. Translate the following text to {target_language} without adding, changing, or omitting any details.
Text:
{text}
"""
model = genai.GenerativeModel("gemini-1.5-flash")
response = model.generate_content(prompt)
return response.text
def detect_language_name(text):
try:
# Detect ISO 639-1 language code
lang_code = detect(text)
# Get full language name using pycountry
language = pycountry.languages.get(alpha_2=lang_code)
if language:
return language.name
else:
return f"Unknown language code: {lang_code}"
except Exception as e:
return f"Error detecting language: {str(e)}"
# Example
utext = "ਮੈਂ ਪੰਜਾਬੀ ਵਿੱਚ ਗੱਲ ਕਰਦਾ ਹਾਂ۔"
print("Detected language:", detect_language_name(utext))
# Detect language
def detect_language(text):
try:
return detect(text)
except:
return "en"
# Translate using OpenAI
def translate_text_with_openai(text, target_lang):
prompt = (
f"You are a professional translator. Translate the following exactly and completely "
f"to {target_lang} without adding or changing any details:\n\n{text}"
)
response = openai_client.chat.completions.create(
model="gpt-3.5-turbo", # or "gpt-4o" if available
messages=[
{"role": "system", "content": "Translate the following exactly and completely."},
{"role": "user", "content": prompt}
],
max_tokens=300,
temperature=0.0
)
return response.choices[0].message.content.strip()
# Example usage
translated = translate_text_with_openai("I worked at Meta Reality Labs and Amazon Lab126 in California.", "Malayalam")
print("Translated:", translated)
def translate_with_openai(text, target_lang):
prompt = f"Translate the following to {target_lang}:\n\n{text}"
response = openai_client.chat.completions.create(
model="gpt-4o", # You can also use "gpt-3.5-turbo"
messages=[
{"role": "system", "content": "You are a professional translator."},
{"role": "user", "content": prompt}
],
max_tokens=300,
temperature=0.0
)
return response.choices[0].message.content.strip()
# Example usage
translated = translate_with_openai("I worked at Meta Reality Labs and Amazon Lab126 in California.", "Malayalam")
print("Translated:", translated)
def translate_with_gemini(text, target_lang):
prompt = f"""Translate the following text to {target_lang}. Do not add or change any details.
Text:{text}"""
model = genai.GenerativeModel("gemini-1.5-flash")
response = model.generate_content(prompt)
return response.text.strip()
def evaluate_translations1(original_text, openai_translation, gemini_translation, target_lang):
prompt = f"""You are a multilingual evaluator. Compare two translations of the same English text into {target_lang}. Choose the one that is more accurate, complete, and faithful to the original meaning.
Original text:
{original_text}
Translation A (OpenAI):
{openai_translation}
Translation B (Gemini):
{gemini_translation}
Which translation is better? Respond with selected translation and a brief reason."""
response = openai_client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "You are a professional translation evaluator."},
{"role": "user", "content": prompt}
],
max_tokens=300,
temperature=0.0
)
return response.choices[0].message.content.strip()
def evaluate_translations(original_text, openai_translation, gemini_translation, target_lang):
prompt = f"""You are a multilingual evaluator. Compare two translations of the same English text into {target_lang}.
Choose the one that is more accurate, complete, and faithful to the original meaning.
Original text:
{original_text}
Translation A (OpenAI):
{openai_translation}
Translation B (Gemini):
{gemini_translation}
Respond with only the better translation text. Do not mention 'Translation A' or 'Translation B'. Just return the selected translation itself."""
response = openai_client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "You are a professional translation evaluator."},
{"role": "user", "content": prompt}
],
max_tokens=300,
temperature=0.0
)
return response.choices[0].message.content.strip()
def get_best_translation(text, target_lang):
openai_result = translate_with_openai(text, target_lang)
gemini_result = translate_with_gemini(text, target_lang)
verdict = evaluate_translations(text, openai_result, gemini_result, target_lang)
return verdict
#return {
# "original": text,
## "openai_translation": openai_result,
# "gemini_translation": gemini_result,
# "verdict": verdict
#}
#result = get_best_translation("I worked at Meta Reality Labs and Amazon Lab126 in California.","Malayalam")
#print("Best Translation:", result["verdict"])
# Send a WhatsApp message
def send_whatsapp_message():
message = client.messages.create(
from_=TWILIO_FROM,#'whatsapp:+14155238886', # Twilio sandbox number
body='Hello from Elisda!!',
to='whatsapp:+19495004623' # Your verified number
)
print("Message SID:", message.sid)
# Call this once to send the message
send_whatsapp_message()
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello from FastAPI!"}
# return answer in english for the question in enlgish
def get_reply_english(custom_context, incoming_msg):
try:
response = openai_client.chat.completions.create(
model="gpt-3.5-turbo", # or "gpt-4o" if available
messages=[
{
"role": "system",
"content": f"Use the following context to answer questions in English only:\n{custom_context}"
},
{
"role": "user",
"content": incoming_msg
}
],
max_tokens=300,
temperature=0.5
)
answer = response.choices[0].message.content.strip()
print(answer)
except Exception as e:
print("OpenAI error:", str(e))
answer = "Sorry, I cannot answer that question."
return answer
# Generate reply and send via Twilio API
with open("summary.txt", "r", encoding="utf-8") as f:
custom_context = f.read()
custom_context = custom_context[:8000]
def process_and_respond(incoming_msg, custom_context, sender_number):
print("Incoming message:", incoming_msg)
# Detect language
det_lang = detect_language_name(incoming_msg)
print("Detected language:", det_lang)
target_lang = get_lang_or_default(det_lang)
# Generate AI reply in English
response = openai_client.chat.completions.create(
model="gpt-3.5-turbo", # or "gpt-4o"
messages=[
{
"role": "system",
"content": f"Use the following context to answer questions:\n{custom_context}"
},
{
"role": "user",
"content": incoming_msg
}
],
max_tokens=1000,
temperature=0.3
)
answer = response.choices[0].message.content.strip()
# Translate if needed
if target_lang.lower() == "english":
final_reply = get_reply_english(custom_context, incoming_msg)
translated_reply = final_reply
else:
translated_question = translate_with_openai(incoming_msg, "English")
print("Translated question:", translated_question)
english_reply = get_reply_english(custom_context, translated_question)
print("English reply:", english_reply)
translated_reply = get_best_translation(english_reply, target_lang)
print("Final translated reply:", translated_reply)
# Send reply via Twilio
client.messages.create(
from_=TWILIO_FROM,
to=sender_number,
body=translated_reply
)
@app.post("/webhook")
async def whatsapp_reply( Body: str = Form(...), From: str = Form(...), background_tasks: BackgroundTasks = None):
# Respond immediately to Twilio
#send multimedia
incoming_msg = Body.lower()
sender = From
resp = MessagingResponse()
if "menu" in incoming_msg or "picture" in incoming_msg:
client.messages.create(
from_ =TWILIO_FROM,
to=sender,
body="Here's the image you requested!",
media_url=["https://example.com/sample-image.jpg"]
)
elif "send video" in incoming_msg:
client.messages.create(
from_=TWILIO_FROM,
to=sender,
body="Here's your video!",
media_url=["https://www.appsloveworld.com/wp-content/uploads/2018/10/640.mp4"]
)
elif "send audio" in incoming_msg:
client.messages.create(
from_=TWILIO_FROM,
to=sender,
body="Here's your audio file!",
media_url=["http://www.largesound.com/ashborytour/sound/brobob.mp3"]
)
else:
resp.message("Send 'menu', 'picture', 'send video', or 'send audio' to receive a file.")
print("------------------------------------")
print(Body.strip())
det_lang = detect_language(Body.strip())
print(det_lang)
target_lang=get_lang_or_default(det_lang)
print(target_lang)
if(target_lang =='English'):
translated_wait_msg="Processing your request..."
else:
translated_wait_msg = translate_text_with_openai("Processing your request...", target_lang)
#print(translated_wait_msg)
#msg = resp.message(translated_wait_msg)
# Process in background
background_tasks.add_task(process_and_respond, Body.strip(), custom_context, From)
#return Response(content=str(resp), media_type="application/xml")
return Response(content=str(resp).encode("utf-8"), media_type="application/xml")
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
main.pyDeleted-415