Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -44,7 +44,6 @@ except Exception as e:
|
|
| 44 |
|
| 45 |
def call_ai(prompt):
|
| 46 |
"""Try OpenRouter first, then local GPT‑2. Returns a simple generic question if all fail."""
|
| 47 |
-
# Try OpenRouter
|
| 48 |
openrouter_key = os.getenv("OPENROUTER_API_KEY")
|
| 49 |
if openrouter_key:
|
| 50 |
url = "https://openrouter.ai/api/v1/chat/completions"
|
|
@@ -207,7 +206,7 @@ def get_chat_history(session_id):
|
|
| 207 |
messages = list(snap.values())
|
| 208 |
return sorted(messages, key=lambda x: x.get("timestamp", ""))
|
| 209 |
|
| 210 |
-
# ---------- Step Builder with
|
| 211 |
user_sessions = {}
|
| 212 |
|
| 213 |
def is_start_project_request(text):
|
|
@@ -308,7 +307,6 @@ def process_step_by_step(session_id, message):
|
|
| 308 |
if msg_lower in ["none", "done", "no"]:
|
| 309 |
session["step"] = "asking_deep"
|
| 310 |
session["deep_index"] = 0
|
| 311 |
-
# Build prompt for first deep question
|
| 312 |
prompt = f"""You are an expert project estimator. Based on the following client requirements, ask the NEXT most important, specific, and open‑ended question to clarify the project details. Do not repeat what has already been answered. Ask about design, content, audience, integrations, or any missing critical detail. Keep your question concise (one sentence).
|
| 313 |
|
| 314 |
Current requirements:
|
|
@@ -401,11 +399,45 @@ Generated question:"""
|
|
| 401 |
if idx + 1 < len(qlist):
|
| 402 |
return qlist[idx+1]["question"]
|
| 403 |
else:
|
| 404 |
-
|
| 405 |
-
|
|
|
|
| 406 |
else:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 407 |
session["step"] = "asking_contact"
|
| 408 |
return "📞 **Please provide your mobile number** (e.g., 03001234567) – We'll use this to contact you."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 409 |
|
| 410 |
elif step == "asking_contact":
|
| 411 |
if "mobile" not in session:
|
|
@@ -447,6 +479,11 @@ Generated question:"""
|
|
| 447 |
deep_text = "\n\n📌 **Deep Dive Responses:**\n"
|
| 448 |
for key, val in deep_answers.items():
|
| 449 |
deep_text += f"• {key}: {val}\n"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 450 |
contact_text = f"\n\n📞 **Contact Details:**\n• Mobile: {req.get('mobile', '')}\n• Email: {req.get('email', '')}"
|
| 451 |
return f"""📋 **Your Project Proposal**
|
| 452 |
|
|
@@ -456,7 +493,7 @@ Generated question:"""
|
|
| 456 |
• E‑commerce: {'Yes' if req.get('ecommerce') else 'No'}
|
| 457 |
• Chatbot: {'Yes' if req.get('chatbot') else 'No'}
|
| 458 |
• SEO: {'Yes' if req.get('seo') else 'No'}
|
| 459 |
-
• Extras: {extra_display}{add_text}{deep_text}{contact_text}
|
| 460 |
|
| 461 |
💰 **Total Cost:** PKR {price:,}
|
| 462 |
⏱️ **Timeline:** {timeline} working days
|
|
@@ -490,6 +527,23 @@ We'll contact you within 24 hours. 🚀"""
|
|
| 490 |
|
| 491 |
return None
|
| 492 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 493 |
# ---------- Package details (fallback) ----------
|
| 494 |
def package_details(query):
|
| 495 |
q = query.lower()
|
|
@@ -516,7 +570,14 @@ def get_final_response(user_message, session_id):
|
|
| 516 |
emoji = {"pending":"⏳", "in-progress":"🔄", "completed":"✅", "declined":"❌"}.get(status, "❓")
|
| 517 |
msg = proj.get("admin_message", "")
|
| 518 |
extra = f"\n📝 **Admin note:** {msg}" if msg else ""
|
| 519 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 520 |
else:
|
| 521 |
return f"❌ Project ID `{pid}` not found."
|
| 522 |
|
|
|
|
| 44 |
|
| 45 |
def call_ai(prompt):
|
| 46 |
"""Try OpenRouter first, then local GPT‑2. Returns a simple generic question if all fail."""
|
|
|
|
| 47 |
openrouter_key = os.getenv("OPENROUTER_API_KEY")
|
| 48 |
if openrouter_key:
|
| 49 |
url = "https://openrouter.ai/api/v1/chat/completions"
|
|
|
|
| 206 |
messages = list(snap.values())
|
| 207 |
return sorted(messages, key=lambda x: x.get("timestamp", ""))
|
| 208 |
|
| 209 |
+
# ---------- Step Builder with Media Upload ----------
|
| 210 |
user_sessions = {}
|
| 211 |
|
| 212 |
def is_start_project_request(text):
|
|
|
|
| 307 |
if msg_lower in ["none", "done", "no"]:
|
| 308 |
session["step"] = "asking_deep"
|
| 309 |
session["deep_index"] = 0
|
|
|
|
| 310 |
prompt = f"""You are an expert project estimator. Based on the following client requirements, ask the NEXT most important, specific, and open‑ended question to clarify the project details. Do not repeat what has already been answered. Ask about design, content, audience, integrations, or any missing critical detail. Keep your question concise (one sentence).
|
| 311 |
|
| 312 |
Current requirements:
|
|
|
|
| 399 |
if idx + 1 < len(qlist):
|
| 400 |
return qlist[idx+1]["question"]
|
| 401 |
else:
|
| 402 |
+
# After additional questions, ask for media upload
|
| 403 |
+
session["step"] = "asking_media"
|
| 404 |
+
return "🖼️ **Do you want to add any additional text or images?** (Reply: Yes/No)\n\nIf Yes, a text area and image upload will appear. Type **skip** if none."
|
| 405 |
else:
|
| 406 |
+
session["step"] = "asking_media"
|
| 407 |
+
return "🖼️ **Do you want to add any additional text or images?** (Reply: Yes/No)\n\nIf Yes, a text area and image upload will appear. Type **skip** if none."
|
| 408 |
+
|
| 409 |
+
elif step == "asking_media":
|
| 410 |
+
if msg_lower in ["yes", "han"]:
|
| 411 |
+
session["waiting_for_media"] = True
|
| 412 |
+
session["media_text"] = ""
|
| 413 |
+
session["media_image"] = None
|
| 414 |
+
# The frontend will handle the actual upload via a separate API call.
|
| 415 |
+
# We'll send a special response that the frontend recognizes.
|
| 416 |
+
return "MEDIA_REQUEST|Please provide your additional notes in the text area below and/or upload an image.\n\n(After done, type **DONE** to finish.)"
|
| 417 |
+
elif msg_lower in ["no", "skip", "none"]:
|
| 418 |
session["step"] = "asking_contact"
|
| 419 |
return "📞 **Please provide your mobile number** (e.g., 03001234567) – We'll use this to contact you."
|
| 420 |
+
else:
|
| 421 |
+
# User might be sending media data via separate API call (see /api/upload_media endpoint)
|
| 422 |
+
# For simplicity, we'll not handle inline media; rely on separate endpoint.
|
| 423 |
+
return "Please reply **Yes** to add media, **No** to skip."
|
| 424 |
+
|
| 425 |
+
elif step == "waiting_media":
|
| 426 |
+
# This state is handled by the frontend via a separate API call.
|
| 427 |
+
# Once the user types DONE, we move to contact.
|
| 428 |
+
if msg_lower == "done":
|
| 429 |
+
# Save collected media into requirements
|
| 430 |
+
if "media_text" in session and session["media_text"]:
|
| 431 |
+
req["media_text"] = session["media_text"]
|
| 432 |
+
if "media_image" in session and session["media_image"]:
|
| 433 |
+
req["media_image"] = session["media_image"]
|
| 434 |
+
session["requirements"] = req
|
| 435 |
+
session["step"] = "asking_contact"
|
| 436 |
+
del session["waiting_media"]
|
| 437 |
+
return "📞 **Please provide your mobile number** (e.g., 03001234567) – We'll use this to contact you."
|
| 438 |
+
else:
|
| 439 |
+
# User typed something while waiting_media – ignore, because media is uploaded via API.
|
| 440 |
+
return "Please type **DONE** when you have finished adding text/image."
|
| 441 |
|
| 442 |
elif step == "asking_contact":
|
| 443 |
if "mobile" not in session:
|
|
|
|
| 479 |
deep_text = "\n\n📌 **Deep Dive Responses:**\n"
|
| 480 |
for key, val in deep_answers.items():
|
| 481 |
deep_text += f"• {key}: {val}\n"
|
| 482 |
+
media_text = ""
|
| 483 |
+
if req.get("media_text"):
|
| 484 |
+
media_text += f"\n\n📝 **Client Notes:** {req['media_text']}\n"
|
| 485 |
+
if req.get("media_image"):
|
| 486 |
+
media_text += f"\n🖼️ **Image uploaded** (view in admin panel)\n"
|
| 487 |
contact_text = f"\n\n📞 **Contact Details:**\n• Mobile: {req.get('mobile', '')}\n• Email: {req.get('email', '')}"
|
| 488 |
return f"""📋 **Your Project Proposal**
|
| 489 |
|
|
|
|
| 493 |
• E‑commerce: {'Yes' if req.get('ecommerce') else 'No'}
|
| 494 |
• Chatbot: {'Yes' if req.get('chatbot') else 'No'}
|
| 495 |
• SEO: {'Yes' if req.get('seo') else 'No'}
|
| 496 |
+
• Extras: {extra_display}{add_text}{deep_text}{media_text}{contact_text}
|
| 497 |
|
| 498 |
💰 **Total Cost:** PKR {price:,}
|
| 499 |
⏱️ **Timeline:** {timeline} working days
|
|
|
|
| 527 |
|
| 528 |
return None
|
| 529 |
|
| 530 |
+
# ---------- Endpoint to receive media uploads (text/image) ----------
|
| 531 |
+
@app.route('/api/upload_media', methods=['POST'])
|
| 532 |
+
def upload_media():
|
| 533 |
+
data = request.json
|
| 534 |
+
session_id = data.get('session_id')
|
| 535 |
+
media_text = data.get('text', '')
|
| 536 |
+
image_base64 = data.get('image', '') # base64 string
|
| 537 |
+
if session_id in user_sessions:
|
| 538 |
+
session = user_sessions[session_id]
|
| 539 |
+
if session.get("waiting_media"):
|
| 540 |
+
if media_text:
|
| 541 |
+
session["media_text"] = media_text
|
| 542 |
+
if image_base64:
|
| 543 |
+
session["media_image"] = image_base64
|
| 544 |
+
return jsonify({"status": "ok", "message": "Media saved"})
|
| 545 |
+
return jsonify({"status": "error", "message": "Session not in media upload mode"}), 400
|
| 546 |
+
|
| 547 |
# ---------- Package details (fallback) ----------
|
| 548 |
def package_details(query):
|
| 549 |
q = query.lower()
|
|
|
|
| 570 |
emoji = {"pending":"⏳", "in-progress":"🔄", "completed":"✅", "declined":"❌"}.get(status, "❓")
|
| 571 |
msg = proj.get("admin_message", "")
|
| 572 |
extra = f"\n📝 **Admin note:** {msg}" if msg else ""
|
| 573 |
+
# Show media details if present
|
| 574 |
+
req = proj.get("requirements", {})
|
| 575 |
+
media_info = ""
|
| 576 |
+
if req.get("media_text"):
|
| 577 |
+
media_info += f"\n📝 **Client Notes:** {req['media_text']}"
|
| 578 |
+
if req.get("media_image"):
|
| 579 |
+
media_info += "\n🖼️ **Image uploaded** (view in admin panel)"
|
| 580 |
+
return f"📦 **Project {pid}**\nStatus: {emoji} {status.upper()}{extra}{media_info}\nTotal: PKR {proj.get('calculated_price',0):,}\nTimeline: {proj.get('calculated_timeline',0)} days"
|
| 581 |
else:
|
| 582 |
return f"❌ Project ID `{pid}` not found."
|
| 583 |
|