SamiKoen commited on
Commit
edf6940
·
1 Parent(s): 03d4524

GPT-5 zekasını kullanarak ürün arama - manuel filtreleme yok

Browse files
Files changed (2) hide show
  1. app.py +55 -28
  2. smart_warehouse.py +129 -0
app.py CHANGED
@@ -29,8 +29,25 @@ from enhanced_features import (
29
  )
30
  from image_renderer import extract_product_info_for_gallery, format_message_with_images
31
 
32
- # SMART warehouse stock finder - general algorithm
 
 
 
 
 
33
  def get_warehouse_stock(product_name):
 
 
 
 
 
 
 
 
 
 
 
 
34
  """Smart warehouse stock finder with general algorithm"""
35
  try:
36
  import re
@@ -60,34 +77,44 @@ def get_warehouse_stock(product_name):
60
  # Smart filtering: Keep only meaningful product identifiers
61
  product_words = []
62
 
63
- # First pass: identify what looks like product terms
64
- for word in words:
65
- # Skip if it's a size marker
66
- if word in sizes:
67
- continue
68
-
69
- # Always keep numbers (model numbers like 6, 7, 8)
70
- if word.isdigit():
71
- product_words.append(word)
72
-
73
- # Keep alphanumeric codes (like "sl6", "gen8")
74
- elif any(c.isdigit() for c in word) and any(c.isalpha() for c in word):
75
- product_words.append(word)
76
-
77
- # Keep 2-3 letter codes (often product codes like "sl", "slr", "emx")
78
- elif 2 <= len(word) <= 3 and word.isalpha():
79
- # Check if it has consonants (likely a code, not a particle)
80
- if any(c not in 'aeiou' for c in word):
81
  product_words.append(word)
82
-
83
- # Keep longer words that have good consonant/vowel mix (likely product names)
84
- elif len(word) > 3:
85
- # Calculate consonant ratio
86
- consonants = sum(1 for c in word if c not in 'aeiou')
87
- vowels = len(word) - consonants
88
- # Product names usually have balanced or consonant-heavy distribution
89
- # Turkish question words are often vowel-heavy
90
- if consonants >= vowels * 0.5: # At least 1 consonant per 2 vowels
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
  product_words.append(word)
92
 
93
  print(f"DEBUG - Searching: {' '.join(product_words)}, Size: {size}")
 
29
  )
30
  from image_renderer import extract_product_info_for_gallery, format_message_with_images
31
 
32
+ # Import smart warehouse with GPT intelligence
33
+ try:
34
+ from smart_warehouse import get_warehouse_stock_smart
35
+ except ImportError:
36
+ get_warehouse_stock_smart = None
37
+
38
  def get_warehouse_stock(product_name):
39
+ """Use GPT intelligence to find warehouse stock"""
40
+ # First try GPT-powered search
41
+ if get_warehouse_stock_smart:
42
+ result = get_warehouse_stock_smart(product_name)
43
+ if result:
44
+ return result
45
+
46
+ # Fallback to old method
47
+ return get_warehouse_stock_old(product_name)
48
+
49
+ # OLD warehouse stock finder - general algorithm
50
+ def get_warehouse_stock_old(product_name):
51
  """Smart warehouse stock finder with general algorithm"""
52
  try:
53
  import re
 
77
  # Smart filtering: Keep only meaningful product identifiers
78
  product_words = []
79
 
80
+ # If query is very short (like "hangi boyu"), skip it
81
+ if len(words) <= 2 and not any(w.isdigit() for w in words):
82
+ # Likely just a question, not a product search
83
+ pass
84
+ else:
85
+ # Extract product-like terms
86
+ for word in words:
87
+ # Skip if it's a size marker
88
+ if word in sizes:
89
+ continue
90
+
91
+ # Always keep numbers (model numbers)
92
+ if word.isdigit():
 
 
 
 
 
93
  product_words.append(word)
94
+
95
+ # Keep alphanumeric codes
96
+ elif any(c.isdigit() for c in word) and any(c.isalpha() for c in word):
97
+ product_words.append(word)
98
+
99
+ # Keep 2-3 letter codes that look like product codes
100
+ elif len(word) in [2, 3] and word.isalpha():
101
+ # Skip common particles
102
+ if word in ['mi', 'mı', 'mu', 'mü', 'var', 'yok', 've', 'de', 'da']:
103
+ continue
104
+ # Must have at least one consonant
105
+ if any(c not in 'aeiouı' for c in word):
106
+ product_words.append(word)
107
+
108
+ # For longer words, be selective
109
+ elif len(word) > 3:
110
+ # Skip if ends with Turkish question suffixes
111
+ if any(word.endswith(suffix) for suffix in ['mi', 'mı', 'mu', 'mü']):
112
+ continue
113
+ # Skip if only 1-2 consonants (likely a particle/question word)
114
+ consonants = sum(1 for c in word if c not in 'aeiouı')
115
+ if consonants <= 2: # "var" has 2 consonants, skip it
116
+ continue
117
+ # Keep it
118
  product_words.append(word)
119
 
120
  print(f"DEBUG - Searching: {' '.join(product_words)}, Size: {size}")
