File size: 37,638 Bytes
f22680d 5fd0cd9 c1a894b 5fd0cd9 c1a894b 5fd0cd9 c1a894b 5fd0cd9 c1a894b 5fd0cd9 c1a894b 5fd0cd9 70e6845 5fd0cd9 c1a894b 5fd0cd9 3f44417 5fd0cd9 3f44417 c1a894b 5fd0cd9 c1a894b 3f44417 c1a894b 3f44417 c1a894b 3f44417 5fd0cd9 3f44417 5fd0cd9 3f44417 c1a894b 5fd0cd9 c1a894b 5fd0cd9 c1a894b 5fd0cd9 c1a894b e2a874a d6ee006 f22680d e2a874a 73cc2c5 f22680d 73cc2c5 f22680d 73cc2c5 f22680d 73cc2c5 f22680d 73cc2c5 f22680d 73cc2c5 f22680d 73cc2c5 f22680d 73cc2c5 f22680d 73cc2c5 f22680d 73cc2c5 f22680d 73cc2c5 f22680d 73cc2c5 f22680d 73cc2c5 f22680d 73cc2c5 f22680d 73cc2c5 f22680d 73cc2c5 f22680d 73cc2c5 f22680d 73cc2c5 f22680d 73cc2c5 f22680d 73cc2c5 f22680d 73cc2c5 f22680d 73cc2c5 f22680d 73cc2c5 f22680d e2a874a f22680d e2a874a f22680d 73cc2c5 f22680d 73cc2c5 f22680d 73cc2c5 f22680d 73cc2c5 f22680d e2a874a f22680d e2a874a f22680d e2a874a f22680d 73cc2c5 f22680d e2a874a f22680d e2a874a d6ee006 e2a874a c1a894b 5fd0cd9 c1a894b 5fd0cd9 c1a894b e2a874a c1a894b e2a874a dae8b66 e2a874a dae8b66 e2a874a 5a5a4bb dae8b66 5a5a4bb dae8b66 5a5a4bb e2a874a 5a5a4bb dae8b66 5a5a4bb 5fd0cd9 c1a894b 5fd0cd9 c1a894b 5a5a4bb c1a894b 24d840d 5a5a4bb f22680d e2a874a f22680d e2a874a f6c512e f22680d f6c512e f22680d e2a874a f22680d e2a874a f22680d e2a874a f22680d 73cc2c5 f22680d e2a874a f22680d e2a874a f22680d e2a874a f22680d 73cc2c5 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 |
import gradio as gr
import os
import json
import requests
import xml.etree.ElementTree as ET
import schedule
import time
import threading
from huggingface_hub import HfApi, create_repo, hf_hub_download
import warnings
import pandas as pd
from docx import Document
import spaces
from google.oauth2.service_account import Credentials
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseDownload
import io
import warnings
from requests.packages.urllib3.exceptions import InsecureRequestWarning
warnings.simplefilter('ignore', InsecureRequestWarning)
# Prompt dosyasını import et
from prompts import get_prompt_content_only
# Enhanced features import et (sadece temel özellikler)
from enhanced_features import (
initialize_enhanced_features, process_image_message,
handle_comparison_request
)
from image_renderer import extract_product_info_for_gallery, format_message_with_images
# Warehouse stock integration - OPTIMIZED VERSION
def get_warehouse_stock(product_name):
"""B2B API'den mağaza stok bilgilerini çek - Optimize edilmiş versiyon"""
try:
import re
import signal
# Create a timeout handler
def timeout_handler(signum, frame):
raise TimeoutError("Warehouse API timeout")
# Set alarm for 3 seconds
signal.signal(signal.SIGALRM, timeout_handler)
signal.alarm(3)
try:
warehouse_url = 'https://video.trek-turkey.com/bizimhesap-warehouse-xml-b2b-api.php'
response = requests.get(warehouse_url, verify=False, timeout=2)
if response.status_code != 200:
return None
root = ET.fromstring(response.content)
# Turkish character normalization function
turkish_map = {'ı': 'i', 'ğ': 'g', 'ü': 'u', 'ş': 's', 'ö': 'o', 'ç': 'c', 'İ': 'i', 'I': 'i'}
def normalize_turkish(text):
import unicodedata
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
# 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()
# Search using new B2B API structure
candidates = []
product_count = 0
max_products = 100 # Increase limit for new API
# Separate size/color words from product words for context-aware search
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]
for product in root.findall('Product'):
if product_count >= max_products:
break
product_count += 1
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_name = normalize_turkish(xml_product_name.lower())
variant_text = ""
if variant_elem is not None and variant_elem.text:
variant_text = normalize_turkish(variant_elem.text.strip().lower())
# Context-aware matching
name_match = False
variant_match = False
# Check product name match
if product_words:
name_match = all(word in normalized_name for word in product_words)
else:
name_match = any(word in normalized_name for word in search_words if len(word) > 2)
# Check variant match
if variant_words and variant_text:
variant_match = all(word in variant_text for word in variant_words)
# Include if name matches and (no variant search OR variant matches)
if name_match and (not variant_words or variant_match):
candidates.append((product, xml_product_name, variant_text))
if len(candidates) >= 10: # Limit candidates
break
# Collect stock info from new structure
warehouse_stock_map = {}
for product, xml_name, variant in candidates:
# New structure: Warehouse elements are direct children of Product
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
# Cancel alarm
signal.alarm(0)
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 ["Hiçbir mağazada stokta bulunmuyor"]
except TimeoutError:
signal.alarm(0)
print("Warehouse API timeout - skipping")
return None
except Exception as e:
try:
signal.alarm(0)
except:
pass
print(f"Mağaza stok bilgisi çekme hatası: {e}")
return None
# Import improved product search
try:
from improved_chatbot import ImprovedChatbot
USE_IMPROVED_SEARCH = True
except ImportError:
print("Improved chatbot not available, using basic search")
USE_IMPROVED_SEARCH = False
# Gradio uyarılarını bastır
warnings.filterwarnings("ignore", category=UserWarning, module="gradio.components.chatbot")
# Log dosyası adı ve yolu
LOG_FILE = '/data/chat_logs.txt' if os.path.exists('/data') else 'chat_logs.txt'
print(f"Dosya yolu: {os.path.abspath(LOG_FILE)}")
# API ayarları
API_URL = "https://api.openai.com/v1/chat/completions"
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
if not OPENAI_API_KEY:
print("Hata: OPENAI_API_KEY çevre değişkeni ayarlanmamış!")
# Trek bisiklet ürünlerini çekme
url = 'https://www.trekbisiklet.com.tr/output/8582384479'
response = requests.get(url, verify=False, timeout=30)
if response.status_code == 200 and response.content:
root = ET.fromstring(response.content)
else:
print(f"HTTP hatası: {response.status_code}")
root = None
products = []
if root is not None:
for item in root.findall('item'):
# Tüm ürünleri al, sonra stokta olma durumunu kontrol et - None kontrolü
rootlabel_elem = item.find('rootlabel')
stock_elem = item.find('stockAmount')
if rootlabel_elem is None or stock_elem is None:
continue # Eksik veri varsa bu ürünü atla
name_words = rootlabel_elem.text.lower().split()
name = name_words[0]
full_name = ' '.join(name_words)
stock_amount = "stokta" if stock_elem.text and stock_elem.text > '0' else "stokta değil"
# Stokta olmayan ürünler için fiyat/link bilgisi eklemiyoruz
if stock_amount == "stokta":
# Normal fiyat bilgisini al - Güvenli versiyon
price_elem = item.find('priceTaxWithCur')
price_str = price_elem.text if price_elem is not None and price_elem.text else "Fiyat bilgisi yok"
# EFT fiyatını al (havale indirimli orijinal fiyat) - Güvenli versiyon
price_eft_elem = item.find('priceEft')
price_eft_str = price_eft_elem.text if price_eft_elem is not None and price_eft_elem.text else ""
# İndirimli fiyatı al (kampanyalı fiyat) - Güvenli versiyon
price_rebate_elem = item.find('priceRebateWithTax')
price_rebate_str = price_rebate_elem.text if price_rebate_elem is not None and price_rebate_elem.text else ""
# Havale indirimi fiyatını al (havale indirimli kampanyalı fiyat) - Güvenli versiyon
price_rebate_money_order_elem = item.find('priceRebateWithMoneyOrderWithTax')
price_rebate_money_order_str = price_rebate_money_order_elem.text if price_rebate_money_order_elem is not None and price_rebate_money_order_elem.text else ""
# Normal fiyatı yuvarla
try:
price_float = float(price_str)
# Fiyat 200000 üzerindeyse en yakın 5000'lik basamağa yuvarla
if price_float > 200000:
price = str(round(price_float / 5000) * 5000) # En yakın 5000'e yuvarla
# Fiyat 30000 üzerindeyse en yakın 1000'lik basamağa yuvarla
elif price_float > 30000:
price = str(round(price_float / 1000) * 1000) # En yakın 1000'e yuvarla
# Fiyat 10000 üzerindeyse en yakın 100'lük basamağa yuvarla
elif price_float > 10000:
price = str(round(price_float / 100) * 100) # En yakın 100'e yuvarla
# Diğer durumlarda en yakın 10'luk basamağa yuvarla
else:
price = str(round(price_float / 10) * 10) # En yakın 10'a yuvarla
except (ValueError, TypeError):
price = price_str # Sayıya dönüştürülemezse olduğu gibi bırak
# Havale indirimli orijinal fiyatı yuvarla (varsa)
if price_eft_str:
try:
price_eft_float = float(price_eft_str)
# Fiyat 200000 üzerindeyse en yakın 5000'lik basamağa yuvarla
if price_eft_float > 200000:
price_eft = str(round(price_eft_float / 5000) * 5000)
# Fiyat 30000 üzerindeyse en yakın 1000'lik basamağa yuvarla
elif price_eft_float > 30000:
price_eft = str(round(price_eft_float / 1000) * 1000)
# Fiyat 10000 üzerindeyse en yakın 100'lük basamağa yuvarla
elif price_eft_float > 10000:
price_eft = str(round(price_eft_float / 100) * 100)
# Diğer durumlarda en yakın 10'luk basamağa yuvarla
else:
price_eft = str(round(price_eft_float / 10) * 10)
except (ValueError, TypeError):
price_eft = price_eft_str
else:
price_eft = ""
# İndirimli fiyatı yuvarla (varsa)
if price_rebate_str:
try:
price_rebate_float = float(price_rebate_str)
# Fiyat 200000 üzerindeyse en yakın 5000'lik basamağa yuvarla
if price_rebate_float > 200000:
price_rebate = str(round(price_rebate_float / 5000) * 5000)
# Fiyat 30000 üzerindeyse en yakın 1000'lik basamağa yuvarla
elif price_rebate_float > 30000:
price_rebate = str(round(price_rebate_float / 1000) * 1000)
# Fiyat 10000 üzerindeyse en yakın 100'lük basamağa yuvarla
elif price_rebate_float > 10000:
price_rebate = str(round(price_rebate_float / 100) * 100)
# Diğer durumlarda en yakın 10'luk basamağa yuvarla
else:
price_rebate = str(round(price_rebate_float / 10) * 10)
except (ValueError, TypeError):
price_rebate = price_rebate_str
else:
price_rebate = ""
# Havale indirimli kampanyalı fiyatı yuvarla (varsa)
if price_rebate_money_order_str:
try:
price_rebate_money_order_float = float(price_rebate_money_order_str)
# Fiyat 200000 üzerindeyse en yakın 5000'lik basamağa yuvarla
if price_rebate_money_order_float > 200000:
price_rebate_money_order = str(round(price_rebate_money_order_float / 5000) * 5000)
# Fiyat 30000 üzerindeyse en yakın 1000'lik basamağa yuvarla
elif price_rebate_money_order_float > 30000:
price_rebate_money_order = str(round(price_rebate_money_order_float / 1000) * 1000)
# Fiyat 10000 üzerindeyse en yakın 100'lük basamağa yuvarla
elif price_rebate_money_order_float > 10000:
price_rebate_money_order = str(round(price_rebate_money_order_float / 100) * 100)
# Diğer durumlarda en yakın 10'luk basamağa yuvarla
else:
price_rebate_money_order = str(round(price_rebate_money_order_float / 10) * 10)
except (ValueError, TypeError):
price_rebate_money_order = price_rebate_money_order_str
else:
price_rebate_money_order = ""
# Ürün bilgilerini al - None kontrolü ekle
product_url_elem = item.find('productLink')
product_url = product_url_elem.text if product_url_elem is not None and product_url_elem.text else ""
product_info = [stock_amount, price, product_url, price_eft, price_rebate, price_rebate_money_order]
# Resim URL'si ekle (varsa) - Güvenli versiyon
image_elem = item.find('picture1Path')
if image_elem is not None and image_elem.text:
product_info.append(image_elem.text)
else:
product_info.append("") # Boş resim URL'si
else:
# Stokta olmayan ürün için sadece stok durumu
product_info = [stock_amount]
products.append((name, product_info, full_name))
print(f"Toplam {len(products)} ürün yüklendi.")
# Initialize enhanced features
initialize_enhanced_features(OPENAI_API_KEY, products)
# Initialize improved chatbot if available
improved_bot = None
if USE_IMPROVED_SEARCH:
try:
improved_bot = ImprovedChatbot(products)
print("Improved product search initialized successfully")
except Exception as e:
print(f"Failed to initialize improved search: {e}")
USE_IMPROVED_SEARCH = False
# Google Drive API ayarları
GOOGLE_CREDENTIALS_PATH = os.getenv("GOOGLE_CREDENTIALS_PATH")
GOOGLE_FOLDER_ID = "1bE8aMj8-eFGftjMPOF8bKQJAhfHa0BN8"
# Global değişkenler
file_lock = threading.Lock()
history_lock = threading.Lock()
global_chat_history = []
document_content = ""
# Google Drive'dan döküman indirme fonksiyonu
def download_documents_from_drive():
global document_content
if not GOOGLE_CREDENTIALS_PATH:
print("Google credentials dosyası bulunamadı.")
return
try:
credentials = Credentials.from_service_account_file(GOOGLE_CREDENTIALS_PATH)
service = build('drive', 'v3', credentials=credentials)
# Klasördeki dosyaları listele
results = service.files().list(
q=f"'{GOOGLE_FOLDER_ID}' in parents",
fields="files(id, name, mimeType)"
).execute()
files = results.get('files', [])
all_content = []
for file in files:
print(f"İndiriliyor: {file['name']}")
# DOCX dosyaları için
if file['mimeType'] == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
request = service.files().get_media(fileId=file['id'])
file_io = io.BytesIO()
downloader = MediaIoBaseDownload(file_io, request)
done = False
while done is False:
status, done = downloader.next_chunk()
file_io.seek(0)
doc = Document(file_io)
content = f"\\n=== {file['name']} ===\\n"
for paragraph in doc.paragraphs:
if paragraph.text.strip():
content += paragraph.text + "\\n"
all_content.append(content)
document_content = "\\n".join(all_content)
print(f"Toplam {len(files)} döküman yüklendi.")
except Exception as e:
print(f"Google Drive'dan döküman indirme hatası: {e}")
# Döküman indirme işlemini arka planda çalıştır
document_thread = threading.Thread(target=download_documents_from_drive, daemon=True)
document_thread.start()
# Log dosyasını zamanla temizleme fonksiyonu
def clear_log_file():
try:
if os.path.exists(LOG_FILE):
with file_lock:
with open(LOG_FILE, 'w', encoding='utf-8') as f:
f.write("Log dosyası temizlendi.\\n")
print("Log dosyası temizlendi.")
except Exception as e:
print(f"Log dosyası temizleme hatası: {e}")
# Zamanlanmış görevleri çalıştırma fonksiyonu
def run_scheduler(chat_history):
schedule.every().day.at("03:00").do(clear_log_file)
while True:
schedule.run_pending()
time.sleep(60)
# Chatbot fonksiyonu
def chatbot_fn(user_message, history, image=None):
if history is None:
history = []
try:
# Enhanced features - Görsel işleme
if image is not None:
user_message = process_image_message(image, user_message)
# Enhanced features - Karşılaştırma kontrolü
comparison_result = handle_comparison_request(user_message)
if comparison_result:
yield comparison_result
return
# Enhanced features - Basit karşılaştırma ve görsel işleme
# Profil sistemi kaldırıldı - daha hızlı çalışma için
except Exception as e:
print(f"Enhanced features error: {e}")
# Enhanced features hata verirse normal chatbot'a devam et
# Log: Kullanıcı mesajını ekle
try:
with file_lock:
with open(LOG_FILE, 'a', encoding='utf-8') as f:
f.write(f"User: {user_message}\\n")
except Exception as e:
print(f"Dosya yazma hatası (Kullanıcı): {e}")
# Sistem mesajlarını external dosyadan yükle
system_messages = get_prompt_content_only()
# Döküman verilerini sistem mesajlarına ekle
if document_content:
system_messages.append({"role": "system", "content": f"Dökümanlardan gelen bilgiler: {document_content}"})
# Profil sistemi kaldırıldı - daha hızlı çalışma için
# Try improved search first if available
product_found_improved = False
if USE_IMPROVED_SEARCH and improved_bot:
try:
product_result = improved_bot.process_message(user_message)
if product_result['is_product_query'] and product_result['response']:
# Extract product name from improved search result for warehouse stock
enhanced_response = product_result['response']
# Try to get warehouse stock info (optimize edilmiş)
try:
warehouse_info = ""
warehouse_stock = get_warehouse_stock(user_message)
if warehouse_stock and warehouse_stock != ["Hiçbir mağazada stokta bulunmuyor"]:
warehouse_info = f"\n\n🏪 MAĞAZA STOK BİLGİLERİ:\n"
for store_info in warehouse_stock:
warehouse_info += f"• {store_info}\n"
enhanced_response += warehouse_info
elif warehouse_stock == ["Hiçbir mağazada stokta bulunmuyor"]:
enhanced_response += f"\n\n🏪 MAĞAZA STOK BİLGİLERİ: Hiçbir mağazada stokta bulunmuyor"
except Exception as e:
print(f"Warehouse stock error in improved search: {e}")
system_messages.append({
"role": "system",
"content": f"ÜRÜN BİLGİSİ:\n{enhanced_response}\n\nBu bilgileri kullanarak kullanıcıya yardımcı ol."
})
product_found_improved = True
except Exception as e:
print(f"Improved search error: {e}")
# Use basic search as fallback or if improved search didn't find anything
if not product_found_improved:
# Kullanıcı mesajında ürün ismi geçiyorsa ekle
input_words = user_message.lower().split()
for word in input_words:
for product_info in products:
if word in product_info[0] or word in product_info[2].lower():
# Stokta olup olmadığını kontrol et
if product_info[1][0] == "stokta":
# Normal fiyat
normal_price = f"\\nFiyat: {product_info[1][1]} TL"
# Kampanyalı fiyat kontrolü
rebate_price = ""
discount_info = ""
eft_price = ""
rebate_money_order_price = ""
# Kampanyalı fiyat var mı kontrol et
if len(product_info[1]) > 4 and product_info[1][4] and product_info[1][4] != "":
rebate_price = f"\\nKampanyalı fiyat: {product_info[1][4]} TL"
# İndirim miktarını hesapla
try:
normal_price_float = float(product_info[1][1])
rebate_price_float = float(product_info[1][4])
discount_amount = normal_price_float - rebate_price_float
# İndirim miktarı 0'dan büyükse göster
if discount_amount > 0:
# İndirim miktarı için yuvarlama kurallarını uygula
if discount_amount > 200000:
discount_amount_rounded = round(discount_amount / 5000) * 5000
elif discount_amount > 30000:
discount_amount_rounded = round(discount_amount / 1000) * 1000
elif discount_amount > 10000:
discount_amount_rounded = round(discount_amount / 100) * 100
else:
discount_amount_rounded = round(discount_amount / 10) * 10
# İndirim bilgisi
discount_info = f"\\nYapılan indirim: {discount_amount_rounded:.0f} TL"
except (ValueError, TypeError):
discount_info = ""
# Havale indirimli kampanyalı fiyat bilgisini gösterme
rebate_money_order_price = ""
else:
# Kampanyalı değilse, havale indirimli normal fiyatı göster
if product_info[1][3] and product_info[1][3] != "":
eft_price = f"\\nHavale indirimli fiyat: {product_info[1][3]} TL"
# Ürün linki ve resim
product_link = f"\\nÜrün linki: {product_info[1][2]}"
product_image = ""
if len(product_info[1]) > 6 and product_info[1][6]: # Resim URL'si varsa
product_image = f"\\nÜrün resmi: {product_info[1][6]}"
# Mağaza stok bilgilerini ekle (optimize edilmiş versiyon)
warehouse_stock_info = ""
try:
warehouse_stock = get_warehouse_stock(product_info[2])
if warehouse_stock and warehouse_stock != ["Hiçbir mağazada stokta bulunmuyor"]:
warehouse_stock_info = f"\\n🏪 Mağaza stok bilgileri:\\n"
for store_info in warehouse_stock:
warehouse_stock_info += f"• {store_info}\\n"
elif warehouse_stock == ["Hiçbir mağazada stokta bulunmuyor"]:
warehouse_stock_info = f"\\n🏪 Mağaza stok bilgileri: Hiçbir mağazada stokta bulunmuyor\\n"
except Exception as e:
print(f"Warehouse stock error for {product_info[2]}: {e}")
# Tüm bilgileri birleştir
new_msg = f"{product_info[2]} {product_info[1][0]}\\n{normal_price}{rebate_price}{discount_info}{eft_price}{rebate_money_order_price}{product_link}{product_image}{warehouse_stock_info}"
else:
# Ürün stokta yoksa sadece stok durumunu bildir
new_msg = f"{product_info[2]} {product_info[1][0]}"
system_messages.append({"role": "system", "content": new_msg})
messages = system_messages + history + [{"role": "user", "content": user_message}]
payload = {
"model": "gpt-4.1",
"messages": messages,
"temperature": 0.2,
"top_p": 1,
"n": 1,
"stream": True,
"presence_penalty": 0,
"frequency_penalty": 0,
}
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {OPENAI_API_KEY}"
}
response = requests.post(API_URL, headers=headers, json=payload, stream=True)
if response.status_code != 200:
yield "Bir hata oluştu."
return
partial_response = ""
for chunk in response.iter_lines():
if not chunk:
continue
chunk_str = chunk.decode('utf-8')
if chunk_str.startswith("data: ") and chunk_str != "data: [DONE]":
try:
chunk_data = json.loads(chunk_str[6:])
delta = chunk_data['choices'][0]['delta']
if 'content' in delta:
partial_response += delta['content']
# Resim formatlaması uygula
formatted_response = extract_product_info_for_gallery(partial_response)
yield formatted_response
except json.JSONDecodeError as e:
print(f"JSON parse hatası: {e} - Chunk: {chunk_str}")
elif chunk_str == "data: [DONE]":
break
# Son resim formatlaması
final_response = extract_product_info_for_gallery(partial_response)
yield final_response
# Profil kaydetme kaldırıldı - daha hızlı çalışma için
# Log: Asistan cevabını ekle
try:
with file_lock:
with open(LOG_FILE, 'a', encoding='utf-8') as f:
f.write(f"Bot: {partial_response}\\n")
except Exception as e:
print(f"Dosya yazma hatası (Bot): {e}")
# Global geçmişi güncelle
with history_lock:
global_chat_history.append({"role": "user", "content": user_message})
global_chat_history.append({"role": "assistant", "content": partial_response})
# Slow echo (test için)
def slow_echo(message, history):
for i in range(len(message)):
time.sleep(0.05)
yield "You typed: " + message[: i + 1]
# Kullanım modu
USE_SLOW_ECHO = False
chat_fn = slow_echo if USE_SLOW_ECHO else chatbot_fn
if not USE_SLOW_ECHO:
scheduler_thread = threading.Thread(target=run_scheduler, args=(global_chat_history,), daemon=True)
scheduler_thread.start()
# Trek markasına özel tema oluştur (düzeltilmiş sürüm)
trek_theme = gr.themes.Base(
primary_hue="red", # Trek kırmızısı için
secondary_hue="slate", # Gri tonları için
neutral_hue="slate",
radius_size=gr.themes.sizes.radius_sm, # Köşe yuvarlatma değerleri
spacing_size=gr.themes.sizes.spacing_md, # Aralık değerleri
text_size=gr.themes.sizes.text_sm # Yazı boyutları (small)
)
# Chatbot kartları için arka plan renkleri değiştiren CSS
custom_css = """
/* Genel font ayarları */
.gradio-container, .gradio-container *, .message-wrap, .message-wrap p, .message-wrap div,
button, input, select, textarea {
font-family: 'Segoe UI', 'SF Pro Text', 'Roboto', -apple-system, BlinkMacSystemFont,
'Helvetica Neue', Arial, sans-serif !important;
font-size: 0.6rem !important;
}
/* Mobil responsive başlangıç */
@media (max-width: 768px) {
.gradio-container, .gradio-container *, .message-wrap, .message-wrap p, .message-wrap div {
font-size: 0.8rem !important;
}
h1 {
font-size: 1.8rem !important;
text-align: center;
margin: 10px 0;
}
h2 {
font-size: 1.4rem !important;
}
}
/* Input alanı için de aynı boyut */
.message-textbox textarea {
font-size: 0.6rem !important;
}
/* Başlıklar için özel boyutlar */
h1 {
font-size: 1.4rem !important;
font-weight: 800 !important;
}
h2 {
font-size: 1.2rem !important;
font-weight: 600 !important;
}
h3 {
font-size: 1rem !important;
font-weight: 600 !important;
}
/* Kart arka plan renkleri - görseldeki gibi */
/* Kullanıcı mesajları için mavi tonda arka plan */
.user-message, .user-message-highlighted {
background-color: #e9f5fe !important;
border-bottom-right-radius: 0 !important;
box-shadow: 0 1px 2px rgba(0,0,0,0.1) !important;
}
/* Bot mesajları için beyaz arka plan ve hafif kenarlık */
.bot-message, .bot-message-highlighted {
background-color: white !important;
border: 1px solid #e0e0e0 !important;
border-bottom-left-radius: 0 !important;
box-shadow: 0 1px 2px rgba(0,0,0,0.05) !important;
}
/* Mesaj baloncuklarının köşe yuvarlatma değerleri */
.message-wrap {
border-radius: 12px !important;
margin: 0.5rem 0 !important;
max-width: 90% !important;
}
/* Sohbet alanının genel arka planı */
.chat-container, .gradio-container {
background-color: #f7f7f7 !important;
}
/* Daha net yazılar için text rendering */
* {
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-rendering: optimizeLegibility;
}
/* Restore butonu stilleri kaldırıldı */
/* Responsive mobil tasarım - iOS benzeri */
@media (max-width: 768px) {
/* Daha büyük ve dokunmatik dostu boyutlar */
.gradio-container {
padding: 0 !important;
margin: 0 !important;
}
/* Mesaj baloncukları iOS tarzı */
.message-wrap {
margin: 0.3rem 0.5rem !important;
max-width: 85% !important;
border-radius: 18px !important;
padding: 10px 15px !important;
font-size: 0.9rem !important;
}
/* Kullanıcı mesajları */
.user-message, .user-message-highlighted {
background-color: #007AFF !important;
color: white !important;
margin-left: auto !important;
margin-right: 8px !important;
}
/* Bot mesajları */
.bot-message, .bot-message-highlighted {
background-color: #f1f1f1 !important;
color: #333 !important;
margin-left: 8px !important;
margin-right: auto !important;
}
}
/* Input alanına uçan kağıt ikonu ekle */
#msg-input {
position: relative;
}
#msg-input textarea {
padding-right: 40px !important;
}
.input-icon {
position: absolute;
right: 12px;
top: 50%;
transform: translateY(-50%);
font-size: 16px;
pointer-events: none;
z-index: 10;
color: #666;
}
/* Mobil responsive - Input alanı */
@media (max-width: 768px) {
#msg-input {
margin: 10px 0;
}
#msg-input textarea {
padding: 12px 45px 12px 15px !important;
font-size: 1rem !important;
border-radius: 20px !important;
border: 1px solid #ddd !important;
box-shadow: 0 1px 3px rgba(0,0,0,0.1) !important;
}
.input-icon {
right: 15px;
font-size: 18px;
}
}
/* Genel mobil iyileştirmeler */
@media (max-width: 768px) {
/* Chatbot alanı tam ekran */
.gradio-container .main {
padding: 0 !important;
}
/* Başlık alanı küçült */
.gradio-container header {
padding: 8px !important;
}
/* Tab alanlarını küçült */
.tab-nav {
padding: 5px !important;
}
/* Scroll bar'ı gizle */
.scroll-hide {
scrollbar-width: none;
-ms-overflow-style: none;
}
.scroll-hide::-webkit-scrollbar {
display: none;
}
}
/* CSS Bitişi */
"""
# Chat persistence sistemi tamamen kaldırıldı
storage_js = ""
# Enhanced chatbot fonksiyonu image destekli
def enhanced_chatbot_fn(message, history, image):
return chatbot_fn(message, history, image)
# Demo arayüzü - Mobil responsive
with gr.Blocks(css=custom_css, theme="soft", title="Trek Asistanı", head=storage_js) as demo:
gr.Markdown("# 🚲 Trek Asistanı AI")
gr.Markdown("**Akıllı özellikler:** Ürün karşılaştırması ve detaylı ürün bilgileri sunuyorum.")
# LocalStorage fonksiyonu kaldırıldı
chatbot = gr.Chatbot(height=600, elem_id="chatbot", show_label=False)
msg = gr.Textbox(
placeholder="Trek bisikletleri hakkında soru sorun...",
show_label=False,
elem_id="msg-input"
)
# Restore button tamamen kaldırıldı
# Session ve profil sistemi tamamen kaldırıldı
def respond(message, chat_history):
if not message.strip():
return "", chat_history
# Kullanıcı mesajını hemen göster
if chat_history is None:
chat_history = []
# Kullanıcı mesajını ekle ve hemen yield et
chat_history.append((message, None))
yield "", chat_history
# Chat history'yi chatbot_fn için uygun formata çevir (son mesaj hariç)
formatted_history = []
if len(chat_history) > 1: # Son mesajı hariç tut
for user_msg, bot_msg in chat_history[:-1]:
if bot_msg: # Sadece tamamlanmış mesajlar
formatted_history.append({"role": "user", "content": user_msg})
formatted_history.append({"role": "assistant", "content": bot_msg})
try:
# Enhanced chatbot fonksiyonunu çağır (image=None)
response_generator = chatbot_fn(message, formatted_history, None)
# Generator'dan streaming cevap al
response = ""
for partial in response_generator:
response = partial
# Son mesajı güncelle ve yield et
chat_history[-1] = (message, response)
yield "", chat_history
# Chat kaydetme sistemi kaldırıldı
except Exception as e:
error_msg = f"Üzgünüm, bir hata oluştu: {str(e)}"
print(f"Chat error: {e}")
# Hata mesajıyla güncelle
chat_history[-1] = (message, error_msg)
yield "", chat_history
msg.submit(respond, [msg, chatbot], [msg, chatbot], show_progress=True)
if __name__ == "__main__":
demo.launch(debug=True) |