rairo commited on
Commit
9e1838c
Β·
verified Β·
1 Parent(s): 2cafbfb

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +215 -90
main.py CHANGED
@@ -1,11 +1,16 @@
1
  import os
2
  import json
 
 
 
 
3
  from flask import Flask, request, jsonify
4
  from flask_cors import CORS
5
  from dotenv import load_dotenv
6
 
7
- # Firebase
8
- from firebase_admin import credentials, firestore, storage, initialize_app
 
9
 
10
  # Exa.ai
11
  from exa_py import Exa
@@ -13,129 +18,249 @@ from exa_py import Exa
13
  # Google GenAI (Gemini)
14
  from google import genai
15
 
16
- # (Optional) Faiss for behavioral embeddings
17
- import faiss
18
-
19
  # ─── Load environment ───────────────────────────────────────────────────────────
20
  load_dotenv()
21
- EXA_API_KEY = os.getenv("EXA_API_KEY")
22
- GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
23
- FIREBASE_JSON = os.getenv("FIREBASE")
24
- STORAGE_BUCKET = os.getenv("Firebase_Storage")
 
25
 
26
- if not (EXA_API_KEY and GEMINI_API_KEY and FIREBASE_JSON and STORAGE_BUCKET):
27
- raise RuntimeError("Missing one or more required env vars: EXA_API_KEY, GEMINI_API_KEY, FIREBASE, Firebase_Storage")
28
 
29
- # ─── Initialize Firebase ───────────────────────────────────────────────────────
30
  cred = credentials.Certificate(json.loads(FIREBASE_JSON))
31
- initialize_app(cred, {"storageBucket": STORAGE_BUCKET})
 
 
 
32
  fs = firestore.client()
33
  bucket = storage.bucket()
34
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  # ─── Initialize Exa.ai ─────────────────────────────────────────────────────────
36
- exa = Exa(EXA_API_KEY) # [oai_citation:0‑docs.exa.ai](https://docs.exa.ai/reference/quickstart)
37
 
38
  # ─── Initialize Gemini Client ─────────────────────────────────────────────────
39
- client = genai.Client(api_key=GEMINI_API_KEY) # [oai_citation:1‑Google Cloud](https://cloud.google.com/vertex-ai/generative-ai/docs/sdks/overview?utm_source=chatgpt.com)
40
  MODEL = "gemini-2.0-flash-001"
41
 
42
- # ─── (Optional) Setup a Faiss index for future behavioral targeting ─────────────
43
- # dim = 1536 # e.g., if you use a 1536‑dim embedding model
44
- # faiss_index = faiss.IndexFlatL2(dim)
45
-
46
  # ─── Flask App ────────────────────────────────────────────────────────────────
47
  app = Flask(__name__)
48
  CORS(app)
49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  @app.route("/chat", methods=["POST"])
51
  def chat():
52
- payload = request.get_json()
53
- user_message = payload.get("message", "").strip()
54
- user_ip = request.remote_addr or "0.0.0.0"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
 
56
- # 1️⃣ Classify intent
57
  classify_prompt = (
58
- "Categorize the user's intent into one or both:\n"
59
- " - self-help\n"
60
- " - product_search\n"
61
- "Return as a JSON list, e.g.: [\"self-help\"] or [\"product_search\"] or [\"self-help\",\"product_search\"]\n\n"
62
- f"User message: \"{user_message}\""
63
- )
64
- classify_resp = client.models.generate_content(
65
- model=MODEL,
66
- contents=classify_prompt
67
  )
 
68
  try:
69
  intents = json.loads(classify_resp.text)
70
- except json.JSONDecodeError:
71
- # fallback: treat as a catch‑all
72
  intents = ["self-help"]
73
 
74
- response_parts = []
75
 
76
- # 2️⃣ If self‑help requested, generate guidance
77
  if "self-help" in intents:
78
- help_prompt = (
79
- "You are a friendly assistant. Provide clear, step‑by‑step guidance for:\n\n"
80
- f"\"{user_message}\""
81
- )
82
- help_resp = client.models.generate_content(
83
- model=MODEL,
84
- contents=help_prompt
85
- )
86
- response_parts.append(help_resp.text.strip())
87
-
88
- # Also dynamically lookup β€œwhat to buy” where applicable
89
- # e.g. for β€œI want to bake a cake” β†’ search β€œbake a cake ingredients”
90
- search_query = user_message + " shop links for supplies"
91
- exa_results = exa.search_and_contents(
92
- search_query,
93
- type="auto",
94
- text=True
95
- )
96
- # take top 3 links
97
- links = [r.url for r in exa_results.results[:3]]
98
- suggestion_text = (
99
- "If you need to pick up supplies, here are some helpful links:\n" +
100
- "\n".join(f"- {url}" for url in links)
101
- )
102
- response_parts.append(suggestion_text)
103
 