smart_warehouse.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Smart warehouse stock finder using GPT-5's intelligence"""
2
+
3
+ import requests
4
+ import re
5
+ import os
6
+ import json
7
+
8
+ def get_warehouse_stock_smart(user_message):
9
+ """Let GPT-5 intelligently find products in XML without manual filtering"""
10
+
11
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
12
+
13
+ # Get XML data
14
+ try:
15
+ url = 'https://video.trek-turkey.com/bizimhesap-warehouse-xml-b2b-api-v2.php'
16
+ response = requests.get(url, verify=False, timeout=7)
17
+ xml_text = response.text
18
+ print(f"DEBUG - XML fetched: {len(xml_text)} characters")
19
+ except Exception as e:
20
+ print(f"XML fetch error: {e}")
21
+ return None
22
+
23
+ # Extract just product blocks to reduce token usage
24
+ product_pattern = r'<Product>(.*?)</Product>'
25
+ all_products = re.findall(product_pattern, xml_text, re.DOTALL)
26
+
27
+ # Create a simplified product list for GPT
28
+ products_summary = []
29
+ for i, product_block in enumerate(all_products): # All products
30
+ name_match = re.search(r'<ProductName><!\[CDATA\[(.*?)\]\]></ProductName>', product_block)
31
+ variant_match = re.search(r'<ProductVariant><!\[CDATA\[(.*?)\]\]></ProductVariant>', product_block)
32
+
33
+ if name_match:
34
+ product_info = {
35
+ "index": i,
36
+ "name": name_match.group(1),
37
+ "variant": variant_match.group(1) if variant_match else ""
38
+ }
39
+ products_summary.append(product_info)
40
+
41
+ # Let GPT-5 find the product
42
+ smart_prompt = f"""User is asking: "{user_message}"
43
+
44
+ Find the product they're asking about from this list:
45
+ {json.dumps(products_summary, ensure_ascii=False, indent=2)}
46
+
47
+ Return ONLY the index number of the matching product, or -1 if not found.
48
+ Be smart about matching - consider partial matches, abbreviations, Turkish/English variations.
49
+ If asking about size (S, M, L, XL), match the variant field."""
50
+
51
+ headers = {
52
+ "Content-Type": "application/json",
53
+ "Authorization": f"Bearer {OPENAI_API_KEY}"
54
+ }
55
+
56
+ payload = {
57
+ "model": "gpt-5-chat-latest",
58
+ "messages": [
59
+ {"role": "system", "content": "You are a product matcher. Return only a number."},
60
+ {"role": "user", "content": smart_prompt}
61
+ ],
62
+ "temperature": 0,
63
+ "max_tokens": 10
64
+ }
65
+
66
+ try:
67
+ response = requests.post(
68
+ "https://api.openai.com/v1/chat/completions",
69
+ headers=headers,
70
+ json=payload,
71
+ timeout=10
72
+ )
73
+
74
+ if response.status_code == 200:
75
+ result = response.json()
76
+ product_index = result['choices'][0]['message']['content'].strip()
77
+
78
+ try:
79
+ idx = int(product_index)
80
+ if idx == -1:
81
+ return ["Ürün bulunamadı"]
82
+
83
+ # Get warehouse info for found product
84
+ product_block = all_products[idx]
85
+ return extract_warehouse_info(product_block)
86
+
87
+ except (ValueError, IndexError):
88
+ print(f"DEBUG - GPT returned invalid index: {product_index}")
89
+ return None
90
+ else:
91
+ print(f"GPT API error: {response.status_code}")
92
+ return None
93
+
94
+ except Exception as e:
95
+ print(f"Error calling GPT: {e}")
96
+ return None
97
+
98
+ def extract_warehouse_info(product_block):
99
+ """Extract warehouse stock information from a product block"""
100
+ warehouse_info = []
101
+
102
+ # Find all warehouses with stock
103
+ warehouse_regex = r'<Warehouse>.*?<Name><!\[CDATA\[(.*?)\]\]></Name>.*?<Stock>(.*?)</Stock>.*?</Warehouse>'
104
+ warehouses = re.findall(warehouse_regex, product_block, re.DOTALL)
105
+
106
+ for wh_name, wh_stock in warehouses:
107
+ try:
108
+ stock = int(wh_stock.strip())
109
+ if stock > 0:
110
+ # Format warehouse name nicely
111
+ if "CADDEBOSTAN" in wh_name:
112
+ display = "Caddebostan mağazası"
113
+ elif "ORTAKÖY" in wh_name:
114
+ display = "Ortaköy mağazası"
115
+ elif "ALSANCAK" in wh_name:
116
+ display = "İzmir Alsancak mağazası"
117
+ elif "BAHCEKOY" in wh_name or "BAHÇEKÖY" in wh_name:
118
+ display = "Bahçeköy mağazası"
119
+ else:
120
+ display = wh_name.replace("MAGAZA DEPO", "").strip()
121
+
122
+ warehouse_info.append(f"{display}: {stock} adet")
123
+ except:
124
+ pass
125
+
126
+ if warehouse_info:
127
+ return warehouse_info
128
+ else:
129
+ return ["Hiçbir mağazada stokta yok"]