Ahmad140 commited on
Commit
b73ec2e
·
verified ·
1 Parent(s): d352aee

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +103 -180
app.py CHANGED
@@ -7,6 +7,9 @@ import json
7
  from datetime import datetime
8
  from sentence_transformers import SentenceTransformer, util
9
  import uuid
 
 
 
10
 
11
  app = Flask(__name__)
12
 
@@ -21,130 +24,99 @@ firebase_admin.initialize_app(cred, {'databaseURL': database_url})
21
  ref = db.reference('/')
22
  print("✅ Firebase connected")
23
 
24
- # ---------- Sentence-Transformer Model ----------
25
  print("🔄 Loading sentence-transformers...")
26
  embedding_model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
27
  print("✅ Embedding model loaded")
28
 
29
- # ---------- Intent Classification (Relevant vs Irrelevant) ----------
30
- # Relevant topics (services) – these will NEVER be marked irrelevant
31
- RELEVANT_SERVICE_KEYWORDS = [
32
- "photography", "product photo", "jewelry photo", "car photo",
33
- "architecture", "3d render", "rendering", "visualization",
34
- "corporate video", "commercial", "advertisement",
35
- "drone", "videography", "cinematography", "aerial",
36
- "headshot", "portrait", "corporate headshot",
37
- "editing", "retouching", "post production",
38
- "wedding", "event", "real estate", "property",
39
- "catalog", "ecommerce", "packshot",
40
- "virtual tour", "360 photo", "vr"
41
- ]
42
-
43
- # Completely irrelevant keywords (out of scope)
44
- IRRELEVANT_KEYWORDS = [
45
- "politics", "imran khan", "nawaz sharif", "election", "vote",
46
- "weather", "rain", "temperature", "mausam",
47
- "cricket", "football", "sports", "match", "world cup",
48
- "stock market", "bitcoin", "crypto", "share price",
49
- "bollywood", "hollywood", "film", "actor", "actress",
50
- "covid", "corona", "vaccine",
51
- "pakistan army", "india", "china",
52
- "python", "coding", "programming", "ai", "machine learning",
53
- "news", "headlines", "today news", "breaking news"
54
- ]
55
-
56
- # Intent mapping for relevant queries (keywords to intent)
57
- KEYWORD_TO_INTENT = {
58
- "contact number": "contact", "phone number": "contact", "whatsapp": "contact",
59
- "call": "contact", "raabta": "contact", "email": "contact",
60
- "price": "pricing", "cost": "pricing", "rate": "pricing", "kitne ka": "pricing",
61
- "charges": "pricing", "fee": "pricing", "quote": "pricing",
62
- "portfolio": "portfolio", "sample": "portfolio", "gallery": "portfolio", "kaam dikhao": "portfolio",
63
- "order status": "order_status", "track order": "order_status",
64
- "refund": "refund", "return": "refund",
65
- "complaint": "complaint", "shikayat": "complaint",
66
- "salam": "greeting", "hello": "greeting", "hi": "greeting"
67
- }
68
-
69
- # For SBERT similarity fallback
70
- INTENT_EXAMPLES = {
71
- "greeting": ["hello", "hi", "salam", "namaste"],
72
- "pricing": ["price", "cost", "rate", "kitne ka hai"],
73
- "service_inquiry": ["drone videography", "3d rendering", "product photography", "architecture rendering", "corporate video", "wedding photography", "real estate photos"],
74
- "contact": ["contact number", "phone number", "customer support"],
75
- "portfolio": ["portfolio", "sample", "gallery"],
76
- "complaint": ["complaint", "problem", "issue"],
77
- "order_status": ["order status", "track order"],
78
- "refund": ["refund", "return"]
79
  }
80
 
81
- def is_relevant_query(text):
82
- """Check if query is related to services (even if not exact match)"""
83
- text_lower = text.lower()
84
- # If any relevant keyword present -> relevant
85
- for kw in RELEVANT_SERVICE_KEYWORDS:
86
- if kw in text_lower:
87
- return True
88
- # If it's a question about "kya aap ... karte hain" -> relevant
89
- if "kya aap" in text_lower and ("karte" in text_lower or "karte ho" in text_lower):
90
- return True
91
- return False
92
 