104
- # 3️⃣ If pure product_search requested, search Exa and wrap conversationally
 
 
 
 
 
 
 
105
  if "product_search" in intents and "self-help" not in intents:
106
- exa_results = exa.search_and_contents(
107
- user_message,
108
- type="auto",
109
- text=True
110
- )
111
- links = [r.url for r in exa_results.results[:5]]
112
  rec_prompt = (
113
- "You are a helpful shopping assistant. A user is looking for:\n\n"
114
- f"\"{user_message}\"\n\n"
115
- "From these links:\n" +
116
- "\n".join(links) +
117
- "\n\n"
118
- "Suggest the most relevant products in a friendly, conversational way. if the user does not provide specifics ie budget, brand etc you provide the suggestions. dont prompt for more information. also always return the links."
119
  )
120
- rec_resp = client.models.generate_content(
121
- model=MODEL,
122
- contents=rec_prompt
123
- )
124
- response_parts.append(rec_resp.text.strip())
125
 
126
- # 4️⃣ Fallback if nothing matched
127
- if not response_parts:
128
- default_resp = client.models.generate_content(
129
- model=MODEL,
130
- contents=f"Assist the user with: \"{user_message}\""
131
- )
132
- response_parts.append(default_resp.text.strip())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
 
134
- # 5️⃣ Combine and return
135
- final_text = "\n\n".join(response_parts)
136
- return jsonify({"response": final_text})
 
 
 
 
 
 
 
 
137
 
 
 
 
 
 
 
 
 
 
 
 
 
138
 
139
  if __name__ == "__main__":
140
- # Host on all interfaces, port 7860
141
  app.run(host="0.0.0.0", port=7860, debug=True)
 
1
  import os
2
  import json
3
+ import csv
4
+ from io import StringIO
5
+ from functools import wraps
6
+ from datetime import datetime
7
  from flask import Flask, request, jsonify
8
  from flask_cors import CORS
9
  from dotenv import load_dotenv
10
 
11
+ # Firebase Admin SDK
12
+ import firebase_admin
13
+ from firebase_admin import credentials, auth, firestore, storage, db as firebase_db, initialize_app
14
 
15
  # Exa.ai
16
  from exa_py import Exa
 
18
  # Google GenAI (Gemini)
19
  from google import genai
20
 
 
 
 
21
  # ─── Load environment ───────────────────────────────────────────────────────────
22
  load_dotenv()
23
+ EXA_API_KEY = os.getenv("EXA_API_KEY")
24
+ GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
25
+ FIREBASE_JSON = os.getenv("FIREBASE")
26
+ FIREBASE_DB_URL = os.getenv("FIREBASE_DB_URL")
27
+ STORAGE_BUCKET = os.getenv("Firebase_Storage")
28
 
29
+ if not (EXA_API_KEY and GEMINI_API_KEY and FIREBASE_JSON and FIREBASE_DB_URL and STORAGE_BUCKET):
30
+ raise RuntimeError("Missing one or more required env vars: EXA_API_KEY, GEMINI_API_KEY, FIREBASE, FIREBASE_DB_URL, Firebase_Storage")
31
 
32
+ # ─── Initialize Firebase (Auth, Firestore, Realtime DB, Storage) ─────────────
33
  cred = credentials.Certificate(json.loads(FIREBASE_JSON))
34
+ initialize_app(cred, {
35
+ "storageBucket": STORAGE_BUCKET,
36
+ "databaseURL": FIREBASE_DB_URL
37
+ })
38
  fs = firestore.client()
39
  bucket = storage.bucket()
40
 
41
+ # ─── Ensure dummy admin exists ─────────────────────────────────────────────────
42
+ try:
43
+ admin_user = auth.get_user_by_email("rairorr@gmail.com")
44
+ except firebase_admin._auth_utils.UserNotFoundError:
45
+ admin_user = auth.create_user(
46
+ email="rairorr@gmail.com",
47
+ email_verified=True,
48
+ password="123456",
49
+ display_name="Admin"
50
+ )
51
+ auth.set_custom_user_claims(admin_user.uid, {"admin": True})
52
+
53
  # ─── Initialize Exa.ai ─────────────────────────────────────────────────────────
