Chat
Browse files
main.py
CHANGED
|
@@ -1,47 +1,126 @@
|
|
| 1 |
import os
|
| 2 |
-
import io
|
| 3 |
import json
|
| 4 |
-
import
|
| 5 |
-
import
|
| 6 |
-
|
| 7 |
-
from
|
| 8 |
-
import pytz
|
| 9 |
-
from flask import Flask, request, jsonify, send_file
|
| 10 |
from flask_cors import CORS
|
| 11 |
import google.generativeai as genai
|
| 12 |
import firebase_admin
|
| 13 |
-
from firebase_admin import credentials,
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
from urllib.parse import urlparse, unquote
|
| 18 |
|
|
|
|
| 19 |
app = Flask(__name__)
|
| 20 |
CORS(app)
|
| 21 |
|
| 22 |
-
#
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
else:
|
| 33 |
-
print("
|
| 34 |
-
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
-
|
| 38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
genai.configure(api_key=os.getenv("Gemini"))
|
| 43 |
-
return genai.GenerativeModel('gemini-2.0-flash-thinking-exp')
|
| 44 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
|
| 46 |
-
|
| 47 |
-
|
|
|
|
|
|
| 1 |
import os
|
|
|
|
| 2 |
import json
|
| 3 |
+
import faiss
|
| 4 |
+
import numpy as np
|
| 5 |
+
import pickle
|
| 6 |
+
from flask import Flask, request, jsonify
|
|
|
|
|
|
|
| 7 |
from flask_cors import CORS
|
| 8 |
import google.generativeai as genai
|
| 9 |
import firebase_admin
|
| 10 |
+
from firebase_admin import credentials, firestore
|
| 11 |
+
from dotenv import load_dotenv
|
| 12 |
+
|
| 13 |
+
load_dotenv()
|
|
|
|
| 14 |
|
| 15 |
+
# --------- Flask Setup ---------
|
| 16 |
app = Flask(__name__)
|
| 17 |
CORS(app)
|
| 18 |
|
| 19 |
+
# --------- Firebase Initialization ---------
|
| 20 |
+
cred_json = os.environ.get("FIREBASE")
|
| 21 |
+
if cred_json:
|
| 22 |
+
cred = credentials.Certificate(json.loads(cred_json))
|
| 23 |
+
firebase_admin.initialize_app(cred)
|
| 24 |
+
fs = firestore.client()
|
| 25 |
+
|
| 26 |
+
# --------- Gemini Configuration ---------
|
| 27 |
+
genai.configure(api_key=os.getenv("Gemini"))
|
| 28 |
+
chat_model = genai.GenerativeModel("gemini-2.0-flash-thinking-exp")
|
| 29 |
+
embed_model = genai.EmbeddingModel("models/embedding-001")
|
| 30 |
+
|
| 31 |
+
# --------- Paths for Cached Index ---------
|
| 32 |
+
INDEX_PATH = "vector.index"
|
| 33 |
+
DOCS_PATH = "documents.pkl"
|
| 34 |
+
|
| 35 |
+
# --------- Load Documents from Firestore ---------
|
| 36 |
+
def fetch_documents():
|
| 37 |
+
documents = []
|
| 38 |
+
|
| 39 |
+
for doc in fs.collection("participants").stream():
|
| 40 |
+
d = doc.to_dict()
|
| 41 |
+
documents.append(f"{d.get('name')} ({d.get('enterpriseName')}), sector: {d.get('sector')}, stage: {d.get('stage')}, type: {d.get('developmentType')}.")
|
| 42 |
+
|
| 43 |
+
for doc in fs.collection("interventions").stream():
|
| 44 |
+
d = doc.to_dict()
|
| 45 |
+
for item in d.get("interventions", []):
|
| 46 |
+
documents.append(f"Intervention: {item.get('title')} under {d.get('area')}.")
|
| 47 |
+
|
| 48 |
+
for doc in fs.collection("feedbacks").stream():
|
| 49 |
+
d = doc.to_dict()
|
| 50 |
+
documents.append(f"Feedback on {d.get('interventionTitle')} by {d.get('smeName')}: {d.get('comment')}")
|
| 51 |
+
|
| 52 |
+
for doc in fs.collection("complianceDocuments").stream():
|
| 53 |
+
d = doc.to_dict()
|
| 54 |
+
documents.append(f"Compliance document '{d.get('documentType')}' for {d.get('participantName')} is {d.get('status')} and expires on {d.get('expiryDate')}.")
|
| 55 |
|
| 56 |
+
for doc in fs.collection("assignedInterventions").stream():
|
| 57 |
+
d = doc.to_dict()
|
| 58 |
+
documents.append(f"Assigned intervention '{d.get('interventionTitle')}' for {d.get('smeName')} by consultant {d.get('consultantId')} with status {d.get('status')}.")
|
| 59 |
+
|
| 60 |
+
for doc in fs.collection("consultants").stream():
|
| 61 |
+
d = doc.to_dict()
|
| 62 |
+
documents.append(f"Consultant {d.get('name')} with expertise in {', '.join(d.get('expertise', []))} and rating {d.get('rating')}.")
|
| 63 |
+
|
| 64 |
+
return documents
|
| 65 |
+
|
| 66 |
+
# --------- FAISS Caching ---------
|
| 67 |
+
def build_or_load_index():
|
| 68 |
+
if os.path.exists(INDEX_PATH) and os.path.exists(DOCS_PATH):
|
| 69 |
+
print("Loading FAISS index and documents from cache...")
|
| 70 |
+
with open(DOCS_PATH, "rb") as f:
|
| 71 |
+
documents = pickle.load(f)
|
| 72 |
+
index = faiss.read_index(INDEX_PATH)
|
| 73 |
else:
|
| 74 |
+
print("Building FAISS index...")
|
| 75 |
+
documents = fetch_documents()
|
| 76 |
+
embeddings = np.array(get_embeddings(documents), dtype="float32")
|
| 77 |
+
dimension = len(embeddings[0])
|
| 78 |
+
index = faiss.IndexFlatIP(dimension)
|
| 79 |
+
index.add(embeddings)
|
| 80 |
|
| 81 |
+
# Save cache
|
| 82 |
+
with open(DOCS_PATH, "wb") as f:
|
| 83 |
+
pickle.dump(documents, f)
|
| 84 |
+
faiss.write_index(index, INDEX_PATH)
|
| 85 |
+
return documents, index
|
| 86 |
+
|
| 87 |
+
def get_embeddings(texts):
|
| 88 |
+
response = embed_model.get_embeddings(texts=texts)
|
| 89 |
+
return [e.values for e in response.embeddings]
|
| 90 |
+
|
| 91 |
+
documents, index = build_or_load_index()
|
| 92 |
+
|
| 93 |
+
# --------- Helper Function: RAG Chat ---------
|
| 94 |
+
def retrieve_and_respond(user_query, top_k=3):
|
| 95 |
+
query_embedding = np.array(get_embeddings([user_query]), dtype="float32")
|
| 96 |
+
distances, indices = index.search(query_embedding, top_k)
|
| 97 |
+
retrieved_docs = [documents[i] for i in indices[0]]
|
| 98 |
+
|
| 99 |
+
prompt = (
|
| 100 |
+
"Use the following context to answer the question.\n\n"
|
| 101 |
+
+ "\n\n".join(retrieved_docs)
|
| 102 |
+
+ f"\n\nQuestion: {user_query}\nAnswer:"
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
chat = chat_model.start_chat()
|
| 106 |
+
response = chat.send_message(prompt)
|
| 107 |
+
return getattr(response, "text", response.last.text)
|
| 108 |
+
|
| 109 |
+
# --------- Flask Chat Endpoint ---------
|
| 110 |
+
@app.route("/chat", methods=["POST"])
|
| 111 |
+
def chat():
|
| 112 |
+
data = request.get_json(force=True)
|
| 113 |
+
user_query = data.get("user_query")
|
| 114 |
|
| 115 |
+
if not user_query:
|
| 116 |
+
return jsonify({"error": "Missing user_query"}), 400
|
|
|
|
|
|
|
| 117 |
|
| 118 |
+
try:
|
| 119 |
+
reply = retrieve_and_respond(user_query)
|
| 120 |
+
return jsonify({"reply": reply})
|
| 121 |
+
except Exception as e:
|
| 122 |
+
return jsonify({"error": str(e)}), 500
|
| 123 |
|
| 124 |
+
# --------- Run Flask Server ---------
|
| 125 |
+
if __name__ == "__main__":
|
| 126 |
+
app.run(host="0.0.0.0", port=7860, debug=True)
|