Update app.py
Browse files
app.py
CHANGED
@@ -1,480 +1,447 @@
|
|
1 |
-
import os
|
2 |
-
import re
|
3 |
-
import ast
|
4 |
-
import json
|
5 |
-
import requests
|
6 |
-
import pandas as pd
|
7 |
-
import sqlite3
|
8 |
-
import logging
|
9 |
-
|
10 |
-
from flask import (
|
11 |
-
Flask,
|
12 |
-
request,
|
13 |
-
jsonify,
|
14 |
-
render_template,
|
15 |
-
redirect,
|
16 |
-
url_for,
|
17 |
-
session
|
18 |
-
)
|
19 |
-
from flask_session import Session
|
20 |
-
from dotenv import load_dotenv
|
21 |
-
|
22 |
-
# Load environment variables from a .env file
|
23 |
-
load_dotenv()
|
24 |
-
|
25 |
-
# Configure Logging
|
26 |
-
logging.basicConfig(level=logging.INFO)
|
27 |
-
logger = logging.getLogger(__name__)
|
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 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
""
|
77 |
-
cur.execute(
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
]
|
105 |
-
for
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
"
|
204 |
-
"
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
-
|
243 |
-
|
244 |
-
|
245 |
-
|
246 |
-
|
247 |
-
|
248 |
-
|
249 |
-
|
250 |
-
|
251 |
-
|
252 |
-
|
253 |
-
|
254 |
-
|
255 |
-
|
256 |
-
|
257 |
-
"""
|
258 |
-
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
-
|
263 |
-
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
|
268 |
-
#
|
269 |
-
|
270 |
-
|
271 |
-
|
272 |
-
|
273 |
-
|
274 |
-
|
275 |
-
|
276 |
-
|
277 |
-
#
|
278 |
-
|
279 |
-
|
280 |
-
|
281 |
-
|
282 |
-
|
283 |
-
|
284 |
-
|
285 |
-
|
286 |
-
|
287 |
-
|
288 |
-
|
289 |
-
|
290 |
-
|
291 |
-
|
292 |
-
|
293 |
-
|
294 |
-
|
295 |
-
|
296 |
-
|
297 |
-
|
298 |
-
|
299 |
-
|
300 |
-
|
301 |
-
|
302 |
-
|
303 |
-
|
304 |
-
|
305 |
-
|
306 |
-
|
307 |
-
#
|
308 |
-
|
309 |
-
|
310 |
-
|
311 |
-
|
312 |
-
|
313 |
-
|
314 |
-
|
315 |
-
|
316 |
-
|
317 |
-
|
318 |
-
|
319 |
-
|
320 |
-
|
321 |
-
|
322 |
-
|
323 |
-
|
324 |
-
|
325 |
-
|
326 |
-
|
327 |
-
|
328 |
-
|
329 |
-
|
330 |
-
|
331 |
-
|
332 |
-
|
333 |
-
|
334 |
-
|
335 |
-
|
336 |
-
|
337 |
-
|
338 |
-
|
339 |
-
|
340 |
-
|
341 |
-
|
342 |
-
|
343 |
-
|
344 |
-
|
345 |
-
for
|
346 |
-
|
347 |
-
|
348 |
-
|
349 |
-
|
350 |
-
|
351 |
-
|
352 |
-
|
353 |
-
|
354 |
-
|
355 |
-
|
356 |
-
|
357 |
-
|
358 |
-
|
359 |
-
|
360 |
-
|
361 |
-
|
362 |
-
|
363 |
-
|
364 |
-
|
365 |
-
|
366 |
-
|
367 |
-
|
368 |
-
|
369 |
-
|
370 |
-
|
371 |
-
|
372 |
-
|
373 |
-
|
374 |
-
|
375 |
-
|
376 |
-
|
377 |
-
|
378 |
-
|
379 |
-
|
380 |
-
|
381 |
-
|
382 |
-
|
383 |
-
|
384 |
-
|
385 |
-
|
386 |
-
|
387 |
-
|
388 |
-
|
389 |
-
|
390 |
-
|
391 |
-
|
392 |
-
|
393 |
-
|
394 |
-
|
395 |
-
|
396 |
-
|
397 |
-
|
398 |
-
|
399 |
-
|
400 |
-
|
401 |
-
|
402 |
-
|
403 |
-
|
404 |
-
|
405 |
-
|
406 |
-
|
407 |
-
"""
|
408 |
-
|
409 |
-
|
410 |
-
|
411 |
-
"
|
412 |
-
"
|
413 |
-
|
414 |
-
|
415 |
-
|
416 |
-
|
417 |
-
|
418 |
-
|
419 |
-
|
420 |
-
|
421 |
-
|
422 |
-
|
423 |
-
|
424 |
-
""
|
425 |
-
|
426 |
-
|
427 |
-
|
428 |
-
|
429 |
-
|
430 |
-
|
431 |
-
|
432 |
-
|
433 |
-
|
434 |
-
|
435 |
-
|
436 |
-
|
437 |
-
|
438 |
-
|
439 |
-
|
440 |
-
|
441 |
-
|
442 |
-
|
443 |
-
|
444 |
-
|
445 |
-
|
446 |
-
|
447 |
-
|
448 |
-
return f"[Gemini Error] Invalid JSON response: {e}"
|
449 |
-
|
450 |
-
if resp.status_code != 200:
|
451 |
-
logger.error(f"Gemini API returned error {resp.status_code}: {data}")
|
452 |
-
return f"[Gemini Error {resp.status_code}] {json.dumps(data, indent=2)}"
|
453 |
-
|
454 |
-
# Parse the "candidates" structure
|
455 |
-
candidates = data.get("candidates", [])
|
456 |
-
if not candidates:
|
457 |
-
logger.error(f"No candidates received from Gemini API: {data}")
|
458 |
-
return f"No candidates received. Debug JSON: {json.dumps(data, indent=2)}"
|
459 |
-
|
460 |
-
first_candidate = candidates[0]
|
461 |
-
content = first_candidate.get("content", {})
|
462 |
-
parts = content.get("parts", [])
|
463 |
-
if not parts:
|
464 |
-
logger.error(f"No 'parts' found in candidate content: {data}")
|
465 |
-
return f"No 'parts' found in candidate content. Debug JSON: {json.dumps(data, indent=2)}"
|
466 |
-
|
467 |
-
assistant_reply = parts[0].get("text", "(No text found in the response)")
|
468 |
-
logger.info(f"Gemini Assistant Reply: {assistant_reply}")
|
469 |
-
return assistant_reply
|
470 |
-
|
471 |
-
##############################################################################
|
472 |
-
# MAIN
|
473 |
-
##############################################################################
|
474 |
-
def main():
|
475 |
-
create_db_from_csv(CSV_PATH, DB_PATH)
|
476 |
-
logger.info("Starting Flask server at http://127.0.0.1:5000")
|
477 |
-
app.run(debug=True)
|
478 |
-
|
479 |
-
if __name__ == "__main__":
|
480 |
-
main()
|
|
|
1 |
+
import os
|
2 |
+
import re
|
3 |
+
import ast
|
4 |
+
import json
|
5 |
+
import requests
|
6 |
+
import pandas as pd
|
7 |
+
import sqlite3
|
8 |
+
import logging
|
9 |
+
|
10 |
+
from flask import (
|
11 |
+
Flask,
|
12 |
+
request,
|
13 |
+
jsonify,
|
14 |
+
render_template,
|
15 |
+
redirect,
|
16 |
+
url_for,
|
17 |
+
session
|
18 |
+
)
|
19 |
+
from flask_session import Session
|
20 |
+
from dotenv import load_dotenv
|
21 |
+
|
22 |
+
# Load environment variables from a .env file
|
23 |
+
load_dotenv()
|
24 |
+
|
25 |
+
# Configure Logging
|
26 |
+
logging.basicConfig(level=logging.INFO)
|
27 |
+
logger = logging.getLogger(__name__)
|
28 |
+
|
29 |
+
CSV_PATH = "All_Categories.csv" # Path to your large CSV
|
30 |
+
DB_PATH = "products.db" # SQLite database file
|
31 |
+
TABLE_NAME = "products"
|
32 |
+
|
33 |
+
# Securely load your Gemini API key from environment variables
|
34 |
+
GEMINI_API_KEY = os.getenv(GEMINI_API_KEY) # Ensure you set this in your .env file
|
35 |
+
|
36 |
+
if not GEMINI_API_KEY:
|
37 |
+
logger.error("Gemini API key not found. Please set GEMINI_API_KEY in your .env file.")
|
38 |
+
raise ValueError("Gemini API key not found. Please set GEMINI_API_KEY in your .env file.")
|
39 |
+
|
40 |
+
# Replace with the correct model name your account has access to
|
41 |
+
GEMINI_MODEL_NAME = "gemini-1.5-flash" # If invalid, try "gemini-1.5-pro"
|
42 |
+
GEMINI_ENDPOINT = f"https://generativelanguage.googleapis.com/v1beta/models/{GEMINI_MODEL_NAME}:generateContent"
|
43 |
+
|
44 |
+
|
45 |
+
def create_db_from_csv(csv_file, db_file):
|
46 |
+
if os.path.exists(db_file):
|
47 |
+
logger.info(f"Database '{db_file}' already exists. Skipping creation.")
|
48 |
+
return
|
49 |
+
|
50 |
+
logger.info(f"Creating SQLite DB from CSV: {csv_file} -> {db_file}")
|
51 |
+
df_iter = pd.read_csv(csv_file, chunksize=50000)
|
52 |
+
conn = sqlite3.connect(db_file)
|
53 |
+
cur = conn.cursor()
|
54 |
+
cur.execute(f"DROP TABLE IF EXISTS {TABLE_NAME}")
|
55 |
+
conn.commit()
|
56 |
+
|
57 |
+
create_sql = f"""
|
58 |
+
CREATE TABLE {TABLE_NAME} (
|
59 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
60 |
+
name TEXT,
|
61 |
+
image TEXT,
|
62 |
+
link TEXT,
|
63 |
+
ratings REAL,
|
64 |
+
no_of_ratings INTEGER,
|
65 |
+
discount_price TEXT,
|
66 |
+
actual_price TEXT,
|
67 |
+
search_terms TEXT,
|
68 |
+
recommended_5 TEXT,
|
69 |
+
category TEXT
|
70 |
+
);
|
71 |
+
"""
|
72 |
+
cur.execute(create_sql)
|
73 |
+
conn.commit()
|
74 |
+
|
75 |
+
# Create indexes to optimize search performance
|
76 |
+
cur.execute(f"CREATE INDEX idx_name ON {TABLE_NAME}(name);")
|
77 |
+
cur.execute(f"CREATE INDEX idx_category ON {TABLE_NAME}(category);")
|
78 |
+
cur.execute(f"CREATE INDEX idx_discount_price ON {TABLE_NAME}(discount_price);")
|
79 |
+
conn.commit()
|
80 |
+
|
81 |
+
chunk_idx = 0
|
82 |
+
for chunk in df_iter:
|
83 |
+
logger.info(f"Processing chunk {chunk_idx}...")
|
84 |
+
chunk_idx += 1
|
85 |
+
|
86 |
+
# Ensure all required columns are present
|
87 |
+
required_columns = [
|
88 |
+
"name","image","link","ratings","no_of_ratings",
|
89 |
+
"discount_price","actual_price","search_terms","recommended_5","category"
|
90 |
+
]
|
91 |
+
for col in required_columns:
|
92 |
+
if col not in chunk.columns:
|
93 |
+
chunk[col] = ""
|
94 |
+
chunk.fillna("", inplace=True)
|
95 |
+
records = chunk.to_dict(orient="records")
|
96 |
+
|
97 |
+
insert_sql = f"""
|
98 |
+
INSERT INTO {TABLE_NAME}
|
99 |
+
(name, image, link, ratings, no_of_ratings,
|
100 |
+
discount_price, actual_price, search_terms,
|
101 |
+
recommended_5, category)
|
102 |
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
103 |
+
"""
|
104 |
+
data_to_insert = []
|
105 |
+
for r in records:
|
106 |
+
# Clean and prepare data
|
107 |
+
try:
|
108 |
+
ratings = float(r["ratings"]) if r["ratings"] else 0.0
|
109 |
+
except ValueError:
|
110 |
+
ratings = 0.0
|
111 |
+
try:
|
112 |
+
no_of_ratings = int(r["no_of_ratings"]) if r["no_of_ratings"] else 0
|
113 |
+
except ValueError:
|
114 |
+
no_of_ratings = 0
|
115 |
+
row_tuple = (
|
116 |
+
str(r["name"]),
|
117 |
+
str(r["image"]),
|
118 |
+
str(r["link"]),
|
119 |
+
ratings,
|
120 |
+
no_of_ratings,
|
121 |
+
str(r["discount_price"]),
|
122 |
+
str(r["actual_price"]),
|
123 |
+
str(r["search_terms"]),
|
124 |
+
str(r["recommended_5"]),
|
125 |
+
str(r["category"])
|
126 |
+
)
|
127 |
+
data_to_insert.append(row_tuple)
|
128 |
+
|
129 |
+
cur.executemany(insert_sql, data_to_insert)
|
130 |
+
conn.commit()
|
131 |
+
|
132 |
+
conn.close()
|
133 |
+
logger.info("Database creation complete.")
|
134 |
+
|
135 |
+
app = Flask(__name__)
|
136 |
+
app.secret_key = os.getenv("FLASK_SECRET_KEY", "SECUREKEY")
|
137 |
+
app.config["SESSION_TYPE"] = "filesystem"
|
138 |
+
Session(app)
|
139 |
+
|
140 |
+
@app.route("/")
|
141 |
+
def index():
|
142 |
+
"""Home page with a search bar."""
|
143 |
+
return render_template("index.html")
|
144 |
+
|
145 |
+
@app.route("/autocomplete")
|
146 |
+
def autocomplete():
|
147 |
+
"""Return (id, name) JSON for substring search in 'name'."""
|
148 |
+
q = request.args.get("q", "").strip()
|
149 |
+
if not q:
|
150 |
+
return jsonify([])
|
151 |
+
|
152 |
+
conn = sqlite3.connect(DB_PATH)
|
153 |
+
cur = conn.cursor()
|
154 |
+
sql = f"""
|
155 |
+
SELECT id, name
|
156 |
+
FROM {TABLE_NAME}
|
157 |
+
WHERE LOWER(name) LIKE LOWER(?)
|
158 |
+
LIMIT 10
|
159 |
+
"""
|
160 |
+
wildcard = f"%{q}%"
|
161 |
+
rows = cur.execute(sql, (wildcard,)).fetchall()
|
162 |
+
conn.close()
|
163 |
+
|
164 |
+
results = [{"id": r[0], "name": r[1]} for r in rows]
|
165 |
+
return jsonify(results)
|
166 |
+
|
167 |
+
@app.route("/product/<int:item_id>")
|
168 |
+
def show_product(item_id):
|
169 |
+
"""Show product detail + top-5 recommended items from recommended_5."""
|
170 |
+
conn = sqlite3.connect(DB_PATH)
|
171 |
+
cur = conn.cursor()
|
172 |
+
|
173 |
+
sql = f"SELECT * FROM {TABLE_NAME} WHERE id=?"
|
174 |
+
row = cur.execute(sql, (item_id,)).fetchone()
|
175 |
+
if not row:
|
176 |
+
conn.close()
|
177 |
+
return "<h2>Product not found</h2>", 404
|
178 |
+
|
179 |
+
product = {
|
180 |
+
"id": row[0],
|
181 |
+
"name": row[1],
|
182 |
+
"image": row[2],
|
183 |
+
"link": row[3],
|
184 |
+
"ratings": row[4],
|
185 |
+
"no_of_ratings": row[5],
|
186 |
+
"discount_price": row[6],
|
187 |
+
"actual_price": row[7],
|
188 |
+
"search_terms": row[8],
|
189 |
+
"recommended_5": row[9],
|
190 |
+
"category": row[10]
|
191 |
+
}
|
192 |
+
|
193 |
+
# Parse recommended_5
|
194 |
+
try:
|
195 |
+
rec_list = ast.literal_eval(product["recommended_5"])
|
196 |
+
if not isinstance(rec_list, list):
|
197 |
+
rec_list = []
|
198 |
+
except:
|
199 |
+
rec_list = []
|
200 |
+
|
201 |
+
recommended_details = []
|
202 |
+
for rec_name in rec_list[:5]:
|
203 |
+
sql_rec = f"SELECT * FROM {TABLE_NAME} WHERE name LIKE ? LIMIT 1"
|
204 |
+
rec_row = cur.execute(sql_rec, (f"%{rec_name}%",)).fetchone()
|
205 |
+
if rec_row:
|
206 |
+
recommended_details.append({
|
207 |
+
"id": rec_row[0],
|
208 |
+
"name": rec_row[1],
|
209 |
+
"image": rec_row[2],
|
210 |
+
"link": rec_row[3],
|
211 |
+
"discount_price": rec_row[6]
|
212 |
+
})
|
213 |
+
|
214 |
+
conn.close()
|
215 |
+
return render_template("product.html",
|
216 |
+
product=product,
|
217 |
+
recommended=recommended_details)
|
218 |
+
|
219 |
+
@app.route("/rag")
|
220 |
+
def rag_index():
|
221 |
+
"""RAG Chat page storing conversation in session['rag_chat']. """
|
222 |
+
if "rag_chat" not in session:
|
223 |
+
session["rag_chat"] = []
|
224 |
+
return render_template("rag.html", chat_history=session["rag_chat"])
|
225 |
+
|
226 |
+
@app.route("/rag/query", methods=["POST"])
|
227 |
+
def rag_query():
|
228 |
+
"""
|
229 |
+
Process user input with an in-depth approach:
|
230 |
+
- Dynamically extract brands, product types, and price limits from the query.
|
231 |
+
- Perform precise DB filtering based on extracted parameters.
|
232 |
+
- Construct a structured prompt for Gemini using the filtered results.
|
233 |
+
- Parse Gemini's response and update the conversation history.
|
234 |
+
"""
|
235 |
+
if "rag_chat" not in session:
|
236 |
+
session["rag_chat"] = []
|
237 |
+
|
238 |
+
user_input = request.form.get("rag_input", "").strip()
|
239 |
+
if not user_input:
|
240 |
+
return redirect(url_for("rag_index"))
|
241 |
+
|
242 |
+
session["rag_chat"].append(("user", user_input))
|
243 |
+
|
244 |
+
brand_keyword, product_type, price_val = extract_query_parameters(user_input)
|
245 |
+
|
246 |
+
matched_items = filter_database(brand_keyword, product_type, price_val)
|
247 |
+
|
248 |
+
db_context = build_db_context(matched_items, brand_keyword, product_type, price_val)
|
249 |
+
|
250 |
+
conversation_text = construct_prompt(session["rag_chat"], db_context)
|
251 |
+
|
252 |
+
gemini_response = gemini_generate_content(
|
253 |
+
api_key=GEMINI_API_KEY,
|
254 |
+
conversation_text=conversation_text
|
255 |
+
)
|
256 |
+
|
257 |
+
session["rag_chat"].append(("assistant", gemini_response))
|
258 |
+
return redirect(url_for("rag_index"))
|
259 |
+
|
260 |
+
def extract_query_parameters(user_query):
|
261 |
+
"""
|
262 |
+
Extract brand, product type, and price from the user's query dynamically.
|
263 |
+
"""
|
264 |
+
user_lower = user_query.lower()
|
265 |
+
|
266 |
+
# Extract price
|
267 |
+
price = None
|
268 |
+
# Look for patterns like "under 5000", "below 25k", etc.
|
269 |
+
price_match = re.search(r'(under|below)\s+₹?(\d+[kK]?)', user_lower)
|
270 |
+
if price_match:
|
271 |
+
price_str = price_match.group(2)
|
272 |
+
if price_str.lower().endswith('k'):
|
273 |
+
price = int(price_str[:-1]) * 1000
|
274 |
+
else:
|
275 |
+
price = int(price_str)
|
276 |
+
|
277 |
+
# Dynamically extract brands and product types from the database
|
278 |
+
conn = sqlite3.connect(DB_PATH)
|
279 |
+
cur = conn.cursor()
|
280 |
+
|
281 |
+
# Fetch distinct categories and search_terms to build dynamic keyword lists
|
282 |
+
cur.execute(f"SELECT DISTINCT category FROM {TABLE_NAME}")
|
283 |
+
categories = [row[0].lower() for row in cur.fetchall()]
|
284 |
+
|
285 |
+
cur.execute(f"SELECT DISTINCT search_terms FROM {TABLE_NAME}")
|
286 |
+
search_terms = [row[0].lower() for row in cur.fetchall()]
|
287 |
+
|
288 |
+
conn.close()
|
289 |
+
|
290 |
+
# Initialize variables
|
291 |
+
brand = None
|
292 |
+
product_type = None
|
293 |
+
|
294 |
+
# Check for product types in user query
|
295 |
+
for category in categories:
|
296 |
+
if category in user_lower:
|
297 |
+
product_type = category
|
298 |
+
break
|
299 |
+
|
300 |
+
# If not found in category, check search_terms
|
301 |
+
if not product_type:
|
302 |
+
for term in search_terms:
|
303 |
+
if term in user_lower:
|
304 |
+
product_type = term
|
305 |
+
break
|
306 |
+
|
307 |
+
# For brand, attempt to extract from the search_terms by splitting
|
308 |
+
possible_brands = set()
|
309 |
+
for term in search_terms:
|
310 |
+
words = term.split()
|
311 |
+
possible_brands.update(words)
|
312 |
+
|
313 |
+
possible_brands = list(possible_brands)
|
314 |
+
|
315 |
+
for b in possible_brands:
|
316 |
+
if b in user_lower:
|
317 |
+
brand = b
|
318 |
+
break
|
319 |
+
|
320 |
+
return brand, product_type, price
|
321 |
+
|
322 |
+
def filter_database(brand, product_type, price):
|
323 |
+
"""
|
324 |
+
Filter the database based on brand, product type, and price.
|
325 |
+
"""
|
326 |
+
conn = sqlite3.connect(DB_PATH)
|
327 |
+
cur = conn.cursor()
|
328 |
+
|
329 |
+
# Build dynamic SQL query
|
330 |
+
sql = f"SELECT id, name, discount_price, recommended_5 FROM {TABLE_NAME} WHERE 1=1"
|
331 |
+
params = []
|
332 |
+
|
333 |
+
if brand:
|
334 |
+
sql += " AND LOWER(name) LIKE ?"
|
335 |
+
params.append(f"%{brand}%")
|
336 |
+
if product_type:
|
337 |
+
sql += " AND LOWER(category) LIKE ?"
|
338 |
+
params.append(f"%{product_type}%")
|
339 |
+
if price:
|
340 |
+
# Clean the discount_price field to extract numerical value
|
341 |
+
# Assuming discount_price is stored as a string like "₹1,299"
|
342 |
+
sql += " AND CAST(REPLACE(REPLACE(discount_price, '₹', ''), ',', '') AS INTEGER) <= ?"
|
343 |
+
params.append(price)
|
344 |
+
|
345 |
+
# Limit to 5000 for performance; adjust as needed
|
346 |
+
sql += " LIMIT 5000"
|
347 |
+
|
348 |
+
rows = cur.execute(sql, tuple(params)).fetchall()
|
349 |
+
conn.close()
|
350 |
+
|
351 |
+
return rows
|
352 |
+
|
353 |
+
def build_db_context(matched_items, brand, product_type, price):
|
354 |
+
"""
|
355 |
+
Build a structured context string from matched database items.
|
356 |
+
"""
|
357 |
+
db_context = ""
|
358 |
+
if matched_items:
|
359 |
+
db_context += f"Found {len(matched_items)} items"
|
360 |
+
if price:
|
361 |
+
db_context += f" under ₹{price}"
|
362 |
+
if brand or product_type:
|
363 |
+
db_context += " matching your criteria"
|
364 |
+
db_context += ":\n"
|
365 |
+
|
366 |
+
# List up to 10 items for context
|
367 |
+
for item in matched_items[:10]:
|
368 |
+
item_name = item[1]
|
369 |
+
item_price = item[2]
|
370 |
+
db_context += f"- {item_name} at ₹{item_price}\n"
|
371 |
+
else:
|
372 |
+
db_context += "No matching items found in the database.\n"
|
373 |
+
|
374 |
+
return db_context
|
375 |
+
|
376 |
+
def construct_prompt(chat_history, db_context):
|
377 |
+
"""
|
378 |
+
Construct the prompt to send to Gemini, including conversation history and DB context.
|
379 |
+
"""
|
380 |
+
prompt = (
|
381 |
+
"You are an intelligent assistant that provides product recommendations based on the user's query and the available database.\n\n"
|
382 |
+
"Conversation so far:\n"
|
383 |
+
)
|
384 |
+
for speaker, message in chat_history:
|
385 |
+
prompt += f"{speaker.capitalize()}: {message}\n"
|
386 |
+
|
387 |
+
prompt += f"\nDatabase Context:\n{db_context}\n"
|
388 |
+
|
389 |
+
prompt += "Based on the above information, provide a helpful and concise answer to the user's query."
|
390 |
+
|
391 |
+
return prompt
|
392 |
+
|
393 |
+
def gemini_generate_content(api_key, conversation_text):
|
394 |
+
"""
|
395 |
+
Call the Gemini API's generateContent endpoint with the constructed prompt.
|
396 |
+
"""
|
397 |
+
url = f"{GEMINI_ENDPOINT}?key={api_key}"
|
398 |
+
|
399 |
+
payload = {
|
400 |
+
"contents": [
|
401 |
+
{
|
402 |
+
"parts": [{"text": conversation_text}]
|
403 |
+
}
|
404 |
+
]
|
405 |
+
}
|
406 |
+
|
407 |
+
headers = {"Content-Type": "application/json"}
|
408 |
+
try:
|
409 |
+
resp = requests.post(url, headers=headers, data=json.dumps(payload))
|
410 |
+
except Exception as e:
|
411 |
+
logger.error(f"Error during Gemini API request: {e}")
|
412 |
+
return f"[Gemini Error] Failed to connect to Gemini API: {e}"
|
413 |
+
|
414 |
+
try:
|
415 |
+
data = resp.json()
|
416 |
+
except Exception as e:
|
417 |
+
logger.error(f"Invalid JSON response from Gemini API: {e}")
|
418 |
+
return f"[Gemini Error] Invalid JSON response: {e}"
|
419 |
+
|
420 |
+
if resp.status_code != 200:
|
421 |
+
logger.error(f"Gemini API returned error {resp.status_code}: {data}")
|
422 |
+
return f"[Gemini Error {resp.status_code}] {json.dumps(data, indent=2)}"
|
423 |
+
|
424 |
+
# Parse the "candidates" structure
|
425 |
+
candidates = data.get("candidates", [])
|
426 |
+
if not candidates:
|
427 |
+
logger.error(f"No candidates received from Gemini API: {data}")
|
428 |
+
return f"No candidates received. Debug JSON: {json.dumps(data, indent=2)}"
|
429 |
+
|
430 |
+
first_candidate = candidates[0]
|
431 |
+
content = first_candidate.get("content", {})
|
432 |
+
parts = content.get("parts", [])
|
433 |
+
if not parts:
|
434 |
+
logger.error(f"No 'parts' found in candidate content: {data}")
|
435 |
+
return f"No 'parts' found in candidate content. Debug JSON: {json.dumps(data, indent=2)}"
|
436 |
+
|
437 |
+
assistant_reply = parts[0].get("text", "(No text found in the response)")
|
438 |
+
logger.info(f"Gemini Assistant Reply: {assistant_reply}")
|
439 |
+
return assistant_reply
|
440 |
+
|
441 |
+
def main():
|
442 |
+
create_db_from_csv(CSV_PATH, DB_PATH)
|
443 |
+
logger.info("Starting Flask server at http://127.0.0.1:5000")
|
444 |
+
app.run(debug=True)
|
445 |
+
|
446 |
+
if __name__ == "__main__":
|
447 |
+
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|