54
+ exa = Exa(EXA_API_KEY)
55
 
56
  # ─── Initialize Gemini Client ─────────────────────────────────────────────────
57
+ client = genai.Client(api_key=GEMINI_API_KEY)
58
  MODEL = "gemini-2.0-flash-001"
59
 
 
 
 
 
60
  # ─── Flask App ────────────────────────────────────────────────────────────────
61
  app = Flask(__name__)
62
  CORS(app)
63
 
64
+ # ─── Helpers ──────────────────────────────────────────────────────────────────
65
+ def verify_id_token(f):
66
+ @wraps(f)
67
+ def wrapper(*args, **kwargs):
68
+ auth_header = request.headers.get("Authorization", "")
69
+ if not auth_header.startswith("Bearer "):
70
+ return jsonify({"error": "Missing or invalid Authorization header"}), 401
71
+ id_token = auth_header.split(" ")[1]
72
+ try:
73
+ decoded = auth.verify_id_token(id_token)
74
+ request.user = decoded
75
+ except Exception:
76
+ return jsonify({"error": "Invalid or expired token"}), 401
77
+ return f(*args, **kwargs)
78
+ return wrapper
79
+
80
+ def require_admin(f):
81
+ @wraps(f)
82
+ def wrapper(*args, **kwargs):
83
+ if not getattr(request, "user", None) or not request.user.get("admin", False):
84
+ return jsonify({"error": "Admin privileges required"}), 403
85
+ return f(*args, **kwargs)
86
+ return wrapper
87
+
88
+ def increment_query_count(ip):
89
+ doc = fs.collection("ip_queries").document(ip)
90
+ snap = doc.get()
91
+ if snap.exists:
92
+ count = snap.get("count") + 1
93
+ doc.update({"count": count})
94
+ else:
95
+ count = 1
96
+ doc.set({"count": 1})
97
+ return count
98
+
99
+ def store_chat(ip, message, response):
100
+ """ Store each chat message/response pair in Realtime Database """
101
+ ref = firebase_db.reference("chats")
102
+ ref.push({
103
+ "ip": ip,
104
+ "message": message,
105
+ "response": response,
106
+ "timestamp": datetime.utcnow().isoformat()
107
+ })
108
+
109
+ # ─── Routes ───────────────────────────────────────────────────────────────────
110
+
111
  @app.route("/chat", methods=["POST"])
112
  def chat():
113
+ user_ip = request.remote_addr or "0.0.0.0"
114
+ count = increment_query_count(user_ip)
115
+ need_login = count > 5
116
+
117
+ # optional user auth
118
+ token = request.headers.get("Authorization", "")
119
+ user_info = None
120
+ if token.startswith("Bearer "):
121
+ try:
122
+ user_info = auth.verify_id_token(token.split(" ")[1])
123
+ except:
124
+ user_info = None
125
+
126
+ if need_login and not user_info:
127
+ return jsonify({
128
+ "error": "Please log in to continue after 5 free queries",
129
+ "login_required": True
130
+ }), 403
131
+
132
+ data = request.get_json()
133
+ user_message = data.get("message", "").strip()
134
 
135
+ # 1) Classify intent
136
  classify_prompt = (
137
+ "Categorize the user's intent as JSON list of one or both:\n"
138
+ "['self-help','product_search']\n\n"
139
+ f"User: \"{user_message}\""
 
 
 
 
 
 
140
  )
141
+ classify_resp = client.models.generate_content(model=MODEL, contents=classify_prompt)
142
  try:
143
  intents = json.loads(classify_resp.text)
144
+ except:
 
145
  intents = ["self-help"]
146
 
147
+ parts = []
148
 
149
+ # 2) Self-help
150
  if "self-help" in intents:
151
+ help_prompt = f"You are a helpful assistant. Give step-by-step guidance for: \"{user_message}\""
152
+ help_resp = client.models.generate_content(model=MODEL, contents=help_prompt)
153
+ parts.append(help_resp.text.strip())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
 
155
+ # dynamic product links
156
+ search_q = user_message + " ingredients"
157
+ exa_res = exa.search_and_contents(search_q, type="auto", text=True)
158
+ links = [r.url for r in exa_res.results[:3]]
159
+ if links:
160
+ parts.append("Here are some useful links to get supplies:\n" + "\n".join(f"- {u}" for u in links))
161
+
162
+ # 3) Product search only
163
  if "product_search" in intents and "self-help" not in intents:
