Upload main.py
Browse files
main.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Flask, request, jsonify
|
| 2 |
+
from sentence_transformers import SentenceTransformer
|
| 3 |
+
from pinecone import Pinecone
|
| 4 |
+
import google.generativeai as genai
|
| 5 |
+
from langdetect import detect
|
| 6 |
+
|
| 7 |
+
# ุชููุฆุฉ ุงูู
ูุฏููุงุช
|
| 8 |
+
embedding_model = SentenceTransformer("intfloat/multilingual-e5-large")
|
| 9 |
+
|
| 10 |
+
pc = Pinecone(api_key="pcsk_3ax4D8_PH7vWF1KWAMRpyjmEnXhwxswmHSjvqgwovna3xGGbfsgZsMRtRyFi9uCpPyi4B9")
|
| 11 |
+
index = pc.Index("newindex")
|
| 12 |
+
|
| 13 |
+
genai.configure(api_key="AIzaSyBXtRzMkpm9RNDO09A9N3XoG_vfjgUe5Vw")
|
| 14 |
+
model = genai.GenerativeModel("gemini-2.0-flash")
|
| 15 |
+
|
| 16 |
+
app = Flask(__name__)
|
| 17 |
+
chat_history = []
|
| 18 |
+
|
| 19 |
+
def detect_language(text):
|
| 20 |
+
try:
|
| 21 |
+
return detect(text)
|
| 22 |
+
except:
|
| 23 |
+
return "unknown"
|
| 24 |
+
|
| 25 |
+
def get_answer_from_pinecone(user_question, embedding_model, index, top_k=5, similarity_threshold=0.7):
|
| 26 |
+
try:
|
| 27 |
+
question_vector = embedding_model.encode(user_question).tolist()
|
| 28 |
+
except Exception as e:
|
| 29 |
+
return [f"โ Error embedding question: {e}"]
|
| 30 |
+
|
| 31 |
+
try:
|
| 32 |
+
search_result = index.query(
|
| 33 |
+
vector=question_vector,
|
| 34 |
+
top_k=top_k,
|
| 35 |
+
include_metadata=True
|
| 36 |
+
)
|
| 37 |
+
except Exception as e:
|
| 38 |
+
return [f"โ Error querying Pinecone: {e}"]
|
| 39 |
+
|
| 40 |
+
matches = [m for m in search_result.matches if m.score >= similarity_threshold]
|
| 41 |
+
sorted_matches = sorted(matches, key=lambda x: x.score, reverse=True)
|
| 42 |
+
|
| 43 |
+
answers = []
|
| 44 |
+
for m in sorted_matches:
|
| 45 |
+
answer = m.metadata.get('answer', '').strip()
|
| 46 |
+
source = m.metadata.get('source', 'unknown')
|
| 47 |
+
score = round(m.score, 3)
|
| 48 |
+
if answer:
|
| 49 |
+
answers.append(f"โข ({score}) from [{source}]:\n{answer}")
|
| 50 |
+
return answers if answers else ["โ ๏ธ No similar answers found."]
|
| 51 |
+
|
| 52 |
+
def ask_gemini_with_combined_answer(user_question, pinecone_answers=[], history=[]):
|
| 53 |
+
context = "\n".join([f"๐ค {q}\n๐ค {a}" for q, a in history])
|
| 54 |
+
extracted_info = "\n".join([f"โข {ans}" for ans in pinecone_answers]) if pinecone_answers else "None"
|
| 55 |
+
lang = detect_language(user_question)
|
| 56 |
+
|
| 57 |
+
if lang == "ar":
|
| 58 |
+
greeting = "ู
ุฑุญุจูุง! ๐"
|
| 59 |
+
instructions = """
|
| 60 |
+
โ ูุงู
: ุงุณุชุฎุฏู
ููุท ุงูู
ุนููู
ุงุช ู
ู ูุงุนุฏุฉ ุงูุจูุงูุงุช.
|
| 61 |
+
|
| 62 |
+
๐ ุงูู
ุญุงุฏุซุฉ ุงูุณุงุจูุฉ:
|
| 63 |
+
{context}
|
| 64 |
+
|
| 65 |
+
๐ค ุงูู
ุณุชุฎุฏู
ูุณุฃู: {user_question}
|
| 66 |
+
๐ ู
ุนููู
ุงุช ู
ู ูุงุนุฏุฉ ุงูุจูุงูุงุช:
|
| 67 |
+
{extracted_info}
|
| 68 |
+
|
| 69 |
+
๐ ุงูุฑุฏ:
|
| 70 |
+
"""
|
| 71 |
+
else:
|
| 72 |
+
greeting = "Hello! ๐"
|
| 73 |
+
instructions = """
|
| 74 |
+
โ Important: Use only database information.
|
| 75 |
+
|
| 76 |
+
๐ Previous conversation:
|
| 77 |
+
{context}
|
| 78 |
+
|
| 79 |
+
๐ค User asks: {user_question}
|
| 80 |
+
๐ Retrieved info:
|
| 81 |
+
{extracted_info}
|
| 82 |
+
|
| 83 |
+
๐ Response:
|
| 84 |
+
"""
|
| 85 |
+
|
| 86 |
+
prompt = instructions.format(
|
| 87 |
+
context=context or ("ูุง ููุฌุฏ" if lang == "ar" else "None"),
|
| 88 |
+
user_question=user_question,
|
| 89 |
+
extracted_info=extracted_info
|
| 90 |
+
)
|
| 91 |
+
response = model.generate_content(prompt)
|
| 92 |
+
return f"{greeting}\n{response.text.strip()}"
|
| 93 |
+
|
| 94 |
+
@app.route("/ask", methods=["POST"])
|
| 95 |
+
def ask():
|
| 96 |
+
data = request.json
|
| 97 |
+
question = data.get("question")
|
| 98 |
+
if not question:
|
| 99 |
+
return jsonify({"error": "Missing question"}), 400
|
| 100 |
+
|
| 101 |
+
pinecone_answer = get_answer_from_pinecone(question, embedding_model, index)
|
| 102 |
+
final_answer = ask_gemini_with_combined_answer(question, pinecone_answer, chat_history)
|
| 103 |
+
chat_history.append((question, final_answer))
|
| 104 |
+
|
| 105 |
+
return jsonify({
|
| 106 |
+
"question": question,
|
| 107 |
+
"pinecone_matches": pinecone_answer,
|
| 108 |
+
"answer": final_answer
|
| 109 |
+
})
|
| 110 |
+
|
| 111 |
+
@app.route("/")
|
| 112 |
+
def home():
|
| 113 |
+
return "๐ค API is running. Use POST /ask with {'question': '...'}"
|
| 114 |
+
|
| 115 |
+
if __name__ == "__main__":
|
| 116 |
+
app.run(host="0.0.0.0", port=7860)
|