93
- def is_irrelevant(text):
94
- """Strictly unrelated topics (politics, weather, sports, etc.)"""
95
- text_lower = text.lower()
96
- for kw in IRRELEVANT_KEYWORDS:
97
- if kw in text_lower:
98
- return True
99
- # Also check SBERT similarity with irrelevant examples
100
- irrelevant_examples = [
101
- "weather today", "cricket match", "imran khan", "stock market",
102
- "bollywood movie", "python code", "election results"
103
- ]
104
- text_emb = embedding_model.encode(text, convert_to_tensor=True)
105
- ex_embs = embedding_model.encode(irrelevant_examples, convert_to_tensor=True)
106
- sims = util.cos_sim(text_emb, ex_embs)[0]
107
- if sims.max().item() > 0.65:
108
- return True
109
- return False
110
 
111
  def classify_intent(user_text):
112
  text_lower = user_text.lower()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
 
114
- # Check for out-of-scope (truly irrelevant)
115
- if is_irrelevant(user_text):
116
- return "out_of_scope"
117
-
118
- # If not irrelevant but also not matching any service keyword? But still might be general question.
119
- # Check keyword mapping first
120
- for keyword, intent in KEYWORD_TO_INTENT.items():
121
- if keyword in text_lower:
122
- return intent
123
-
124
- # Check for service inquiry pattern
125
- if "kya aap" in text_lower and ("karte" in text_lower or "karte ho" in text_lower):
126
- return "service_inquiry"
127
 
128
- # Check if any relevant keyword present (then treat as service inquiry)
129
- if is_relevant_query(user_text):
130
- return "service_inquiry"
131
 
132
- # Use SBERT for remaining
133
- text_emb = embedding_model.encode(user_text, convert_to_tensor=True)
134
- best_intent = "general"
135
- best_score = 0.0
136
- for intent, examples in INTENT_EXAMPLES.items():
137
- if not examples:
138
- continue
139
- ex_embs = embedding_model.encode(examples, convert_to_tensor=True)
140
- scores = util.cos_sim(text_emb, ex_embs)[0]
141
- max_score = scores.max().item()
142
- if max_score > best_score:
143
- best_score = max_score
144
- best_intent = intent
145
- if best_score >= 0.5:
146
- return best_intent
147
- return "general"
 
 
 
 
148
 
149
  # ---------- OpenRouter Setup ----------
150
  OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
@@ -152,19 +124,11 @@ MODEL = "google/gemini-2.0-flash-lite-preview-02-05"
152
 
153
  SYSTEM_PROMPT = """You are "VisionCraft AI" – assistant for "Elite Visuals", a premium imagery business.
154
 
155
- Services: product photography, architecture renders, corporate videos, drone cinematography, headshots, 3D rendering, wedding photography, real estate visuals, AI editing.
156
-
157
- Always answer in bullet points. Be concise and helpful.
158
 
159
- If user asks about a service not explicitly listed, still respond positively explaining we can do it or offer custom quote.
160
-
161
- Never say you don't know. Redirect to services.
162
-
163
- Examples:
164
- - For "kya aap wedding photography karte hain?" → "- ✅ Yes, we offer wedding photography and cinematography packages starting from PKR 50,000.\n- 📸 Sample album available on request."
165
- - For pricing: "- Product photography: PKR 15,000–25,000/session\n- Architecture renders: PKR 30,000–50,000/project"
166
- - For contact: "- 📞 Phone: +92 300 1234567\n- ✉️ Email: hello@elitevisuals.com"
167
- """
168
 
169
  def call_openrouter(prompt):
170
  if not OPENROUTER_API_KEY:
@@ -188,73 +152,32 @@ def call_openrouter(prompt):
188
  print(f"OpenRouter error: {e}")
189
  return None
190
 