164
+ exa_res = exa.search_and_contents(user_message, type="auto", text=True)
165
+ links = [r.url for r in exa_res.results[:5]]
 
 
 
 
166
  rec_prompt = (
167
+ "You are a shopping assistant. Suggest products for:\n"
168
+ f"\"{user_message}\"\n"
169
+ "Always include links:\n" + "\n".join(links)
 
 
 
170
  )
171
+ rec_resp = client.models.generate_content(model=MODEL, contents=rec_prompt)
172
+ parts.append(rec_resp.text.strip())
 
 
 
173
 
174
+ # 4) Fallback
175
+ if not parts:
176
+ default = client.models.generate_content(model=MODEL, contents=f"Help the user with: \"{user_message}\"")
177
+ parts.append(default.text.strip())
178
+
179
+ final_response = "\n\n".join(parts)
180
+
181
+ # Store in Realtime Database
182
+ store_chat(user_ip, user_message, final_response)
183
+
184
+ return jsonify({"response": final_response})
185
+
186
+ @app.route("/auth/signup", methods=["POST"])
187
+ def signup():
188
+ data = request.get_json()
189
+ email = data.get("email")
190
+ pwd = data.get("password")
191
+ try:
192
+ user = auth.create_user(email=email, password=pwd)
193
+ fs.collection("users").document(user.uid).set({
194
+ "preferences": {},
195
+ "email": email
196
+ })
197
+ return jsonify({"message": "User created"}), 201
198
+ except Exception as e:
199
+ return jsonify({"error": str(e)}), 400
200
+
201
+ @app.route("/dashboard", methods=["GET"])
202
+ @verify_id_token
203
+ def user_dashboard():
204
+ uid = request.user["uid"]
205
+ doc = fs.collection("users").document(uid).get()
206
+ if not doc.exists:
207
+ return jsonify({"error": "User not found"}), 404
208
+ data = doc.to_dict()
209
+ return jsonify({
210
+ "email": request.user.get("email"),
211
+ "preferences": data.get("preferences", {})
212
+ })
213
+
214
+ @app.route("/dashboard/preferences", methods=["POST"])
215
+ @verify_id_token
216
+ def update_preferences():
217
+ uid = request.user["uid"]
218
+ prefs = request.get_json().get("preferences", {})
219
+ fs.collection("users").document(uid).update({"preferences": prefs})
220
+ return jsonify({"message": "Preferences updated"})
221
+
222
+ # ── Admin Routes ──────────────────────────────────────────────────────────────
223
+
224
+ @app.route("/admin/upload_links", methods=["POST"])
225
+ @verify_id_token
226
+ @require_admin
227
+ def upload_links():
228
+ if "file" not in request.files:
229
+ return jsonify({"error": "CSV file required"}), 400
230
+ f = request.files["file"]
231
+ stream = StringIO(f.stream.read().decode("utf-8"))
232
+ reader = csv.DictReader(stream)
233
+ batch = fs.batch()
234
+ for row in reader:
235
+ doc = fs.collection("sponsoredLinks").document()
236
+ batch.set(doc, {"keyword": row.get("keyword"), "url": row.get("url")})
237
+ batch.commit()
238
+ return jsonify({"message": "Links uploaded from CSV"})
239
 
240
+ @app.route("/admin/add_link", methods=["POST"])
241
+ @verify_id_token
242
+ @require_admin
243
+ def add_link():
244
+ data = request.get_json()
245
+ keyword = data.get("keyword")
246
+ url = data.get("url")
247
+ if not (keyword and url):
248
+ return jsonify({"error": "Both 'keyword' and 'url' are required"}), 400
249
+ fs.collection("sponsoredLinks").add({"keyword": keyword, "url": url})
250
+ return jsonify({"message": "Link added successfully"})
251
 
252
+ @app.route("/admin/stats", methods=["GET"])
253
+ @verify_id_token
254
+ @require_admin
255
+ def stats():
256
+ users = auth.list_users().users
257
+ total_users = len(users)
258
+ ip_docs = fs.collection("ip_queries").stream()
259
+ total_queries = sum(doc.get("count", 0) for doc in ip_docs)
260
+ return jsonify({
261
+ "total_users": total_users,
262
+ "total_queries": total_queries
263
+ })
264
 
265
  if __name__ == "__main__":
 
266
  app.run(host="0.0.0.0", port=7860, debug=True)