SamiKoen commited on
Commit
0c0cb78
·
1 Parent(s): aad23d9

GPT-5 akıllı ürün arama entegrasyonu - WhatsApp için optimize edildi

Browse files
Files changed (2) hide show
  1. app.py +28 -1
  2. smart_warehouse_whatsapp.py +279 -0
app.py CHANGED
@@ -25,6 +25,15 @@ except ImportError:
25
  print("Improved WhatsApp chatbot not available, using basic search")
26
  USE_IMPROVED_SEARCH = False
27
 
 
 
 
 
 
 
 
 
 
28
  # LOGGING EN BAŞA EKLENDİ
29
  import logging
30
  logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
@@ -60,7 +69,25 @@ else:
60
 
61
  # Mağaza stok bilgilerini çekme fonksiyonu
62
  def get_warehouse_stock(product_name):
63
- """B2B API'den mağaza stok bilgilerini çek - İyileştirilmiş versiyon"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  try:
65
  import re
66
  warehouse_url = 'https://video.trek-turkey.com/bizimhesap-warehouse-xml-b2b-api-v2.php'
 
25
  print("Improved WhatsApp chatbot not available, using basic search")
26
  USE_IMPROVED_SEARCH = False
27
 
28
+ # Import GPT-5 powered smart warehouse search
29
+ try:
30
+ from smart_warehouse_whatsapp import get_warehouse_stock_gpt5
31
+ USE_GPT5_SEARCH = True
32
+ logger.info("✅ GPT-5 smart warehouse search loaded")
33
+ except ImportError:
34
+ USE_GPT5_SEARCH = False
35
+ logger.info("❌ GPT-5 search not available")
36
+
37
  # LOGGING EN BAŞA EKLENDİ
38
  import logging
39
  logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
 
69
 
70
  # Mağaza stok bilgilerini çekme fonksiyonu
71
  def get_warehouse_stock(product_name):
72
+ """B2B API'den mağaza stok bilgilerini çek - GPT-5 enhanced"""
73
+ # Try GPT-5 smart search first
74
+ if USE_GPT5_SEARCH:
75
+ gpt5_result = get_warehouse_stock_gpt5(product_name)
76
+ if gpt5_result:
77
+ # Format for WhatsApp display
78
+ warehouse_info = []
79
+ for product in gpt5_result[:3]: # Max 3 products for WhatsApp
80
+ info = f"📦 {product['name']}"
81
+ if product['variant']:
82
+ info += f" ({product['variant']})"
83
+ if product['warehouses']:
84
+ info += f"\n📍 Mevcut: {', '.join(product['warehouses'])}"
85
+ if product['price']:
86
+ info += f"\n💰 {product['price']}"
87
+ warehouse_info.append(info)
88
+ return warehouse_info
89
+
90
+ # Fallback to original search
91
  try:
92
  import re
93
  warehouse_url = 'https://video.trek-turkey.com/bizimhesap-warehouse-xml-b2b-api-v2.php'