191
- # ---------- Smart Fallback (Intent-based, No Hallucination) ----------
192
- def fallback_response(intent):
193
- if intent == "out_of_scope":
194
- return "- ❌ Maazrat, yeh sawaal mere scope mein nahi hai.\n- Main sirf Elite Visuals ki imagery services ke baare mein jaankaari de sakta hoon:\n • Product photography\n • Architecture renders\n • Corporate videos\n • Drone cinematography\n • 3D rendering\n • Wedding photography\n • Real estate visuals\n • AI editing\n- Kya aap in mein se kisi ke baare mein poochna chahenge?"
195
- elif intent == "greeting":
196
- return "- Wa-Alaikum-Assalam! 👋\n- Main Elite Visuals ka assistant hoon.\n- Main in services mein madad kar sakta hoon:\n • Product photography\n • Architecture renders\n • Corporate videos\n • Drone cinematography\n • 3D rendering\n • Wedding photography\n • Real estate visuals\n • AI editing"
197
- elif intent == "service_inquiry":
198
- return "- ✅ Yes, Elite Visuals offers:\n • Drone videography (events, real estate)\n • 3D architectural rendering\n • Corporate video production\n • Product photography (jewelry, cars, luxury goods)\n • Professional headshots\n • Wedding photography & cinematography\n • Real estate photo/virtual tours\n • AI-enhanced editing\n- 💬 Detailed quote ke liye apni requirement bhejein."
199
- elif intent == "contact":
200
- return "- 📞 Phone: +92 300 1234567\n- ✉️ Email: hello@elitevisuals.com\n- 🌐 Website: www.elitevisuals.com\n- ⏰ Timings: Mon-Sat, 10am-7pm"
201
- elif intent == "pricing":
202
- return "- 📸 Product photography: PKR 15,000–25,000/session\n- 🏛️ Architecture renders: PKR 30,000–50,000/project\n- 🎥 Corporate video: PKR 50,000–2,00,000\n- 🎬 Wedding photography: PKR 50,000–1,50,000\n- ✈️ Drone services: PKR 25,000–60,000/hour\n- 💡 Exact quote ke liye apni requirement bhejein"
203
- elif intent == "portfolio":
204
- return "- 📷 Instagram: @elitevisuals\n- 🖥️ Gallery: www.elitevisuals.com/gallery\n- 📂 Sample PDF: email par request karein"
205
- elif intent == "complaint":
206
- return "- 😔 Maazrat, issue ke liye.\n- 🔢 Apna order ID bhejein.\n- 🚀 Priority resolve karenge.\n- 🎁 Next order par 10% discount"
207
- elif intent == "order_status":
208
- return "- 📦 Order status ke liye:\n • Order ID\n • Email address\n- ⏱️ 24 ghante mein update"
209
- elif intent == "refund":
210
- return "- 💰 Refund policy:\n • 24 hours cancellation: 100% refund\n • After 24 hours: 50% refund\n • Work started: no refund"
211
- else:
212
- return "- Main aapki kaise madad kar sakta hoon?\n- Services: product photography, architecture renders, corporate videos, drone cinematography, 3D rendering, wedding photography, real estate visuals, AI editing"
213
-
214
  def get_ai_response(user_message, intent):
215
- if intent == "out_of_scope":
216
- return fallback_response(intent)
217
- resp = call_openrouter(user_message)
218
- if resp and resp.strip() and "error" not in resp.lower():
219
- return resp
220
- return fallback_response(intent)
 
 
 
221
 
222
- # ---------- Firebase Helpers (Per User History) ----------
223
  def save_message(session_id, role, content, intent=None):
224
- messages_ref = ref.child(f"chats/{session_id}/messages")
225
- new_msg_ref = messages_ref.push()
226
- data = {
227
  "role": role,
228
  "content": content,
229
- "timestamp": datetime.now().isoformat()
230
- }
231
- if intent:
232
- data["intent"] = intent
233
- new_msg_ref.set(data)
234
-
235
- def get_recent_history(session_id, limit=10):
236
- """Optional: fetch last N messages for context (not used in this basic version)"""
237
- messages_ref = ref.child(f"chats/{session_id}/messages")
238
- try:
239
- all_msgs = messages_ref.get()
240
- if not all_msgs:
241
- return []
242
- msg_list = []
243
- for key, val in all_msgs.items():
244
- msg_list.append(val)
245
- msg_list.sort(key=lambda x: x.get('timestamp', ''), reverse=True)
246
- return msg_list[:limit]
247
- except Exception:
248
- return []
249
 
