BF-WAB / app.py
samikoen
Deploy from GitHub Actions
6ea7409
# -*- coding: utf-8 -*-
"""
Trek WhatsApp AI Asistani - Hybrid Model Version
Gorsel varsa: GPT-4o (vision)
Metin varsa: GPT-5.2 (daha akilli)
"""
import os
import json
import re
import requests
import xml.etree.ElementTree as ET
import warnings
import time
import threading
import datetime
import unicodedata
from concurrent.futures import ThreadPoolExecutor, as_completed
from fastapi import FastAPI, Request
from twilio.rest import Client
from twilio.twiml.messaging_response import MessagingResponse
# Yeni moduller - Basit sistem
from prompts import get_active_prompts
from whatsapp_renderer import extract_product_info_whatsapp
from whatsapp_passive_profiler import (
analyze_user_message, get_user_profile_summary, get_personalized_recommendations
)
# LOGGING EN BASA EKLENDI
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# Import improved WhatsApp search for BF space
# DISABLED - Using GPT-5 smart warehouse search instead
USE_IMPROVED_SEARCH = False
warnings.simplefilter('ignore')
# ===============================
# MODEL KONFIGURASYONU
# ===============================
MODEL_CONFIG = {
"vision": "gpt-4o", # Gorsel analizi icin (Vision destekli)
"text": "gpt-5.2-chat-latest", # Metin icin (en akilli model)
"fallback": "gpt-4o" # Yedek model (GPT-5.2 hata verirse)
}
# Model secimi icin yardimci fonksiyon
def get_model_for_request(has_media=False):
"""
Istek tipine gore uygun modeli sec
has_media=True -> GPT-4o (vision destekli)
has_media=False -> GPT-5.2 (daha akilli metin isleme)
"""
if has_media:
logger.info(f"πŸ–ΌοΈ Gorsel tespit edildi -> Model: {MODEL_CONFIG['vision']}")
return MODEL_CONFIG["vision"]
else:
logger.info(f"πŸ“ Metin mesaji -> Model: {MODEL_CONFIG['text']}")
return MODEL_CONFIG["text"]
# ===============================
# API AYARLARI
# ===============================
API_URL = "https://api.openai.com/v1/chat/completions"
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
logger.info(f"OpenAI API Key var mi: {'Evet' if OPENAI_API_KEY else 'Hayir'}")
# Twilio WhatsApp ayarlari
TWILIO_ACCOUNT_SID = os.getenv("TWILIO_ACCOUNT_SID")
TWILIO_AUTH_TOKEN = os.getenv("TWILIO_AUTH_TOKEN")
TWILIO_MESSAGING_SERVICE_SID = os.getenv("TWILIO_MESSAGING_SERVICE_SID", "MG11c1dfac28ad5f81908ec9ede0f7247f")
TWILIO_WHATSAPP_NUMBER = "whatsapp:+905332047254" # Bizim WhatsApp Business numaramiz
logger.info(f"Twilio SID var mi: {'Evet' if TWILIO_ACCOUNT_SID else 'Hayir'}")
logger.info(f"Twilio Auth Token var mi: {'Evet' if TWILIO_AUTH_TOKEN else 'Hayir'}")
logger.info(f"Messaging Service SID var mi: {'Evet' if TWILIO_MESSAGING_SERVICE_SID else 'Hayir'}")
if not TWILIO_ACCOUNT_SID or not TWILIO_AUTH_TOKEN:
logger.error("❌ Twilio bilgileri eksik!")
twilio_client = None
else:
try:
twilio_client = Client(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
logger.info("βœ… Twilio client basariyla olusturuldu!")
except Exception as e:
logger.error(f"❌ Twilio client hatasi: {e}")
twilio_client = None
# ===============================
# GPT-5 SMART WAREHOUSE
# ===============================
try:
from smart_warehouse_with_price import get_warehouse_stock_smart_with_price
USE_GPT5_SEARCH = True
logger.info("βœ… GPT-5 complete smart warehouse with price (BF algorithm) loaded")
except ImportError:
USE_GPT5_SEARCH = False
logger.info("❌ GPT-5 search not available")
# Import Media Queue V2
try:
from media_queue_v2 import media_queue
USE_MEDIA_QUEUE = True
logger.info("βœ… Media Queue V2 loaded successfully")
except ImportError:
USE_MEDIA_QUEUE = False
logger.info("❌ Media Queue V2 not available")
# Import Store Notification System
try:
from store_notification import (
notify_product_reservation,
notify_price_inquiry,
notify_stock_inquiry,
send_test_notification,
send_store_notification,
should_notify_mehmet_bey
)
USE_STORE_NOTIFICATION = True
logger.info("βœ… Store Notification System loaded")
except ImportError:
USE_STORE_NOTIFICATION = False
logger.info("❌ Store Notification System not available")
# Import Follow-Up System
try:
from follow_up_system import (
FollowUpManager,
analyze_message_for_follow_up,
FollowUpType
)
USE_FOLLOW_UP = True
follow_up_manager = FollowUpManager()
logger.info("βœ… Follow-Up System loaded")
except ImportError:
USE_FOLLOW_UP = False
follow_up_manager = None
logger.info("❌ Follow-Up System not available")
# Import Intent Analyzer
try:
from intent_analyzer import (
analyze_customer_intent,
should_notify_store,
get_smart_notification_message
)
USE_INTENT_ANALYZER = True
logger.info("βœ… GPT-5 Intent Analyzer loaded")
except ImportError:
USE_INTENT_ANALYZER = False
logger.info("❌ Intent Analyzer not available")
# ===============================
# STOK API ENTEGRASYONU
# ===============================
STOCK_API_BASE = "https://video.trek-turkey.com/bizimhesap-proxy.php"
# Stock cache (5 dakikalik cache)
stock_cache = {}
CACHE_DURATION = 300 # 5 dakika (saniye cinsinden)
# Turkish character normalization
turkish_map = {'ı': 'i', 'ğ': 'g', 'ü': 'u', 'ş': 's', 'â': 'o', 'ç': 'c', 'İ': 'i', 'I': 'i'}
def normalize_turkish(text):
"""Turkce karakterleri normalize et"""
if not text:
return ""
text = unicodedata.normalize('NFD', text)
text = ''.join(char for char in text if unicodedata.category(char) != 'Mn')
for tr_char, en_char in turkish_map.items():
text = text.replace(tr_char, en_char)
return text.lower()
def fetch_warehouse_inventory(warehouse, product_name, search_terms):
"""Tek bir magazanin stok bilgisini al"""
try:
warehouse_id = warehouse['id']
warehouse_name = warehouse['title']
# DSW'yi ayri tut (gelecek stok icin)
is_dsw = 'DSW' in warehouse_name or 'Γ–N SΔ°PARİŞ' in warehouse_name.upper()
# Magaza stoklarini al
inventory_url = f"{STOCK_API_BASE}?action=inventory&warehouse={warehouse_id}&endpoint=inventory/{warehouse_id}"
inventory_response = requests.get(inventory_url, timeout=3, verify=False)
if inventory_response.status_code != 200:
return None
inventory_data = inventory_response.json()
# API yanitini kontrol et
if 'data' not in inventory_data or 'inventory' not in inventory_data['data']:
return None
products_list = inventory_data['data']['inventory']
# Beden terimleri kontrolu
size_terms = ['xs', 's', 'm', 'ml', 'l', 'xl', 'xxl', '2xl', '3xl', 'small', 'medium', 'large']
size_numbers = ['44', '46', '48', '50', '52', '54', '56', '58', '60']
# Arama terimlerinde beden var mi kontrol et
has_size_query = False
size_query = None
for term in search_terms:
if term in size_terms or term in size_numbers:
has_size_query = True
size_query = term
break
# Eger sadece beden sorgusu varsa (or: "m", "xl")
is_only_size_query = len(search_terms) == 1 and has_size_query
# Urunu ara
warehouse_variants = []
dsw_stock_count = 0
for product in products_list:
product_title = normalize_turkish(product.get('title', '')).lower()
original_title = product.get('title', '')
# Eger sadece beden sorgusu ise
if is_only_size_query:
if size_query in product_title.split() or f'({size_query})' in product_title or f' {size_query} ' in product_title or product_title.endswith(f' {size_query}'):
qty = int(product.get('qty', 0))
stock = int(product.get('stock', 0))
actual_stock = max(qty, stock)
if actual_stock > 0:
if is_dsw:
dsw_stock_count += actual_stock
continue
warehouse_variants.append(f"{original_title}: βœ“ Stokta")
else:
# Normal urun aramasi
if has_size_query:
non_size_terms = [t for t in search_terms if t != size_query]
product_matches = all(term in product_title for term in non_size_terms)
size_matches = size_query in product_title.split() or f'({size_query})' in product_title or f' {size_query} ' in product_title or product_title.endswith(f' {size_query}')
if product_matches and size_matches:
qty = int(product.get('qty', 0))
stock = int(product.get('stock', 0))
actual_stock = max(qty, stock)
if actual_stock > 0:
if is_dsw:
dsw_stock_count += actual_stock
continue
variant_info = original_title
possible_names = [
product_name.upper(),
product_name.lower(),
product_name.title(),
product_name.upper().replace('I', 'Δ°'),
product_name.upper().replace('Δ°', 'I'),
]
if 'fx sport' in product_name.lower():
possible_names.extend(['FX Sport AL 3', 'FX SPORT AL 3', 'Fx Sport Al 3'])
for possible_name in possible_names:
variant_info = variant_info.replace(possible_name, '').strip()
variant_info = ' '.join(variant_info.split())
if variant_info and variant_info != original_title:
warehouse_variants.append(f"{variant_info}: βœ“ Stokta")
else:
warehouse_variants.append(f"{original_title}: βœ“ Stokta")
else:
if all(term in product_title for term in search_terms):
qty = int(product.get('qty', 0))
stock = int(product.get('stock', 0))
actual_stock = max(qty, stock)
if actual_stock > 0:
if is_dsw:
dsw_stock_count += actual_stock
continue
variant_info = original_title
possible_names = [
product_name.upper(),
product_name.lower(),
product_name.title(),
product_name.upper().replace('I', 'Δ°'),
product_name.upper().replace('Δ°', 'I'),
]
if 'fx sport' in product_name.lower():
possible_names.extend(['FX Sport AL 3', 'FX SPORT AL 3', 'Fx Sport Al 3'])
for possible_name in possible_names:
variant_info = variant_info.replace(possible_name, '').strip()
variant_info = ' '.join(variant_info.split())
if variant_info and variant_info != original_title:
warehouse_variants.append(f"{variant_info}: βœ“ Stokta")
else:
warehouse_variants.append(f"{original_title}: βœ“ Stokta")
# Sonuc dondur
if warehouse_variants and not is_dsw:
return {'warehouse': warehouse_name, 'variants': warehouse_variants, 'is_dsw': False}
elif dsw_stock_count > 0:
return {'dsw_stock': dsw_stock_count, 'is_dsw': True}
return None
except Exception:
return None
def get_realtime_stock_parallel(product_name):
"""API'den gercek zamanli stok bilgisini cek - Paralel versiyon with cache"""
try:
# Cache kontrolu
cache_key = normalize_turkish(product_name).lower()
current_time = time.time()
if cache_key in stock_cache:
cached_data, cached_time = stock_cache[cache_key]
if current_time - cached_time < CACHE_DURATION:
logger.info(f"Cache'den donduruluyor: {product_name}")
return cached_data
# Once magaza listesini al
warehouses_url = f"{STOCK_API_BASE}?action=warehouses&endpoint=warehouses"
warehouses_response = requests.get(warehouses_url, timeout=3, verify=False)
if warehouses_response.status_code != 200:
logger.error(f"Magaza listesi alinamadi: {warehouses_response.status_code}")
return None
warehouses_data = warehouses_response.json()
if 'data' not in warehouses_data or 'warehouses' not in warehouses_data['data']:
logger.error("Magaza verisi bulunamadi")
return None
warehouses = warehouses_data['data']['warehouses']
# Urun adini normalize et
search_terms = normalize_turkish(product_name).lower().split()
logger.info(f"Aranan urun: {product_name} -> {search_terms}")
stock_info = {}
total_dsw_stock = 0
total_stock = 0
# Paralel olarak tum magazalari sorgula
with ThreadPoolExecutor(max_workers=10) as executor:
futures = {
executor.submit(fetch_warehouse_inventory, warehouse, product_name, search_terms): warehouse
for warehouse in warehouses
}
for future in as_completed(futures):
result = future.result()
if result:
if result.get('is_dsw'):
total_dsw_stock += result.get('dsw_stock', 0)
else:
warehouse_name = result['warehouse']
stock_info[warehouse_name] = result['variants']
total_stock += 1
# Sonucu olustur
if not stock_info:
if total_dsw_stock > 0:
result = f"{product_name}: Su anda magazalarda stokta yok, ancak yakinda gelecek. On siparis verebilirsiniz."
else:
result = f"{product_name}: Su anda hicbir magazada stokta bulunmuyor."
else:
prompt_lines = [f"{product_name} stok durumu:"]
for warehouse, variants in stock_info.items():
if isinstance(variants, list):
prompt_lines.append(f"- {warehouse}:")
for variant in variants:
prompt_lines.append(f" β€’ {variant}")
else:
prompt_lines.append(f"- {warehouse}: {variants}")
if total_stock > 0:
prompt_lines.append(f"βœ“ Urun stokta mevcut")
result = "\n".join(prompt_lines)
# Sonucu cache'e kaydet
stock_cache[cache_key] = (result, current_time)
return result
except Exception as e:
logger.error(f"API hatasi: {e}")
return None
def is_stock_query(message):
"""Mesajin stok sorgusu olup olmadigini kontrol et - Basit yedek kontrol"""
# Bu fonksiyon artik sadece yedek olarak kullaniliyor
# Ana tespit Intent Analyzer tarafindan yapiliyor
basic_keywords = ['stok', 'stock', 'var mΔ±', 'mevcut']
message_lower = message.lower()
return any(keyword in message_lower for keyword in basic_keywords)
# ===============================
# MAGAZA STOK BILGISI CEKME
# ===============================
def get_warehouse_stock(product_name):
"""B2B API'den magaza stok bilgilerini cek - GPT-5 enhanced"""
# Try GPT-5 complete smart search (BF algorithm)
if USE_GPT5_SEARCH:
try:
gpt5_result = get_warehouse_stock_smart_with_price(product_name)
if gpt5_result and isinstance(gpt5_result, list):
if all(isinstance(item, str) for item in gpt5_result):
return gpt5_result
warehouse_info = []
for item in gpt5_result:
if isinstance(item, dict):
info = f"πŸ“¦ {item.get('name', '')}"
if item.get('variant'):
info += f" ({item['variant']})"
if item.get('warehouses'):
info += f"\nπŸ“ Mevcut: {', '.join(item['warehouses'])}"
if item.get('price'):
info += f"\nπŸ’° {item['price']}"
warehouse_info.append(info)
else:
warehouse_info.append(str(item))
return warehouse_info if warehouse_info else None
except Exception as e:
logger.error(f"GPT-5 warehouse search error: {e}")
# Fallback to original search
try:
import re
warehouse_url = 'https://video.trek-turkey.com/bizimhesap-warehouse-xml-b2b-api-v2.php'
response = requests.get(warehouse_url, verify=False, timeout=15)
if response.status_code != 200:
return None
root = ET.fromstring(response.content)
# Normalize search product name
search_name = normalize_turkish(product_name.lower().strip())
search_name = search_name.replace('(2026)', '').replace('(2025)', '').replace(' gen 3', '').replace(' gen', '').strip()
search_words = search_name.split()
best_matches = []
exact_matches = []
variant_matches = []
candidates = []
size_color_words = ['s', 'm', 'l', 'xl', 'xs', 'small', 'medium', 'large',
'turuncu', 'siyah', 'beyaz', 'mavi', 'kirmizi', 'yesil',
'orange', 'black', 'white', 'blue', 'red', 'green']
variant_words = [word for word in search_words if word in size_color_words]
product_words = [word for word in search_words if word not in size_color_words]
is_size_color_query = len(variant_words) > 0 and len(search_words) <= 4
if is_size_color_query:
for product in root.findall('Product'):
product_name_elem = product.find('ProductName')
variant_elem = product.find('ProductVariant')
if product_name_elem is not None and product_name_elem.text:
xml_product_name = product_name_elem.text.strip()
normalized_product_name = normalize_turkish(xml_product_name.lower())
product_name_matches = True
if product_words:
product_name_matches = all(word in normalized_product_name for word in product_words)
if product_name_matches:
if variant_elem is not None and variant_elem.text:
variant_text = normalize_turkish(variant_elem.text.lower().replace('-', ' '))
if all(word in variant_text for word in variant_words):
variant_matches.append((product, xml_product_name, variant_text))
if variant_matches:
candidates = variant_matches
else:
is_size_color_query = False
if not is_size_color_query or not candidates:
for product in root.findall('Product'):
product_name_elem = product.find('ProductName')
if product_name_elem is not None and product_name_elem.text:
xml_product_name = product_name_elem.text.strip()
normalized_xml = normalize_turkish(xml_product_name.lower())
normalized_xml = normalized_xml.replace('(2026)', '').replace('(2025)', '').replace(' gen 3', '').replace(' gen', '').strip()
xml_words = normalized_xml.split()
if len(search_words) >= 2 and len(xml_words) >= 2:
search_key = f"{search_words[0]} {search_words[1]}"
xml_key = f"{xml_words[0]} {xml_words[1]}"
if search_key == xml_key:
exact_matches.append((product, xml_product_name, normalized_xml))
if not candidates:
candidates = exact_matches if exact_matches else []
if not candidates:
for product in root.findall('Product'):
product_name_elem = product.find('ProductName')
if product_name_elem is not None and product_name_elem.text:
xml_product_name = product_name_elem.text.strip()
normalized_xml = normalize_turkish(xml_product_name.lower())
normalized_xml = normalized_xml.replace('(2026)', '').replace('(2025)', '').replace(' gen 3', '').replace(' gen', '').strip()
xml_words = normalized_xml.split()
common_words = set(search_words) & set(xml_words)
if (len(common_words) >= 2 and
len(search_words) > 0 and len(xml_words) > 0 and
search_words[0] == xml_words[0]):
best_matches.append((product, xml_product_name, normalized_xml, len(common_words)))
if best_matches:
max_common = max(match[3] for match in best_matches)
candidates = [(match[0], match[1], match[2]) for match in best_matches if match[3] == max_common]
warehouse_stock_map = {}
for product, xml_name, _ in candidates:
for warehouse in product.findall('Warehouse'):
name_elem = warehouse.find('Name')
stock_elem = warehouse.find('Stock')
if name_elem is not None and stock_elem is not None:
warehouse_name = name_elem.text if name_elem.text else "Bilinmeyen"
try:
stock_count = int(stock_elem.text) if stock_elem.text else 0
if stock_count > 0:
if warehouse_name in warehouse_stock_map:
warehouse_stock_map[warehouse_name] += stock_count
else:
warehouse_stock_map[warehouse_name] = stock_count
except (ValueError, TypeError):
pass
if warehouse_stock_map:
all_warehouse_info = []
for warehouse_name, total_stock in warehouse_stock_map.items():
all_warehouse_info.append(f"{warehouse_name}: Stokta var")
return all_warehouse_info
else:
return ["Hicbir magazada stokta bulunmuyor"]
except Exception as e:
logger.error(f"Magaza stok bilgisi cekme hatasi: {e}")
return None
# ===============================
# TREK BISIKLET URUNLERINI CEKME
# ===============================
try:
url = 'https://www.trekbisiklet.com.tr/output/8582384479'
response = requests.get(url, verify=False, timeout=10)
root = ET.fromstring(response.content)
all_items = root.findall('item')
products = []
for item in all_items:
stock_number = 0
stock_amount = "stokta degil"
price = ""
price_eft = ""
product_link = ""
picture_url = ""
category_tree = ""
category_label = ""
stock_code = ""
root_product_stock_code = ""
is_option_of_product = "0"
is_optioned_product = "0"
rootlabel = item.find('rootlabel')
if rootlabel is None or not rootlabel.text:
continue
full_name = rootlabel.text.strip()
name_words = full_name.lower().split()
name = name_words[0] if name_words else "unknown"
# STOK KONTROLU - SAYISAL KARSILASTIRMA
stock_element = item.find('stockAmount')
if stock_element is not None and stock_element.text:
try:
stock_number = int(stock_element.text.strip())
stock_amount = "stokta" if stock_number > 0 else "stokta degil"
except (ValueError, TypeError):
stock_number = 0
stock_amount = "stokta degil"
# Urun linki - HER URUN ICIN AL
link_element = item.find('productLink')
product_link = link_element.text if link_element is not None and link_element.text else ""
# Urun resmi - HER URUN ICIN AL
picture_element = item.find('picture1Path')
picture_url = picture_element.text if picture_element is not None and picture_element.text else ""
# Kategori bilgileri - HER URUN ICIN AL
category_tree_element = item.find('categoryTree')
category_tree = category_tree_element.text if category_tree_element is not None and category_tree_element.text else ""
category_label_element = item.find('productCategoryLabel')
category_label = category_label_element.text if category_label_element is not None and category_label_element.text else ""
# Stock Code (SKU) - HER URUN ICIN AL
stock_code_element = item.find('stockCode')
stock_code = stock_code_element.text if stock_code_element is not None and stock_code_element.text else ""
# Variant/main product iliski alanlari
root_product_stock_code_element = item.find('rootProductStockCode')
root_product_stock_code = root_product_stock_code_element.text if root_product_stock_code_element is not None and root_product_stock_code_element.text else ""
is_option_of_product_element = item.find('isOptionOfAProduct')
is_option_of_product = is_option_of_product_element.text if is_option_of_product_element is not None and is_option_of_product_element.text else "0"
is_optioned_product_element = item.find('isOptionedProduct')
is_optioned_product = is_optioned_product_element.text if is_optioned_product_element is not None and is_optioned_product_element.text else "0"
# Stokta olan urunler icin fiyat bilgilerini al
if stock_amount == "stokta":
# Normal fiyat
price_element = item.find('priceTaxWithCur')
price_str = price_element.text if price_element is not None and price_element.text else "0"
# Kampanya fiyati
price_rebate_element = item.find('priceRebateWithTax')
price_rebate_str = price_rebate_element.text if price_rebate_element is not None and price_rebate_element.text else ""
final_price_str = price_str
if price_rebate_str:
try:
normal_price = float(price_str)
rebate_price = float(price_rebate_str)
if rebate_price < normal_price:
final_price_str = price_rebate_str
except (ValueError, TypeError):
final_price_str = price_str
# EFT fiyati
price_eft_element = item.find('priceEft')
price_eft_str = price_eft_element.text if price_eft_element is not None and price_eft_element.text else ""
# Fiyat formatting
try:
price_float = float(final_price_str)
if price_float > 200000:
price = str(round(price_float / 5000) * 5000)
elif price_float > 30000:
price = str(round(price_float / 1000) * 1000)
elif price_float > 10000:
price = str(round(price_float / 100) * 100)
else:
price = str(round(price_float / 10) * 10)
except (ValueError, TypeError):
price = final_price_str
# EFT fiyat formatting
if price_eft_str:
try:
price_eft_float = float(price_eft_str)
if price_eft_float > 200000:
price_eft = str(round(price_eft_float / 5000) * 5000)
elif price_eft_float > 30000:
price_eft = str(round(price_eft_float / 1000) * 1000)
elif price_eft_float > 10000:
price_eft = str(round(price_eft_float / 100) * 100)
else:
price_eft = str(round(price_eft_float / 10) * 10)
except (ValueError, TypeError):
price_eft = price_eft_str
else:
try:
price_eft_float = float(price_str)
price_eft = str(round(price_eft_float * 0.975 / 10) * 10)
except:
price_eft = ""
# Urun bilgilerini tuple olarak olustur
item_info = (stock_amount, price, product_link, price_eft, str(stock_number),
picture_url, category_tree, category_label, stock_code,
root_product_stock_code, is_option_of_product, is_optioned_product)
products.append((name, item_info, full_name))
logger.info(f"βœ… {len(products)} urun yuklendi")
except Exception as e:
logger.error(f"❌ Urun yukleme hatasi: {e}")
import traceback
traceback.print_exc()
products = []
# ===============================
# SISTEM MESAJLARI
# ===============================
def get_system_messages():
"""Sistem mesajlarini yukle - Moduler prompts'tan"""
try:
return get_active_prompts()
except:
# Fallback sistem mesajlari
return [
{"role": "system", "content": "Sen Trek bisiklet uzmani AI asistanisin. Trek ve Electra bisikletler konusunda uzmansin. Stokta bulunan urunlerin fiyat bilgilerini verebilirsin."}
]
# ===============================
# SOHBET HAFIZASI SISTEMI
# ===============================
conversation_memory = {}
def get_conversation_context(phone_number):
"""Kullanicinin sohbet gecmisini getir"""
if phone_number not in conversation_memory:
conversation_memory[phone_number] = {
"messages": [],
"current_category": None,
"current_product": None,
"current_product_link": None,
"current_product_price": None,
"last_activity": None
}
return conversation_memory[phone_number]
def add_to_conversation(phone_number, user_message, ai_response):
"""Sohbet gecmisine ekle"""
context = get_conversation_context(phone_number)
context["last_activity"] = datetime.datetime.now()
context["messages"].append({
"user": user_message,
"ai": ai_response,
"timestamp": datetime.datetime.now()
})
# Sadece son 10 mesaji tut
if len(context["messages"]) > 10:
context["messages"] = context["messages"][-10:]
detect_category(phone_number, user_message, ai_response)
def detect_category(phone_number, user_message, ai_response):
"""Konusulan kategoriyi ve tam urun adini tespit et"""
context = get_conversation_context(phone_number)
categories = {
"marlin": ["marlin", "marlin+"],
"madone": ["madone"],
"emonda": ["emonda", "Γ©monda"],
"domane": ["domane"],
"checkpoint": ["checkpoint"],
"fuel": ["fuel", "fuel ex", "fuel exe"],
"procaliber": ["procaliber"],
"supercaliber": ["supercaliber"],
"fx": ["fx"],
"ds": ["ds", "dual sport"],
"powerfly": ["powerfly"],
"rail": ["rail"],
"verve": ["verve"],
"townie": ["townie"]
}
user_lower = user_message.lower()
for category, keywords in categories.items():
for keyword in keywords:
if keyword in user_lower:
context["current_category"] = category
# TAM URUN ADINI CIKAR - ornegin "Marlin 5", "Madone SLR 9"
# Model numarasini da yakala
import re
# Keyword + sayi pattern'i ara (ornegin "marlin 5", "madone slr 9")
pattern = rf'{keyword}\s*\+?\s*(?:slr\s*)?(\d+)?'
match = re.search(pattern, user_lower)
if match:
model_num = match.group(1)
if model_num:
# Tam urun adi: "marlin 5" veya "madone slr 9"
full_product = match.group(0).strip()
context["current_product"] = full_product
else:
# Sadece kategori adi
context["current_product"] = keyword
else:
context["current_product"] = keyword
return category
return context.get("current_category")
def build_context_messages(phone_number, current_message):
"""Sohbet gecmisi ile sistem mesajlarini olustur"""
context = get_conversation_context(phone_number)
system_messages = get_system_messages()
# Mevcut kategori varsa, sistem mesajina ekle - GUCLENDIRILMIS BAGLAIM
if context.get("current_category"):
cat = context['current_category'].upper()
category_msg = f"""KRITIK BAGLAIM BILGISI:
Musteri su anda {cat} modelleri hakkinda konusuyor.
Butun sorulari bu baglamda cevapla.
"Hangi model var", "stok var mi", "fiyat ne" gibi sorular {cat} icin sorulmus demektir.
DS, FX, Verve gibi BASKA kategorilerden bahsetme - sadece {cat} hakkinda konusuyoruz!"""
system_messages.append({"role": "system", "content": category_msg})
# Son konusulan urun bilgilerini ekle (link, fiyat sorulari icin)
if context.get("current_product"):
product_context = f"Son konusulan urun: {context['current_product']}"
if context.get("current_product_link"):
product_context += f"\nUrun linki: {context['current_product_link']}"
if context.get("current_product_price"):
product_context += f"\nUrun fiyati: {context['current_product_price']}"
system_messages.append({"role": "system", "content": product_context})
# Son 3 mesaj alisverisini ekle
recent_messages = context["messages"][-3:] if context["messages"] else []
all_messages = system_messages.copy()
# Gecmis mesajlari ekle
for msg in recent_messages:
all_messages.append({"role": "user", "content": msg["user"]})
all_messages.append({"role": "assistant", "content": msg["ai"]})
# Mevcut mesaji ekle
all_messages.append({"role": "user", "content": current_message})
return all_messages
# ===============================
# HYBRID MODEL MESAJ ISLEME
# ===============================
def extract_product_from_vision_response(response):
"""
GPT Vision yanitindan urun adini cikarir
Ornek: "Trek Domane+ SLR 7 AXS" -> "Domane+ SLR 7 AXS"
"""
import re
# Bilinen Trek model pattern'leri
patterns = [
# Trek Domane+ SLR 7 AXS gibi tam isimler
r'Trek\s+((?:Domane|Madone|Emonda|Marlin|Fuel|Rail|Powerfly|Checkpoint|FX|Verve|Dual\s*Sport|Procaliber|Supercaliber|Roscoe|Top\s*Fuel|Slash|Remedy|X-?Caliber|Allant)[+]?\s*(?:SLR|SL|Gen|EX|EXe)?\s*\d*\s*(?:AXS|Di2|eTap|Frameset)?)',
# Sadece model adi + numara
r'((?:Domane|Madone|Emonda|Marlin|Fuel|Rail|Powerfly|Checkpoint|FX|Verve|Dual\s*Sport|Procaliber|Supercaliber|Roscoe|Top\s*Fuel|Slash|Remedy|X-?Caliber|Allant)[+]?\s*(?:SLR|SL|Gen|EX|EXe)?\s*\d+\s*(?:AXS|Di2|eTap|Frameset)?)',
# Model + SLR/SL + numara
r'((?:Domane|Madone|Emonda)[+]?\s+(?:SLR|SL)\s*\d+)',
# Marlin + numara
r'(Marlin\s*\d+)',
# FX + numara
r'(FX\s*(?:Sport)?\s*\d+)',
]
response_lower = response.lower()
for pattern in patterns:
match = re.search(pattern, response, re.IGNORECASE)
if match:
product = match.group(1).strip()
# "Trek " prefix varsa kaldir
product = re.sub(r'^Trek\s+', '', product, flags=re.IGNORECASE)
return product
return None
def process_whatsapp_message_with_media(user_message, phone_number, media_urls, media_types):
"""
GORSEL MESAJ ISLEME - GPT-4o Vision kullanir
"""
try:
logger.info(f"πŸ–ΌοΈ Gorsel analizi basliyor: {len(media_urls)} medya")
logger.info(f"πŸ“Ž Medya URL'leri: {media_urls}")
logger.info(f"πŸ“Ž Medya tipleri: {media_types}")
# Pasif profil analizi
try:
profile_analysis = analyze_user_message(phone_number, user_message)
logger.info(f"πŸ“Š Profil analizi: {phone_number} -> {profile_analysis}")
except:
pass
# Gorsel icin GPT-4o kullan
model = get_model_for_request(has_media=True)
# Sohbet gecmisi ile sistem mesajlarini olustur
messages = build_context_messages(phone_number, user_message if user_message else "Gonderilen gorseli analiz et")
# GPT-4o Vision icin mesaj hazirla
vision_message = {
"role": "user",
"content": []
}
# Metin mesaji varsa ekle
# KRITIK: Kisa sorularda (var mi, fiyat, stok) gorseli dikkate alarak cevap vermesini sagla
if user_message and user_message.strip():
short_questions = ['var mi', 'var mΔ±', 'stok', 'fiyat', 'kac', 'kaΓ§', 'ne kadar', 'beden', 'renk']
is_short_question = len(user_message.strip()) < 20 and any(q in user_message.lower() for q in short_questions)
if is_short_question:
# Kisa soru - gorseli referans alarak cevap vermesini iste
enhanced_text = f"Gorseldeki BISIKLETI dikkatlice incele ve model adini tespit et. Musteri bu bisiklet icin '{user_message}' soruyor. Gorseldeki bisikletin TAM MODEL ADINI (ornegin 'Trek Domane+ SLR 7 AXS') belirle ve buna gore cevap ver."
vision_message["content"].append({
"type": "text",
"text": enhanced_text
})
else:
vision_message["content"].append({
"type": "text",
"text": user_message
})
else:
vision_message["content"].append({
"type": "text",
"text": "Bu gorselde ne var? Eger bisiklet veya bisiklet parcasi ise detayli acikla."
})
# Medya URL'lerini isle
valid_images = 0
for i, media_url in enumerate(media_urls):
media_type = media_types[i] if i < len(media_types) else "image/jpeg"
# Sadece gorsel medyalari isle
if media_type and media_type.startswith('image/'):
try:
# Twilio medya URL'sini proxy uzerinden cevir
if 'api.twilio.com' in media_url:
import re
match = re.search(r'/Messages/([^/]+)/Media/([^/]+)', media_url)
if match:
message_sid = match.group(1)
media_sid = match.group(2)
proxy_url = f"https://video.trek-turkey.com/twilio-media-proxy.php?action=media&message={message_sid}&media={media_sid}"
logger.info(f"πŸ”„ Proxy URL olusturuldu: {proxy_url}")
# Proxy URL'sinin calisip calismadigini kontrol et
try:
test_response = requests.head(proxy_url, timeout=5, verify=False)
if test_response.status_code == 200:
vision_message["content"].append({
"type": "image_url",
"image_url": {"url": proxy_url}
})
valid_images += 1
logger.info(f"βœ… Proxy URL gecerli: {proxy_url}")
else:
logger.error(f"❌ Proxy URL calismiyor: {test_response.status_code}")
vision_message["content"].append({
"type": "image_url",
"image_url": {"url": media_url}
})
valid_images += 1
except Exception as proxy_error:
logger.error(f"❌ Proxy test hatasi: {proxy_error}")
vision_message["content"].append({
"type": "image_url",
"image_url": {"url": media_url}
})
valid_images += 1
else:
logger.error(f"❌ Twilio URL parse edilemedi: {media_url}")
else:
vision_message["content"].append({
"type": "image_url",
"image_url": {"url": media_url}
})
valid_images += 1
logger.info(f"βœ… Dogrudan URL eklendi: {media_url}")
except Exception as url_error:
logger.error(f"❌ URL isleme hatasi: {url_error}")
else:
logger.warning(f"⚠️ Gorsel olmayan medya atlandi: {media_type}")
# Hic gecerli gorsel yoksa
if valid_images == 0:
logger.error("❌ Hic gecerli gorsel bulunamadi")
return "Gonderdiginiz gorsel islenemedi. Lutfen farkli bir gorsel gonderin veya sorunuzu yazili olarak iletin."
logger.info(f"βœ… {valid_images} gorsel islenecek")
# Son user mesajini vision mesajiyla degistir
messages = [msg for msg in messages if not (msg.get("role") == "user" and msg == messages[-1])]
messages.append(vision_message)
# Sistem mesajina bisiklet tanima talimati ekle
bike_recognition_prompt = {
"role": "system",
"content": """Gonderilen gorselleri dikkatle analiz et:
1. Eger bisiklet veya bisiklet parcasi goruyorsan, detaylica tanimla (marka, model, renk, beden, ozellikler)
2. Trek bisiklet ise modeli tahmin etmeye calis
3. Stok veya fiyat sorulursa, gorseldeki bisikletin ozelliklerini belirterek bilgi ver
4. Gorsel net degilse veya tanimlanamiyorsa, kullanicidan daha net bir gorsel istemek yerine, gorselde gorduklerini acikla
5. Eger gorsel bisikletle ilgili degilse, ne gordugunu kisaca acikla"""
}
messages.insert(0, bike_recognition_prompt)
if not OPENAI_API_KEY:
logger.error("❌ OpenAI API anahtari eksik")
return "Sistem hatasi olustu. Lutfen daha sonra tekrar deneyin."
logger.info(f"πŸ“€ GPT Vision API'ye gonderiliyor: {len(messages)} mesaj, {valid_images} gorsel")
payload = {
"model": model, # GPT-4o
"messages": messages,
"max_tokens": 800,
"temperature": 0.3
}
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {OPENAI_API_KEY}"
}
response = requests.post(API_URL, headers=headers, json=payload, timeout=30)
logger.info(f"πŸ“₯ API yaniti: {response.status_code}")
if response.status_code == 200:
result = response.json()
ai_response = result['choices'][0]['message']['content']
logger.info(f"βœ… Gorsel analizi basarili: {ai_response[:100]}...")
# KRITIK: Gorselden urun adini cikar ve GERCEK stok kontrolu yap
try:
# app.py'deki get_warehouse_stock fonksiyonunu kullan
# GPT yanitindan urun adini cikar
product_name = extract_product_from_vision_response(ai_response)
if product_name:
logger.info(f"πŸ” Gorselden tespit edilen urun: {product_name}")
# GERCEK stok kontrolu yap
stock_result = get_warehouse_stock(product_name)
# Sonuc list veya string olabilir
stock_info = None
if stock_result:
if isinstance(stock_result, list):
stock_info = chr(10).join(str(item) for item in stock_result)
else:
stock_info = str(stock_result)
if stock_info and len(stock_info) > 5:
logger.info(f"βœ… Stok bilgisi bulundu: {stock_info[:100]}...")
# GPT yanlis "stokta yok" dediyse duzelt
if "stokta bulunmuyor" in ai_response.lower() or "stokta yok" in ai_response.lower():
if "stokta bulunmuyor" not in stock_info.lower():
# Yanlis bilgiyi kaldir ve dogru stok bilgisini ekle
ai_response = re.sub(
r'[^.]*stok[^.]*bulunmuyor[^.]*[.]?',
'',
ai_response,
flags=re.IGNORECASE
)
ai_response = ai_response.strip()
# Stok bilgisini ekle (eger zaten yoksa)
if "Stok:" not in ai_response and "stokta" not in stock_info.lower():
ai_response = ai_response + "\n\n" + stock_info
elif "Stok:" not in ai_response:
ai_response = ai_response + "\n\n" + stock_info
else:
logger.info(f"⚠️ Urun icin stok bilgisi bulunamadi: {product_name}")
else:
logger.info("⚠️ Gorselden urun adi cikarilamadi")
except Exception as stock_error:
logger.error(f"❌ Vision stok kontrolu hatasi: {stock_error}")
# Context'e urun adini kaydet (sonraki sorular icin)
if product_name:
try:
ctx = get_conversation_context(phone_number)
ctx["current_product"] = product_name
ctx["current_category"] = product_name.split()[0].lower()
logger.info(f"πŸ“ Vision context kaydedildi: {product_name}")
except:
pass
# WhatsApp icin formatla
try:
formatted_response = extract_product_info_whatsapp(ai_response)
except:
formatted_response = ai_response
# Sohbet gecmisine ekle
add_to_conversation(phone_number, f"[Gorsel gonderildi] {user_message if user_message else ''}", formatted_response)
return formatted_response
else:
error_detail = response.text[:500] if response.text else "Detay yok"
logger.error(f"❌ OpenAI API Error: {response.status_code} - {error_detail}")
if response.status_code == 400:
return "Gorsel formati desteklenmiyor. Lutfen JPG veya PNG formatinda bir gorsel gonderin."
elif response.status_code == 413:
return "Gorsel boyutu cok buyuk. Lutfen daha kucuk bir gorsel gonderin."
elif response.status_code == 429:
return "Sistem su anda yogun. Lutfen birkac saniye sonra tekrar deneyin."
else:
return "Gorsel su anda analiz edilemiyor. Sorunuzu yazili olarak iletebilir misiniz?"
except requests.exceptions.Timeout:
logger.error("❌ API timeout hatasi")
return "Islem zaman asimina ugradi. Lutfen tekrar deneyin."
except Exception as e:
logger.error(f"❌ Medya isleme hatasi: {e}")
import traceback
traceback.print_exc()
return "Gorsel islenirken bir sorun olustu. Lutfen sorunuzu yazili olarak iletin veya farkli bir gorsel deneyin."
def process_whatsapp_message_with_memory(user_message, phone_number):
"""
METIN MESAJ ISLEME - GPT-5.2 kullanir (daha akilli)
"""
try:
# Metin icin GPT-5.2 kullan
model = get_model_for_request(has_media=False)
# Pasif profil analizi
try:
profile_analysis = analyze_user_message(phone_number, user_message)
logger.info(f"πŸ“Š Profil analizi: {phone_number}")
except:
pass
# πŸ”” Yeni Magaza Bildirim Sistemi - Mehmet Bey'e otomatik bildirim
if USE_STORE_NOTIFICATION:
try:
should_notify_mehmet, notification_reason, urgency = should_notify_mehmet_bey(user_message)
if not should_notify_mehmet and USE_INTENT_ANALYZER:
context = get_conversation_context(phone_number)
intent_analysis = analyze_customer_intent(user_message, context)
should_notify_mehmet, notification_reason, urgency = should_notify_mehmet_bey(user_message, intent_analysis)
else:
intent_analysis = None
if should_notify_mehmet:
if intent_analysis:
product = intent_analysis.get("product") or "Belirtilmemis"
else:
context = get_conversation_context(phone_number)
product = context.get("current_category") or "Urun belirtilmemis"
if "rezervasyon" in notification_reason.lower() or urgency == "high":
action = "reserve"
elif "magaza" in notification_reason.lower() or "lokasyon" in notification_reason.lower():
action = "info"
elif "fiyat" in notification_reason.lower() or "odeme" in notification_reason.lower():
action = "price"
else:
action = "info"
additional_info = f"{notification_reason}\n\nMusteri Mesaji: '{user_message}'"
if urgency == "high":
additional_info = "⚠️ YUKSEK ONCELIK ⚠️\n" + additional_info
result = send_store_notification(
customer_phone=phone_number,
customer_name=None,
product_name=product,
action=action,
store_name=None,
additional_info=additional_info
)
if result:
logger.info(f"βœ… Mehmet Bey'e bildirim gonderildi!")
logger.info(f" πŸ“ Sebep: {notification_reason}")
logger.info(f" ⚑ Oncelik: {urgency}")
logger.info(f" πŸ“¦ Urun: {product}")
# TAKIP SISTEMINI KONTROL ET
if USE_FOLLOW_UP and follow_up_manager:
try:
follow_up_analysis = analyze_message_for_follow_up(user_message)
if follow_up_analysis and follow_up_analysis.get("needs_follow_up"):
follow_up = follow_up_manager.create_follow_up(
customer_phone=phone_number,
product_name=product,
follow_up_type=follow_up_analysis["follow_up_type"],
original_message=user_message,
follow_up_hours=follow_up_analysis.get("follow_up_hours", 24),
notes=follow_up_analysis.get("reason", "")
)
logger.info(f"πŸ“Œ Takip olusturuldu: {follow_up_analysis.get('reason', '')}")
except Exception as follow_up_error:
logger.error(f"Takip sistemi hatasi: {follow_up_error}")
except Exception as notify_error:
logger.error(f"Bildirim hatasi: {notify_error}")
# Sohbet gecmisi ile mesajlari olustur
messages = build_context_messages(phone_number, user_message)
# Intent Analyzer veya context'ten urun bilgisini al
detected_product = None
intent_analysis = None # Scope disinda da kullanilacak
if USE_INTENT_ANALYZER:
try:
context = get_conversation_context(phone_number)
intent_analysis = analyze_customer_intent(user_message, context)
if intent_analysis and intent_analysis.get("product"):
detected_product = intent_analysis.get("product")
logger.info(f"🎯 Intent'ten tespit edilen urun: {detected_product}")
except Exception as e:
logger.error(f"Intent analiz hatasi: {e}")
intent_analysis = None
# Eger Intent'ten urun bulunamadiysa, context'ten al
# ONEMLI: current_product TAM URUN ADINI icerir (ornegin "marlin 5")
# current_category ise sadece kategori adidir (ornegin "marlin")
if not detected_product:
context = get_conversation_context(phone_number)
# Oncelikle tam urun adini dene
if context.get("current_product"):
detected_product = context.get("current_product")
logger.info(f"🎯 Context'ten tespit edilen TAM URUN: {detected_product}")
elif context.get("current_category"):
detected_product = context.get("current_category")
logger.info(f"🎯 Context'ten tespit edilen kategori: {detected_product}")
# Stok sorgusu icin kullanilacak urun adi
stock_query_product = detected_product if detected_product else user_message
# Urun bilgilerini ekle
input_words = user_message.lower().split()
# Detected product'i da input_words'e ekle
if detected_product:
input_words.extend(detected_product.lower().split())
# Bulunan urunun link ve gorsel bilgilerini sakla
found_product_link = None
found_product_image = None
found_product_name = None
best_match_score = 0
# Kullanici mesaji veya detected_product'i normalize et
search_text = (detected_product or user_message).lower()
search_words = search_text.split()
# AKILLI URUN ESLESTIRME
# 1. Kategori bazli filtreleme - Bisiklet aramasinda aksesuar gosterme
# 2. Urun tipi benzerligi - Ayni tip urunler oncelikli
# 3. Kelime eslesmesi - En cok eslesen urun
def is_bicycle_search(text):
"""Arama bisiklet mi yoksa aksesuar mi?"""
bike_indicators = ['madone', 'domane', 'emonda', 'checkpoint', 'fuel', 'slash',
'marlin', 'procaliber', 'supercaliber', 'fx', 'verve', 'dual sport',
'powerfly', 'rail', 'allant', 'bisiklet', 'bike']
text_lower = text.lower()
return any(ind in text_lower for ind in bike_indicators)
def get_product_type(category_tree, product_name):
"""Urun tipini belirle"""
cat_lower = (category_tree or "").lower()
name_lower = (product_name or "").lower()
# Kategori agacindan tip belirle
if 'bisiklet' in cat_lower or 'bike' in cat_lower:
if 'yol' in cat_lower or 'road' in cat_lower:
return 'road_bike'
elif 'dag' in cat_lower or 'mountain' in cat_lower or 'mtb' in cat_lower:
return 'mtb'
elif 'elektrik' in cat_lower or 'e-bike' in cat_lower:
return 'ebike'
elif 'sehir' in cat_lower or 'hybrid' in cat_lower:
return 'hybrid'
return 'bicycle'
elif 'aksesuar' in cat_lower or 'parΓ§a' in cat_lower or 'parca' in cat_lower or 'accessory' in cat_lower or 'yedek' in cat_lower:
return 'accessory'
# Isimden tip belirle (fallback)
# ONEMLI: Aksesuar kontrolu ONCE yapilmali cunku "Domane Kadro Kulagi" gibi
# urunlerde model adi gecebilir ama aksesuar kelimeleri varsa aksesuar'dir
accessory_keywords = ['sele', 'gidon', 'pedal', 'zincir', 'lastik', 'jant', 'fren', 'vites',
'kadro kulağı', 'kadro kulagi', 'kulak', 'kablo', 'kasnak', 'dişli',
'zil', 'far', 'lamba', 'pompa', 'kilit', 'Γ§anta', 'canta', 'suluk',
'gΓΆzlΓΌk', 'gozluk', 'kask', 'eldiven', 'ayakkabΔ±', 'ayakkabi',
'forma', 'tayt', 'şort', 'sort', 'mont', 'yağmurluk', 'yagmurluk']
if any(x in name_lower for x in accessory_keywords):
return 'accessory'
if any(x in name_lower for x in ['madone', 'domane', 'emonda', 'checkpoint', 'fuel', 'marlin', 'fx']):
return 'bicycle'
return 'unknown'
def calculate_smart_match_score(search_words, product_name, product_category, is_bike_search):
"""Akilli eslesme skoru hesapla"""
product_name_lower = product_name.lower()
product_words = product_name_lower.split()
product_type = get_product_type(product_category, product_name)
# Temel kelime eslesmesi
base_score = sum(1 for word in search_words if word in product_name_lower)
# Kategori uyumu bonusu/cezasi
if is_bike_search:
if product_type == 'bicycle':
base_score += 2 # Bisiklet aramasinda bisiklet bulunca bonus
elif product_type == 'accessory':
base_score -= 100 # Bisiklet aramasinda aksesuar KESINLIKLE gosterilmemeli
# KRITIK VARYANT KONTROLU
# AXS, Di2, eTap gibi varyantlar FARKLI URUNLERDIR
# Kullanici "Madone SLR 9" diyorsa "Madone SLR 9 AXS" GOSTERILMEMELI
critical_variants = ['axs', 'etap', 'di2', 'frameset']
# Urunde olan kritik varyantlar
product_critical_variants = [v for v in critical_variants if v in product_name_lower]
# Kullanicinin soyledigi kritik varyantlar
user_critical_variants = [v for v in critical_variants if v in ' '.join(search_words)]
# Urunde kritik varyant var AMA kullanici soylemedi -> BUYUK CEZA
for variant in product_critical_variants:
if variant not in user_critical_variants:
base_score -= 50 # Bu urun gosterilmemeli
# Kullanici kritik varyant soyledi AMA urunde yok -> CEZA
for variant in user_critical_variants:
if variant not in product_critical_variants:
base_score -= 50 # Bu urun gosterilmemeli
# Tam esleme bonusu - Tum arama kelimeleri urunde varsa
all_words_match = all(word in product_name_lower for word in search_words if len(word) > 2)
if all_words_match and len(search_words) > 1:
base_score += 3
# Model numarasi eslesmesi - "9" araniyorsa "9" olmali, "7" olmamali
for word in search_words:
if word.isdigit():
if word in product_words:
base_score += 2 # Tam numara eslesmesi
else:
# Farkli numara varsa ceza
for pword in product_words:
if pword.isdigit() and pword != word:
base_score -= 20 # Farkli model numarasi
return base_score
# Arama bisiklet mi?
is_bike_search = is_bicycle_search(search_text)
for product_info in products:
product_full_name = product_info[2] # Tam urun adi
product_category = product_info[1][6] if len(product_info[1]) > 6 else "" # category_tree
# Akilli skor hesapla
match_score = calculate_smart_match_score(
search_words,
product_full_name,
product_category,
is_bike_search
)
# Daha iyi eslesme bulduysa guncelle
if match_score > best_match_score and product_info[1][0] == "stokta":
best_match_score = match_score
normal_price = f"Fiyat: {product_info[1][1]} TL"
if product_info[1][3]:
eft_price = f"Havale: {product_info[1][3]} TL"
price_info = f"{normal_price}, {eft_price}"
else:
price_info = normal_price
# Urun linki ve gorseli al - EN IYI ESLESEN URUN
if product_info[1][2]: # product_link
found_product_link = product_info[1][2]
if product_info[1][5]: # picture_url
found_product_image = product_info[1][5]
found_product_name = product_info[2]
# System message'a LINK EKLEME - cunku GPT linki yanitina dahil ediyor
# ve sonra biz de ekledigimizde 2 kere gorunuyor
new_msg = f"{product_info[2]} {product_info[1][0]} - {price_info}"
messages.append({"role": "system", "content": new_msg})
# Eger match bulunamadiysa, basit eslesme dene
if best_match_score == 0:
for product_info in products:
if product_info[0] in input_words and product_info[1][0] == "stokta":
normal_price = f"Fiyat: {product_info[1][1]} TL"
if product_info[1][3]:
eft_price = f"Havale: {product_info[1][3]} TL"
price_info = f"{normal_price}, {eft_price}"
else:
price_info = normal_price
if product_info[1][2]:
found_product_link = product_info[1][2]
if product_info[1][5]:
found_product_image = product_info[1][5]
found_product_name = product_info[2]
new_msg = f"{product_info[2]} {product_info[1][0]} - {price_info}"
messages.append({"role": "system", "content": new_msg})
break # Ilk eslesen yeterli
# Stok bilgisi ekle - detected_product kullan
# ONCELIK: XML sonucu (smart_warehouse_with_price.py) daha guvenilir
warehouse_info = get_warehouse_stock(stock_query_product)
xml_has_valid_stock = False
if warehouse_info:
stock_msg = "Magaza Stok Durumu:\n" + "\n".join(warehouse_info) if isinstance(warehouse_info, list) else str(warehouse_info)
messages.append({"role": "system", "content": stock_msg})
# XML sonucunda gercek stok bilgisi var mi kontrol et
# "mevcut degil", "bulunamadi", "tukendi" gibi ifadeler yoksa stok var demektir
stock_msg_lower = stock_msg.lower()
negative_indicators = ["mevcut değil", "mevcut degil", "bulunamadi", "bulunmuyor", "tükendi", "tukendi", "stokta yok"]
xml_has_valid_stock = not any(indicator in stock_msg_lower for indicator in negative_indicators)
if xml_has_valid_stock:
logger.info(f"βœ… XML'den stok bilgisi bulundu: {stock_query_product}")
# Link ve fiyat bilgisini context'e kaydet (follow-up sorular icin)
context = get_conversation_context(phone_number)
link_match = re.search(r'Link: (https?://[^\s]+)', stock_msg)
if link_match:
context["current_product_link"] = link_match.group(1)
logger.info(f"πŸ”— Link context'e kaydedildi: {link_match.group(1)}")
price_match = re.search(r'Fiyat: ([^\n]+)', stock_msg)
if price_match:
context["current_product_price"] = price_match.group(1)
# Urun adini da kaydet
if stock_query_product:
context["current_product"] = stock_query_product
# Gercek zamanli stok sorgusu - SADECE XML sonucu bos veya olumsuzsa calistir
# Bu sayede XML'de bulunan urunler icin yanlis "stokta yok" mesaji onlenir
should_query_stock = False
if not xml_has_valid_stock:
if intent_analysis:
# Intent Analyzer'dan gelen intent'lere bak
intents = intent_analysis.get("intents", [])
# stock, info, price gibi intent'ler stok sorgusu gerektirir
stock_related_intents = ["stock", "info", "price", "availability"]
should_query_stock = any(intent in intents for intent in stock_related_intents)
# Urun tespit edildiyse de stok sorgula (kullanici urun hakkinda konusuyor demektir)
if detected_product:
should_query_stock = True
# Yedek: Intent Analyzer calismazsa basit keyword kontrolu
if not intent_analysis and is_stock_query(user_message):
should_query_stock = True
if should_query_stock and stock_query_product and not xml_has_valid_stock:
realtime_stock = get_realtime_stock_parallel(stock_query_product)
if realtime_stock:
messages.append({"role": "system", "content": f"Gercek Zamanli Stok:\n{realtime_stock}"})
logger.info(f"πŸ“¦ API'den stok bilgisi eklendi: {stock_query_product}")
if not OPENAI_API_KEY:
return "Sistem hatasi olustu."
# SON HATIRLATMA: Turkce dil kurallari - GPT'ye her yanit oncesi hatirlatma
# Bu mesaj en sona ekleniyor ki GPT son gordukleri kurallari uygulasΔ±n
turkish_reminder = """KRITIK KURALLAR (HER YANIT ICIN GECERLI):
1. ASLA 'sen' kullanma, HER ZAMAN 'siz' kullan (istersen -> isterseniz, sana -> size)
2. ASLA soru ile bitirme (ayirtayim mi?, ister misiniz?, bakar misiniz? YASAK)
3. Bilgiyi ver ve sus, musteri karar versin
4. ONEMLI: Onceki mesajlarda bahsedilen urunleri UNUTMA! "Hangi model var" gibi sorular onceki konudan devam eder.
YANLIS: "Istersen beden ve magaza bazli stok bilgisini de netlestirebilirim."
DOGRU: "Beden ve magaza bazli stok bilgisi icin yazabilirsiniz." """
messages.append({"role": "system", "content": turkish_reminder})
# Model tipine gore payload olustur
# GPT-5.2 ve o1/o3 modelleri: temperature ve max_tokens desteklemiyor
if "gpt-5" in model or "o1" in model or "o3" in model:
payload = {
"model": model,
"messages": messages,
"max_completion_tokens": 1000
}
else:
payload = {
"model": model,
"messages": messages,
"temperature": 0.3,
"max_tokens": 1000
}
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {OPENAI_API_KEY}"
}
logger.info(f"πŸ“€ API istegi gonderiliyor - Model: {model}")
response = requests.post(API_URL, headers=headers, json=payload, timeout=30)
if response.status_code == 200:
result = response.json()
ai_response = result['choices'][0]['message']['content']
# Kullanilan modeli logla
used_model = result.get('model', model)
logger.info(f"βœ… Yanit alindi - Kullanilan model: {used_model}")
try:
formatted_response = extract_product_info_whatsapp(ai_response)
except:
formatted_response = ai_response
# Urun linki ve gorseli varsa ekle
# NOT: Stok/magaza sorularinda yanlis gorsel gostermemek icin
# sadece TEK URUN soruldugundan eminsen gorsel gonder
is_specific_product_query = best_match_score >= 3 # En az 3 kelime eslesmeli
# GORSEL GONDERILMEMESI GEREKEN SORU TIPLERI
# Beden, size, kadro, geometri gibi sorularda gorsel gereksiz
no_image_keywords = [
'beden', 'size', 'kadro', 'boy', 'kac cm', 'kaΓ§ cm',
'hangi beden', 'xl mi', 'l mi', 'm mi', 's mi',
'geometri', 'stack', 'reach', 'standover',
'kilo', 'agirlik', 'ağırlık', 'weight',
'garanti', 'warranty', 'teslimat', 'kargo',
'taksit', 'odeme', 'ΓΆdeme', 'kredi', 'havale'
]
user_msg_lower = user_message.lower()
is_info_only_query = any(keyword in user_msg_lower for keyword in no_image_keywords)
if found_product_link and is_specific_product_query and not is_info_only_query:
formatted_response += f"\n\nπŸ”— {found_product_link}"
add_to_conversation(phone_number, user_message, formatted_response)
# Gorsel sadece spesifik urun sorgusu ise gonder
# "Sariyer'de hangi renk var" gibi genel sorularda gorsel gonderme
# Beden/size sorularinda da gorsel gonderme
if found_product_image and is_specific_product_query and not is_info_only_query:
return (formatted_response, found_product_image)
return formatted_response
else:
error_msg = response.text[:200] if response.text else "Bilinmeyen hata"
logger.error(f"❌ API hatasi {response.status_code}: {error_msg}")
# Fallback modele gec
if model != MODEL_CONFIG["fallback"]:
logger.info(f"πŸ”„ Fallback modele geciliyor: {MODEL_CONFIG['fallback']}")
fallback_model = MODEL_CONFIG["fallback"]
# Fallback icin payload'i yeniden olustur (max_tokens kullan)
fallback_payload = {
"model": fallback_model,
"messages": messages,
"temperature": 0.3,
"max_tokens": 1000
}
response = requests.post(API_URL, headers=headers, json=fallback_payload, timeout=30)
if response.status_code == 200:
result = response.json()
ai_response = result['choices'][0]['message']['content']
add_to_conversation(phone_number, user_message, ai_response)
return ai_response
return "Su anda bir sorun yasiyorum. Lutfen tekrar deneyin."
except requests.exceptions.Timeout:
logger.error("❌ API timeout hatasi")
return "Islem zaman asimina ugradi. Lutfen tekrar deneyin."
except Exception as e:
logger.error(f"❌ Mesaj isleme hatasi: {e}")
import traceback
traceback.print_exc()
return "Teknik bir sorun olustu. Lutfen tekrar deneyin."
# ===============================
# FASTAPI UYGULAMASI
# ===============================
app = FastAPI(title="Trek WhatsApp Bot - Hybrid Model")
@app.post("/whatsapp-webhook")
async def whatsapp_webhook(request: Request):
"""WhatsApp webhook - Hybrid model ile"""
try:
form_data = await request.form()
from_number = form_data.get('From')
to_number = form_data.get('To')
message_body = form_data.get('Body', '')
message_status = form_data.get('MessageStatus')
# Medya kontrolu
num_media = int(form_data.get('NumMedia', 0))
media_urls = []
media_types = []
for i in range(num_media):
media_url = form_data.get(f'MediaUrl{i}')
media_type = form_data.get(f'MediaContentType{i}')
if media_url:
media_urls.append(media_url)
media_types.append(media_type)
logger.info(f"πŸ“± Webhook - From: {from_number}, Body: {message_body[:50] if message_body else 'N/A'}, Media: {num_media}")
# Durum guncellemelerini ignore et
if message_status in ['sent', 'delivered', 'read', 'failed']:
return {"status": "ignored", "message": f"Status: {message_status}"}
# Giden mesajlari ignore et
if to_number != TWILIO_WHATSAPP_NUMBER:
return {"status": "ignored", "message": "Outgoing message"}
# Bos mesaj ve medya yoksa ignore et
if not message_body and num_media == 0:
return {"status": "ignored", "message": "Empty message"}
logger.info(f"βœ… MESAJ ALINDI: {from_number} -> Metin: {bool(message_body)}, Medya: {num_media}")
if not twilio_client:
return {"status": "error", "message": "Twilio yapilandirmasi eksik"}
# ========================================
# HYBRID MODEL SECIMI
# ========================================
product_image_url = None
if num_media > 0 and media_urls:
# GORSEL VAR -> GPT-4o kullan
logger.info("πŸ–ΌοΈ GORSEL TESPIT EDILDI -> GPT-4o Vision kullanilacak")
ai_response = process_whatsapp_message_with_media(
message_body,
from_number,
media_urls,
media_types
)
else:
# SADECE METIN -> GPT-5.2 kullan
logger.info("πŸ“ METIN MESAJI -> GPT-5.2 kullanilacak")
result = process_whatsapp_message_with_memory(
message_body,
from_number
)
# Tuple donerse (metin, gorsel_url) seklinde
if isinstance(result, tuple):
ai_response, product_image_url = result
logger.info(f"πŸ–ΌοΈ Urun gorseli bulundu: {product_image_url}")
else:
ai_response = result
# Yanit kisalt
if len(ai_response) > 1500:
ai_response = ai_response[:1500] + "...\n\nDetayli bilgi: trekbisiklet.com.tr"
# WhatsApp'a gonder
# Once metin mesaji gonder
message = twilio_client.messages.create(
messaging_service_sid=TWILIO_MESSAGING_SERVICE_SID,
body=ai_response,
to=from_number
)
logger.info(f"βœ… YANIT GONDERILDI: {ai_response[:100]}...")
# Urun gorseli varsa ayrica gonder
if product_image_url:
try:
image_message = twilio_client.messages.create(
messaging_service_sid=TWILIO_MESSAGING_SERVICE_SID,
media_url=[product_image_url],
to=from_number
)
logger.info(f"πŸ–ΌοΈ URUN GORSELI GONDERILDI: {product_image_url}")
except Exception as img_error:
logger.error(f"❌ Gorsel gonderme hatasi: {img_error}")
return {"status": "success", "message_sid": message.sid}
except Exception as e:
logger.error(f"❌ Webhook hatasi: {str(e)}")
import traceback
traceback.print_exc()
return {"status": "error", "message": str(e)}
@app.get("/")
async def root():
return {
"message": "Trek WhatsApp Bot - Hybrid Model calisiyor!",
"status": "active",
"models": {
"vision": MODEL_CONFIG["vision"],
"text": MODEL_CONFIG["text"],
"fallback": MODEL_CONFIG["fallback"]
}
}
@app.get("/health")
async def health():
return {
"status": "healthy",
"twilio_configured": twilio_client is not None,
"openai_configured": OPENAI_API_KEY is not None,
"models": MODEL_CONFIG,
"products_loaded": len(products),
"modules": {
"gpt5_search": USE_GPT5_SEARCH,
"media_queue": USE_MEDIA_QUEUE,
"store_notification": USE_STORE_NOTIFICATION,
"follow_up": USE_FOLLOW_UP,
"intent_analyzer": USE_INTENT_ANALYZER
}
}
@app.get("/test-models")
async def test_models():
"""Model durumlarini test et"""
results = {}
for model_type, model_name in MODEL_CONFIG.items():
try:
payload = {
"model": model_name,
"messages": [{"role": "user", "content": "Merhaba, test mesaji."}],
"max_tokens": 10
}
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {OPENAI_API_KEY}"
}
response = requests.post(API_URL, headers=headers, json=payload, timeout=10)
results[model_type] = {
"model": model_name,
"status": "OK" if response.status_code == 200 else f"Error: {response.status_code}",
"available": response.status_code == 200
}
except Exception as e:
results[model_type] = {
"model": model_name,
"status": f"Error: {str(e)}",
"available": False
}
return results
@app.get("/cache-status")
async def cache_status():
"""Cache durumunu goster"""
return {
"cache_size": len(stock_cache),
"cache_duration_seconds": CACHE_DURATION,
"cached_products": list(stock_cache.keys())[:10] # Ilk 10
}
@app.post("/clear-cache")
async def clear_cache():
"""Cache'i temizle"""
global stock_cache
old_size = len(stock_cache)
stock_cache = {}
return {"message": f"Cache temizlendi. {old_size} kayit silindi."}
if __name__ == "__main__":
import uvicorn
print("=" * 60)
print(" Trek WhatsApp Bot - HYBRID MODEL")
print("=" * 60)
print(f" πŸ–ΌοΈ Gorsel mesajlar -> {MODEL_CONFIG['vision']}")
print(f" πŸ“ Metin mesajlar -> {MODEL_CONFIG['text']}")
print(f" πŸ”„ Fallback -> {MODEL_CONFIG['fallback']}")
print("=" * 60)
print(f" πŸ“¦ Yuklenen urun sayisi: {len(products)}")
print(f" πŸ” GPT-5 Search: {'Aktif' if USE_GPT5_SEARCH else 'Pasif'}")
print(f" πŸ”” Store Notification: {'Aktif' if USE_STORE_NOTIFICATION else 'Pasif'}")
print(f" πŸ“Œ Follow-Up System: {'Aktif' if USE_FOLLOW_UP else 'Pasif'}")
print(f" 🧠 Intent Analyzer: {'Aktif' if USE_INTENT_ANALYZER else 'Pasif'}")
print("=" * 60)
uvicorn.run(app, host="0.0.0.0", port=7860)