smart_warehouse_whatsapp.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Smart warehouse stock finder for WhatsApp - GPT-5 powered"""
2
+
3
+ import requests
4
+ import re
5
+ import os
6
+ import json
7
+ import xml.etree.ElementTree as ET
8
+
9
+ def get_product_price_and_link(product_name, variant=None):
10
+ """Get price and link from Trek website XML"""
11
+ try:
12
+ url = 'https://www.trekbisiklet.com.tr/output/8582384479'
13
+ response = requests.get(url, verify=False, timeout=10)
14
+
15
+ if response.status_code != 200:
16
+ return None, None
17
+
18
+ root = ET.fromstring(response.content)
19
+
20
+ # Normalize search terms
21
+ search_name = product_name.lower()
22
+ search_variant = variant.lower() if variant else ""
23
+
24
+ # Turkish character normalization
25
+ tr_map = {'ı': 'i', 'ğ': 'g', 'ü': 'u', 'ş': 's', 'ö': 'o', 'ç': 'c'}
26
+ for tr, en in tr_map.items():
27
+ search_name = search_name.replace(tr, en)
28
+ search_variant = search_variant.replace(tr, en)
29
+
30
+ best_match = None
31
+ best_score = 0
32
+
33
+ for item in root.findall('item'):
34
+ rootlabel_elem = item.find('rootlabel')
35
+ if rootlabel_elem is None or not rootlabel_elem.text:
36
+ continue
37
+
38
+ item_name = rootlabel_elem.text.lower()
39
+ for tr, en in tr_map.items():
40
+ item_name = item_name.replace(tr, en)
41
+
42
+ # Calculate match score
43
+ score = 0
44
+ name_parts = search_name.split()
45
+ for part in name_parts:
46
+ if part in item_name:
47
+ score += 1
48
+
49
+ if variant and search_variant in item_name:
50
+ score += 2
51
+
52
+ if score > best_score:
53
+ best_score = score
54
+ best_match = item
55
+
56
+ if best_match and best_score > 0:
57
+ # Extract price
58
+ price_elem = best_match.find('priceTaxWithCur')
59
+ price = price_elem.text if price_elem is not None and price_elem.text else None
60
+
61
+ # Round price for WhatsApp display
62
+ if price:
63
+ try:
64
+ price_float = float(price)
65
+ if price_float > 200000:
66
+ rounded = round(price_float / 5000) * 5000
67
+ price = f"{int(rounded):,}".replace(',', '.') + " TL"
68
+ elif price_float > 30000:
69
+ rounded = round(price_float / 1000) * 1000
70
+ price = f"{int(rounded):,}".replace(',', '.') + " TL"
71
+ elif price_float > 10000:
72
+ rounded = round(price_float / 100) * 100
73
+ price = f"{int(rounded):,}".replace(',', '.') + " TL"
74
+ else:
75
+ rounded = round(price_float / 10) * 10
76
+ price = f"{int(rounded):,}".replace(',', '.') + " TL"
77
+ except:
78
+ price = None
79
+
80
+ # Extract link
81
+ link_elem = best_match.find('productLink')
82
+ link = link_elem.text if link_elem is not None and link_elem.text else None
83
+
84
+ return price, link
85
+
86
+ return None, None
87
+
88
+ except Exception as e:
89
+ print(f"Error getting price/link: {e}")
90
+ return None, None
91
+
92
+ def get_warehouse_stock_gpt5(user_message):
93
+ """GPT-5 powered smart warehouse stock search for WhatsApp"""
94
+
95
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
96
+ if not OPENAI_API_KEY:
97
+ return None
98
+
99
+ # Check for specific warehouse in query
100
+ warehouse_keywords = {
101
+ 'caddebostan': 'Caddebostan',
102
+ 'ortaköy': 'Ortaköy',
103
+ 'ortakoy': 'Ortaköy',
104
+ 'alsancak': 'Alsancak',
105
+ 'izmir': 'Alsancak',
106
+ 'bahçeköy': 'Bahçeköy',
107
+ 'bahcekoy': 'Bahçeköy'
108
+ }
109
+
110
+ user_lower = user_message.lower()
111
+ asked_warehouse = None
112
+ for keyword, warehouse in warehouse_keywords.items():
113
+ if keyword in user_lower:
114
+ asked_warehouse = warehouse
115
+ break
116
+
117
+ # Get warehouse XML with retry
118
+ xml_text = None
119
+ for attempt in range(3):
120
+ try:
121
+ url = 'https://video.trek-turkey.com/bizimhesap-warehouse-xml-b2b-api-v2.php'
122
+ timeout_val = 10 + (attempt * 5)
123
+ response = requests.get(url, verify=False, timeout=timeout_val)
124
+ xml_text = response.text
125
+ break
126
+ except:
127
+ if attempt == 2:
128
+ return None
129
+
130
+ if not xml_text:
131
+ return None
132
+
133
+ # Extract product blocks
134
+ product_pattern = r'<Product>(.*?)</Product>'
135
+ all_products = re.findall(product_pattern, xml_text, re.DOTALL)
136
+
137
+ # Create product summary for GPT
138
+ products_summary = []
139
+ for i, product_block in enumerate(all_products):
140
+ name_match = re.search(r'<ProductName><!\[CDATA\[(.*?)\]\]></ProductName>', product_block)
141
+ variant_match = re.search(r'<ProductVariant><!\[CDATA\[(.*?)\]\]></ProductVariant>', product_block)
142
+
143
+ if name_match:
144
+ warehouses_with_stock = []
145
+ warehouse_regex = r'<Warehouse>.*?<Name><!\[CDATA\[(.*?)\]\]></Name>.*?<Stock>(.*?)</Stock>.*?</Warehouse>'
146
+ warehouses = re.findall(warehouse_regex, product_block, re.DOTALL)
147
+
148
+ for wh_name, wh_stock in warehouses:
149
+ try:
150
+ if int(wh_stock.strip()) > 0:
151
+ warehouses_with_stock.append(wh_name)
152
+ except:
153
+ pass
154
+
155
+ if warehouses_with_stock: # Only add if has stock
156
+ product_info = {
157
+ "index": i,
158
+ "name": name_match.group(1),
159
+ "variant": variant_match.group(1) if variant_match else "",
160
+ "warehouses": warehouses_with_stock
161
+ }
162
+ products_summary.append(product_info)
163
+
164
+ # Prepare GPT-5 prompt
165
+ warehouse_filter = ""
166
+ if asked_warehouse:
167
+ warehouse_filter = f"\nIMPORTANT: User is asking about {asked_warehouse} warehouse. Only return products available there."
168
+
169
+ smart_prompt = f"""User WhatsApp message: "{user_message}"
170
+
171
+ Find products matching this query.
172
+ Understand Turkish/English terms:
173
+ - FORMA = jersey/cycling shirt
174
+ - TAYT = tights
175
+ - İÇLİK = base layer
176
+ - YAĞMURLUK = raincoat
177
+ - GOBIK = Spanish textile brand
178
+
179
+ Product types: "erkek forma" = men's jersey, "tayt" = tights, etc.
180
+ Sizes: S, M, L, XL, XXL, SMALL, MEDIUM, LARGE
181
+ {warehouse_filter}
182
+
183
+ Products with stock:
184
+ {json.dumps(products_summary[:500], ensure_ascii=False)}
185
+
186
+ Return ONLY index numbers as comma-separated list (e.g., "5,8,12,15") or -1 if none found.
187
+ NO explanations, ONLY numbers."""
188
+
189
+ headers = {
190
+ "Content-Type": "application/json",
191
+ "Authorization": f"Bearer {OPENAI_API_KEY}"
192
+ }
193
+
194
+ payload = {
195
+ "model": "gpt-5-chat-latest",
196
+ "messages": [
197
+ {"role": "system", "content": "You are a product matcher. Return only numbers."},
198
+ {"role": "user", "content": smart_prompt}
199
+ ],
200
+ "temperature": 0,
201
+ "max_tokens": 100
202
+ }
203
+
204
+ try:
205
+ response = requests.post(
206
+ "https://api.openai.com/v1/chat/completions",
207
+ headers=headers,
208
+ json=payload,
209
+ timeout=10
210
+ )
211
+
212
+ if response.status_code != 200:
213
+ return None
214
+
215
+ result = response.json()
216
+ indices_str = result['choices'][0]['message']['content'].strip()
217
+
218
+ if not indices_str or indices_str == "-1":
219
+ return None
220
+
221
+ # Parse indices safely
222
+ indices = []
223
+ for idx in indices_str.split(','):
224
+ idx = idx.strip()
225
+ if idx and idx.isdigit():
226
+ indices.append(int(idx))
227
+
228
+ if not indices:
229
+ return None
230
+
231
+ # Collect matched products
232
+ matched_products = []
233
+ for idx in indices[:10]: # Limit to 10 for WhatsApp
234
+ if 0 <= idx < len(all_products):
235
+ product_block = all_products[idx]
236
+
237
+ name_match = re.search(r'<ProductName><!\[CDATA\[(.*?)\]\]></ProductName>', product_block)
238
+ variant_match = re.search(r'<ProductVariant><!\[CDATA\[(.*?)\]\]></ProductVariant>', product_block)
239
+
240
+ if name_match:
241
+ product_name = name_match.group(1)
242
+ variant = variant_match.group(1) if variant_match else ""
243
+
244
+ # Get price and link
245
+ price, link = get_product_price_and_link(product_name, variant)
246
+
247
+ # Get warehouse info
248
+ warehouses = []
249
+ warehouse_regex = r'<Warehouse>.*?<Name><!\[CDATA\[(.*?)\]\]></Name>.*?<Stock>(.*?)</Stock>.*?</Warehouse>'
250
+ wh_matches = re.findall(warehouse_regex, product_block, re.DOTALL)
251
+
252
+ for wh_name, wh_stock in wh_matches:
253
+ try:
254
+ if int(wh_stock.strip()) > 0:
255
+ if "CADDEBOSTAN" in wh_name:
256
+ warehouses.append("Caddebostan")
257
+ elif "ORTAKÖY" in wh_name:
258
+ warehouses.append("Ortaköy")
259
+ elif "ALSANCAK" in wh_name:
260
+ warehouses.append("Alsancak")
261
+ elif "BAHCEKOY" in wh_name or "BAHÇEKÖY" in wh_name:
262
+ warehouses.append("Bahçeköy")
263
+ except:
264
+ pass
265
+
266
+ if warehouses:
267
+ matched_products.append({
268
+ 'name': product_name,
269
+ 'variant': variant,
270
+ 'price': price,
271
+ 'link': link,
272
+ 'warehouses': warehouses
273
+ })
274
+
275
+ return matched_products if matched_products else None
276
+
277
+ except Exception as e:
278
+ print(f"GPT-5 search error: {e}")
279
+ return None