BF / smart_warehouse.py
SamiKoen's picture
GPT-5 tüm varyantları buluyor - sadece ilk eşleşmeyi değil
8ba1576
raw
history blame
7.12 kB
"""Smart warehouse stock finder using GPT-5's intelligence"""
import requests
import re
import os
import json
def get_warehouse_stock_smart(user_message):
"""Let GPT-5 intelligently find ALL matching products in XML"""
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
# Get XML data
try:
url = 'https://video.trek-turkey.com/bizimhesap-warehouse-xml-b2b-api-v2.php'
response = requests.get(url, verify=False, timeout=7)
xml_text = response.text
print(f"DEBUG - XML fetched: {len(xml_text)} characters")
except Exception as e:
print(f"XML fetch error: {e}")
return None
# Extract just product blocks to reduce token usage
product_pattern = r'<Product>(.*?)</Product>'
all_products = re.findall(product_pattern, xml_text, re.DOTALL)
# Create a simplified product list for GPT
products_summary = []
for i, product_block in enumerate(all_products):
name_match = re.search(r'<ProductName><!\[CDATA\[(.*?)\]\]></ProductName>', product_block)
variant_match = re.search(r'<ProductVariant><!\[CDATA\[(.*?)\]\]></ProductVariant>', product_block)
if name_match:
product_info = {
"index": i,
"name": name_match.group(1),
"variant": variant_match.group(1) if variant_match else ""
}
products_summary.append(product_info)
# Let GPT-5 find ALL matching products
smart_prompt = f"""User is asking: "{user_message}"
Find ALL products that match this query from the list below.
If user asks about specific size (S, M, L, XL), return only that size.
If user asks generally (without size), return ALL variants of the product.
Products list:
{json.dumps(products_summary, ensure_ascii=False, indent=2)}
Return index numbers of ALL matching products as comma-separated list (e.g., "5,8,12,15").
If no products found, return: -1
Examples:
- "madone sl 6 var mı" -> Return ALL Madone SL 6 variants (all sizes)
- "madone sl 6 S beden" -> Return only S size variant
- "madone sl 6 gen 8" -> Return ALL variants of Madone SL 6 Gen 8"""
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {OPENAI_API_KEY}"
}
payload = {
"model": "gpt-5-chat-latest",
"messages": [
{"role": "system", "content": "You are a product matcher. Find ALL matching products. Return only index numbers."},
{"role": "user", "content": smart_prompt}
],
"temperature": 0,
"max_tokens": 100
}
try:
response = requests.post(
"https://api.openai.com/v1/chat/completions",
headers=headers,
json=payload,
timeout=10
)
if response.status_code == 200:
result = response.json()
indices_str = result['choices'][0]['message']['content'].strip()
if indices_str == "-1":
return ["Ürün bulunamadı"]
try:
# Parse multiple indices
indices = [int(idx.strip()) for idx in indices_str.split(',')]
# Aggregate warehouse info from all matching products
all_warehouses = {}
product_names = []
for idx in indices:
if 0 <= idx < len(all_products):
product_block = all_products[idx]
# Get product name and variant
name_match = re.search(r'<ProductName><!\[CDATA\[(.*?)\]\]></ProductName>', product_block)
variant_match = re.search(r'<ProductVariant><!\[CDATA\[(.*?)\]\]></ProductVariant>', product_block)
if name_match:
product_desc = name_match.group(1)
if variant_match and variant_match.group(1):
product_desc += f" ({variant_match.group(1)})"
product_names.append(product_desc)
# Get warehouse stock
warehouse_regex = r'<Warehouse>.*?<Name><!\[CDATA\[(.*?)\]\]></Name>.*?<Stock>(.*?)</Stock>.*?</Warehouse>'
warehouses = re.findall(warehouse_regex, product_block, re.DOTALL)
for wh_name, wh_stock in warehouses:
try:
stock = int(wh_stock.strip())
if stock > 0:
# Format warehouse name
display_name = format_warehouse_name(wh_name)
if display_name not in all_warehouses:
all_warehouses[display_name] = 0
all_warehouses[display_name] += stock
except:
pass
# Format result
if product_names:
result = []
# Show product variants found
if len(product_names) > 1:
result.append(f"Bulunan {len(product_names)} varyant:")
for name in product_names[:5]: # Show first 5 variants
result.append(f"• {name}")
if len(product_names) > 5:
result.append(f"... ve {len(product_names) - 5} varyant daha")
result.append("")
# Show aggregated warehouse stock
if all_warehouses:
result.append("Toplam stok durumu:")
for warehouse, total_stock in sorted(all_warehouses.items()):
result.append(f"{warehouse}: {total_stock} adet")
else:
result.append("Hiçbir mağazada stok yok")
return result
except (ValueError, IndexError) as e:
print(f"DEBUG - Error parsing indices: {e}")
return None
else:
print(f"GPT API error: {response.status_code}")
return None
except Exception as e:
print(f"Error calling GPT: {e}")
return None
def format_warehouse_name(wh_name):
"""Format warehouse name nicely"""
if "CADDEBOSTAN" in wh_name:
return "Caddebostan mağazası"
elif "ORTAKÖY" in wh_name:
return "Ortaköy mağazası"
elif "ALSANCAK" in wh_name:
return "İzmir Alsancak mağazası"
elif "BAHCEKOY" in wh_name or "BAHÇEKÖY" in wh_name:
return "Bahçeköy mağazası"
else:
return wh_name.replace("MAGAZA DEPO", "").strip()