250
- # ---------- API Endpoint (with session_id) ----------
251
  @app.route('/api/chat', methods=['POST'])
252
  def chat():
253
  data = request.get_json()
254
  user_message = data.get('message', '')
255
- session_id = data.get('session_id', '')
256
- if not session_id:
257
- session_id = str(uuid.uuid4()) # fallback, but frontend should send valid one
258
  if not user_message:
259
  return jsonify({"error": "No message"}), 400
260
 
 
7
  from datetime import datetime
8
  from sentence_transformers import SentenceTransformer, util
9
  import uuid
10
+ import re
11
+ import torch
12
+ from transformers import AutoTokenizer, AutoModelForCausalLM
13
 
14
  app = Flask(__name__)
15
 
 
24
  ref = db.reference('/')
25
  print("✅ Firebase connected")
26
 
27
+ # ---------- Sentence-Transformer Model for Intent ----------
28
  print("🔄 Loading sentence-transformers...")
29
  embedding_model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
30
  print("✅ Embedding model loaded")
31
 
32
+ # ---------- Local GPT-2 Model (Fallback) ----------
33
+ print("🔄 Loading local GPT-2 model (fallback)...")
34
+ try:
35
+ gpt2_tokenizer = AutoTokenizer.from_pretrained("gpt2")
36
+ gpt2_model = AutoModelForCausalLM.from_pretrained("gpt2")
37
+ gpt2_tokenizer.pad_token = gpt2_tokenizer.eos_token
38
+ # Move to GPU if available
39
+ device = "cuda" if torch.cuda.is_available() else "cpu"
40
+ gpt2_model = gpt2_model.to(device)
41
+ print(f"✅ GPT-2 loaded on {device}")
42
+ except Exception as e:
43
+ print(f"⚠️ GPT-2 load failed: {e}")
44
+ gpt2_model = None
45
+ gpt2_tokenizer = None
46
+
47
+ # ---------- Service List (used only for context) ----------
48
+ SERVICES_DESC = {
49
+ "product photography": "High-end product photography for jewelry, cars, luxury goods.",
50
+ "architecture renders": "3D architectural visualization and rendering.",
51
+ "corporate videos": "4K/8K corporate video production.",
52
+ "drone cinematography": "Drone videography for events, real estate, commercials.",
53
+ "3d rendering": "3D rendering for products and architecture.",
54
+ "wedding photography": "Wedding photography & cinematography packages.",
55
+ "real estate visuals": "Real estate photo, virtual tours, drone shoots.",
56
+ "ai editing": "AI-enhanced photo editing and retouching.",
57
+ "headshots": "Professional corporate headshots and portraits."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  }
59
 
60
+ SERVICES_LIST = list(SERVICES_DESC.keys())
 
 
 
 
 
 
 
 
 
 
61
 
62
+ # ---------- Intent Classification ----------
63
+ IRRELEVANT_KEYWORDS = ["cricket", "weather", "politics", "imran", "nawaz", "election", "stock", "bitcoin", "covid", "corona"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
 
65
  def classify_intent(user_text):
66
  text_lower = user_text.lower()
67
+ if any(kw in text_lower for kw in IRRELEVANT_KEYWORDS):
68
+ return "irrelevant"
69
+ if any(x in text_lower for x in ["contact", "phone", "number", "whatsapp", "email", "call", "raabta"]):
70
+ return "contact"
71
+ if any(x in text_lower for x in ["price", "cost", "rate", "kitne", "quote", "charges", "fee"]):
72
+ return "pricing"
73
+ if any(x in text_lower for x in ["portfolio", "sample", "gallery", "kaam dikhao"]):
74
+ return "portfolio"
75
+ if any(x in text_lower for x in ["salam", "hello", "hi", "hey"]):
76
+ return "greeting"
77
+ return "service_inquiry"
78
+
79
+ def handle_negation(text):
80
+ neg_patterns = [r"can(not|'t) you", r"do you not", r"don't you", r"nhi karte", r"nahi karte"]
81
+ return any(re.search(pat, text.lower()) for pat in neg_patterns)
82
+
83
+ # ---------- Local GPT-2 Generation (Personalized, No Copy-Paste) ----------
84
+ def generate_with_gpt2(prompt):
85
+ """Generate a response using local GPT-2 model."""
86
+ if gpt2_model is None or gpt2_tokenizer is None:
87
+ return "Local AI model unavailable. Please try again later."
88
 
89
+ # Build a structured prompt for GPT-2 to produce relevant answers
90
+ full_prompt = f"""You are VisionCraft AI, assistant for Elite Visuals, a premium imagery business. Services include: {', '.join(SERVICES_LIST)}.
91
+ Answer the user's question in short bullet points. Be helpful and accurate.
92
+
93
+ User: {prompt}
94
+ Assistant:"""
 
 
 
 
 
 
 
95
 
96
+ inputs = gpt2_tokenizer(full_prompt, return_tensors="pt", truncation=True, max_length=512)
97
+ device = next(gpt2_model.parameters()).device
98
+ inputs = {k: v.to(device) for k, v in inputs.items()}
99
 
100
+ with torch.no_grad():
101
+ outputs = gpt2_model.generate(
102
+ **inputs,
103
+ max_new_tokens=150,
104
+ temperature=0.8,
105
+ do_sample=True,
106
+ top_p=0.9,
107
+ pad_token_id=gpt2_tokenizer.eos_token_id
108
+ )
109
+ response = gpt2_tokenizer.decode(outputs[0], skip_special_tokens=True)
110
+ # Extract only the assistant part
111
+ if "Assistant:" in response:
112
+ response = response.split("Assistant:")[-1].strip()
113
+ # Remove the original prompt if it appears
114
+ if response.startswith(full_prompt):
115
+ response = response[len(full_prompt):].strip()
116
+ # If response is too short or empty, provide a default
117
+ if len(response) < 10:
118
+ response = "- I understand you're asking about Elite Visuals services. Could you please be more specific? We offer product photography, drone videos, 3D rendering, wedding shoots, and more."
119
+ return response
120
 
121
  # ---------- OpenRouter Setup ----------
122
  OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
 
124
 
125
  SYSTEM_PROMPT = """You are "VisionCraft AI" – assistant for "Elite Visuals", a premium imagery business.
126
 
127
+ Services: product photography, architecture renders, corporate videos, drone cinematography, 3D rendering, wedding photography, real estate visuals, AI editing.
 
 
128
 
129
+ Always answer in bullet points. Be concise, helpful, and personalized to the user's exact question.
130
+ If user asks "can you not provide X", clarify that you DO provide it unless X is not in the list.
131
+ Never copy-paste the same generic list for every question. Adapt to the query."""
 
 
 
 
 
 
132
 
133
  def call_openrouter(prompt):
134
  if not OPENROUTER_API_KEY:
 
152
  print(f"OpenRouter error: {e}")
153
  return None
154
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
155
  def get_ai_response(user_message, intent):
156
+ # Priority 1: OpenRouter (smart, personalized)
157
+ ai_response = call_openrouter(user_message)
158
+ if ai_response and ai_response.strip() and "error" not in ai_response.lower():
159
+ print("✅ OpenRouter succeeded")
160
+ return ai_response
161
+
162
+ # Priority 2: Local GPT-2 (still personalized, not copy-paste)
163
+ print("⚠️ OpenRouter failed – using local GPT-2")
164
+ return generate_with_gpt2(user_message)
165
 
166
+ # ---------- Firebase Helpers ----------
167
  def save_message(session_id, role, content, intent=None):
168
+ ref.child(f"chats/{session_id}/messages").push().set({
 
 
169
  "role": role,
170
  "content": content,
171
+ "timestamp": datetime.now().isoformat(),
172
+ "intent": intent
173
+ })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
174
 
175
+ # ---------- API Endpoint ----------
176
  @app.route('/api/chat', methods=['POST'])
177
  def chat():
178
  data = request.get_json()
179
  user_message = data.get('message', '')
180
+ session_id = data.get('session_id', str(uuid.uuid4()))
 
 
181
  if not user_message:
182
  return jsonify({"error": "No message"}), 400
183