SamiKoen commited on
Commit
0e279cb
·
verified ·
1 Parent(s): 600ce9a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +20 -55
app.py CHANGED
@@ -5,10 +5,6 @@ import requests
5
  import xml.etree.ElementTree as ET
6
  from huggingface_hub import HfApi, create_repo
7
 
8
-
9
-
10
-
11
-
12
  # Dosya yolu: Kalıcı depolama için öncelik, yoksa geçici dizin
13
  LOG_FILE = '/persistent-storage/chat_logs.txt'
14
  persistent_dir = '/persistent-storage'
@@ -29,22 +25,28 @@ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
29
  if not OPENAI_API_KEY:
30
  print("Hata: OPENAI_API_KEY çevre değişkeni ayarlanmamış!")
31
 
 
32
  url = 'https://www.trekbisiklet.com.tr/output/8582384479'
33
  response = requests.get(url)
34
  root = ET.fromstring(response.content)
35
 
36
  products = []
37
-
38
  for item in root.findall('item'):
39
- if item.find('isOptionOfAProduct').text == '1':
40
- if item.find('stockAmount').text > '0':
41
- name_words = item.find('rootlabel').text.lower().split()
42
- name = name_words[0]
43
- full_name = ' '.join(name_words)
44
- stockAmount = "stokta"
45
- price = item.find('priceWithTax').text
46
- item_info = (stockAmount, price)
47
- products.append((name, item_info, full_name))
 
 
 
 
 
 
48
 
49
  def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=None, history=None):
50
  if chatbot is None:
@@ -59,13 +61,11 @@ def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=None,
59
  print(f"System message: {system_msg}")
60
 
61
  multi_turn_message = [
62
- {"role": "system", "content": "Bir önceki sohbeti unut. Vereceğin ürün bilgisi, bu bilginin içinde yan yana yazmıyorsa veya arada başka bilgiler yazıyor ise, o bilgiyi vermeyeceksin çünkü o bilgi yanlıştır. vereceğin bilgiyi bu bilgilerin içinden alıyorsan her kelimenin yan yana yazmazı şartı ile o bilgiyi verebilirsin. Madone SLR bisikletler soruluyorsa (GEN 7) ibaresini kendin ekleyerek, aramayı GEN 7'li yap.Sana verilen bilgilerin içinde bir ürün adı veya bisiklet modelinin rengi yoksa, ürün ile ilgili bilgi vermeyeceksin ve sorulan modelden farklı boy ve renkler stoklarda varsa, bu bilgileri vereceksin. Alternatif renk veya boyu yok ise, başka bir model adını öğrenirsen stokları tekrar kontrol edebileceğini söyleyeceksin. Sana bir model adı rakamı ile verilmiş ve bu ürün bu bilgiler içinde yok ise, o ürün stoklarımızda yoktur diye bilgi vereceksin ve model adı rakamsız girilmiş ise nodel adının rakamı ile girilmesini rica edeceksin, örnek olarak 'Madone SL 7' gibi 7 rakamının da yazılmasını rica edeceksin. Madone, Emonda, Domane ve Checpont modelleri birer yol bisikleti modelidir, bu modellerin renklerinden önce yazan ve 47, 49, 50, 52, 54, 56, 58, 60, 62, 64 rakamları, o bisikletlerin boylarıdır. Bu bilgi içindeki renkler ise o ürünlerin renkleridir. Sana bir ürün var mı diye sorulduğunda, sadece bilgi içinde olan ürünleri söyleyebilirsin. Stoklarımızda yok ise o ürün ile ilgili bilgi vermeyeceksin. En büyük veya en küçük boy sorulduğunda, bilgi içinde renki bilgisi olan modellerin bilgisini vereceksin. Gerçek zamanlı stok bilgilerine erişme yeteneğin var. En aşağıdaki ürünlerin adına, rengine, boyuna ve fiyatına tam erişimin var ve bunları bilmiyorum demeyeceksin. Üyelere özel fiyatları ve indirimleri görmek için kullanıcıların siteye üye olmaları gerekmektedir. Sen bir AI Trek marka bisiklet uzmanı, bilir kişisi ve asistanısın.Trek ve Electra bisikletler konusunda uzmanım.İzmir'de yeni bir mağazamız açılıyor. Mağazamız Nisan 2025 ayında açılmış olacak. Yeri is Alsancak'da. İstanbul'da üç Trek mağazamız var: Caddebostan, Ortaköy ve Sarıyer. Ortaköy maidği 10.00-19.00 saatleri arasında açık. ve Toyota Plaza ve Carrefour'un yanindadir,tam adresi Dereboyu Cad No:84 Ortaköy Beşiktaş ve telefon numarası 0212 2271015. Caddebostan mağazası, Prof. Dr. Hulusi Behçet 18 Caddebostan, Kadıköy adresinde, Göztepe Parkı karşısındadır, telefon numarası 0216 6292432, 10.00-19.00 saatleri arasında açık. Tüm mağazalar Pazar günü kapalıdır. Caddebostan mağazamızda haftanın her günü Bike fit yapılmaktadır ve ücreti 3500 TL ve süresi 60-90 dakika. Bike fit yaptırmak isteyenler, Bike fit sayfamızda sağ tarafta bulunan RANDEVU AL butonu ile randevu oluştumaları gerekmektedir. Sarıyer mağazamızın adresi şöyledir: Mareşal Fevzi Çakmak Cad. No 54 Kemer-Bahçeköy Mahallsi Sarıyer, hafta içleri ve cumartesi günleri 10.00 ile 19.00 saatleri arasında hizmet vermektedir. Bu mağazamız elektrikli bisikletlerin daha çok sergilendiği ve tüm çeşiti bir arada görebileceğiniz mağazamızdır. Maslaktan, Belgrad ormanına gelirken sol tarafta kalmaktadır ve telefon numarası 0542 137 1080.."},
63
  ]
64
-
65
- messages = multi_turn_message.copy()
66
 
 
67
  input_words = [str(word).lower() for word in inputs.split()]
68
-
69
  for product_info in products:
70
  if product_info[0] in input_words:
71
  new_msg = f"{product_info[2]} {product_info[1][0]} ve fiyatı EURO {product_info[1][1]}"
@@ -73,10 +73,7 @@ def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=None,
73
  messages.append({"role": "system", "content": new_msg})
74
 
75
  for data in chatbot:
76
- if data["role"] == "user":
77
- messages.append({"role": "user", "content": data["content"]})
78
- elif data["role"] == "assistant":
79
- messages.append({"role": "assistant", "content": data["content"]})
80
 
81
  messages.append({"role": "user", "content": inputs})
82
 
@@ -103,9 +100,7 @@ def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=None,
103
  except Exception as e:
104
  print(f"Dosya yazma hatası (Kullanıcı): {e}")
105
 
106
- # Chatbot'a kullanıcı mesajını ekle
107
  chatbot.append({"role": "user", "content": inputs})
108
-
109
  response = requests.post(API_URL, headers=headers, json=payload, stream=True)
110
  print(f"Logging: Response code - {response.status_code}")
111
  if response.status_code != 200:
@@ -114,14 +109,12 @@ def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=None,
114
 
115
  partial_words = ""
116
  counter = 0
117
-
118
  for chunk in response.iter_lines():
119
  counter += 1
120
  if not chunk:
121
  continue
122
  chunk_str = chunk.decode('utf-8')
123
  print(f"Chunk {counter}: {chunk_str}")
124
-
125
  if chunk_str.startswith("data: ") and chunk_str != "data: [DONE]":
126
  try:
127
  chunk_data = json.loads(chunk_str[6:])
@@ -144,16 +137,12 @@ def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=None,
144
  print(f"Bot yanıtı dosyaya yazıldı: {partial_words}")
145
  except Exception as e:
146
  print(f"Dosya yazma hatası (Bot): {e}")
147
-
148
- # Chatbot içeriğini güncelle ve yield ile gönder
149
  chat = chatbot.copy()
150
  if partial_words and chat and chat[-1]["role"] == "user":
151
  chat.append({"role": "assistant", "content": partial_words})
152
  elif partial_words and chat and chat[-1]["role"] == "assistant":
153
  chat[-1] = {"role": "assistant", "content": partial_words}
154
-
155
  yield chat, history, chat_counter
156
-
157
  print(f"Son chatbot durumu: {chatbot}")
158
  return chatbot, history, chat_counter
159
 
@@ -173,12 +162,6 @@ def save_chat(chatbot):
173
  def reset_textbox():
174
  return gr.update(value='')
175
 
176
- from huggingface_hub import HfApi, create_repo
177
-
178
- # Repository oluşturma (eğer mevcut değilse)
179
- HF_TOKEN = os.getenv("HF_TOKEN")
180
- create_repo("BF", token=HF_TOKEN, repo_type="space", exist_ok=True)
181
-
182
  def upload_logs_to_hf(repo_id: str, hf_token: str, local_log_file: str = "chat_logs.txt"):
183
  """
184
  Log dosyasını Hugging Face Hub repository'sine yükler.
@@ -189,7 +172,6 @@ def upload_logs_to_hf(repo_id: str, hf_token: str, local_log_file: str = "chat_l
189
  local_log_file (str): Yüklenecek log dosyasının yolu.
190
  """
191
  api = HfApi(token=hf_token)
192
-
193
  try:
194
  api.upload_file(
195
  path_or_fileobj=local_log_file,
@@ -202,30 +184,13 @@ def upload_logs_to_hf(repo_id: str, hf_token: str, local_log_file: str = "chat_l
202
  except Exception as e:
203
  print(f"Log dosyası yüklenirken hata oluştu: {e}")
204
 
205
-
206
  def save_chat_and_upload(chatbot):
207
- # Sohbeti kaydetme işlemini burada yapın
208
  save_status = save_chat(chatbot)
209
- # Log dosyasını Hugging Face Hub'a yükleyin
210
  HF_REPO_ID = "SamiKoen/BF" # Kendi repo kimliğinizi girin.
211
- HF_TOKEN = os.getenv("HF_TOKEN") # Token'ı ortam değişkeni olarak alabilirsiniz.
212
  upload_logs_to_hf(HF_REPO_ID, HF_TOKEN)
213
-
214
  return save_status
215
 
216
- from huggingface_hub import HfApi, create_repo
217
-
218
- # HF_TOKEN'ı ortam değişkeninden alıyoruz
219
- HF_TOKEN = os.getenv("HF_TOKEN")
220
- if not HF_TOKEN:
221
- raise ValueError("HF_TOKEN ortam değişkeni ayarlanmamış!")
222
-
223
- # Repository oluşturma (space_sdk parametresi eklenmiş)
224
- create_repo("BF", token=HF_TOKEN, repo_type="space", space_sdk="gradio", exist_ok=True)
225
-
226
-
227
-
228
-
229
  # Gradio arayüzü
230
  demo_css = """
231
  #send_button, #save_button {
 
5
  import xml.etree.ElementTree as ET
6
  from huggingface_hub import HfApi, create_repo
7
 
 
 
 
 
8
  # Dosya yolu: Kalıcı depolama için öncelik, yoksa geçici dizin
9
  LOG_FILE = '/persistent-storage/chat_logs.txt'
10
  persistent_dir = '/persistent-storage'
 
25
  if not OPENAI_API_KEY:
26
  print("Hata: OPENAI_API_KEY çevre değişkeni ayarlanmamış!")
27
 
28
+ # Trek bisiklet ürünlerini çekme
29
  url = 'https://www.trekbisiklet.com.tr/output/8582384479'
30
  response = requests.get(url)
31
  root = ET.fromstring(response.content)
32
 
33
  products = []
 
34
  for item in root.findall('item'):
35
+ if item.find('isOptionOfAProduct').text == '1' and item.find('stockAmount').text > '0':
36
+ name_words = item.find('rootlabel').text.lower().split()
37
+ name = name_words[0]
38
+ full_name = ' '.join(name_words)
39
+ stockAmount = "stokta"
40
+ price = item.find('priceWithTax').text
41
+ item_info = (stockAmount, price)
42
+ products.append((name, item_info, full_name))
43
+
44
+ # HF_TOKEN ayarı ve repository oluşturma
45
+ HF_TOKEN = os.getenv("HF_TOKEN")
46
+ if not HF_TOKEN:
47
+ raise ValueError("HF_TOKEN ortam değişkeni ayarlanmamış!")
48
+ # Burada repo adınızı kullanıcı adınızla uyumlu şekilde belirleyin
49
+ create_repo("BF", token=HF_TOKEN, repo_type="space", space_sdk="gradio", exist_ok=True)
50
 
51
  def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=None, history=None):
52
  if chatbot is None:
 
61
  print(f"System message: {system_msg}")
62
 
63
  multi_turn_message = [
64
+ {"role": "system", "content": "Bir önceki sohbeti unut. Vereceğin ürün bilgisi, bu bilginin içinde yan yana yazmıyorsa veya arada başka bilgiler yazıyor ise, o bilgiyi vermeyeceksin çünkü o bilgi yanlıştır. ... (uzun metin)"}
65
  ]
 
 
66
 
67
+ messages = multi_turn_message.copy()
68
  input_words = [str(word).lower() for word in inputs.split()]
 
69
  for product_info in products:
70
  if product_info[0] in input_words:
71
  new_msg = f"{product_info[2]} {product_info[1][0]} ve fiyatı EURO {product_info[1][1]}"
 
73
  messages.append({"role": "system", "content": new_msg})
74
 
75
  for data in chatbot:
76
+ messages.append({"role": data["role"], "content": data["content"]})
 
 
 
77
 
78
  messages.append({"role": "user", "content": inputs})
79
 
 
100
  except Exception as e:
101
  print(f"Dosya yazma hatası (Kullanıcı): {e}")
102
 
 
103
  chatbot.append({"role": "user", "content": inputs})
 
104
  response = requests.post(API_URL, headers=headers, json=payload, stream=True)
105
  print(f"Logging: Response code - {response.status_code}")
106
  if response.status_code != 200:
 
109
 
110
  partial_words = ""
111
  counter = 0
 
112
  for chunk in response.iter_lines():
113
  counter += 1
114
  if not chunk:
115
  continue
116
  chunk_str = chunk.decode('utf-8')
117
  print(f"Chunk {counter}: {chunk_str}")
 
118
  if chunk_str.startswith("data: ") and chunk_str != "data: [DONE]":
119
  try:
120
  chunk_data = json.loads(chunk_str[6:])
 
137
  print(f"Bot yanıtı dosyaya yazıldı: {partial_words}")
138
  except Exception as e:
139
  print(f"Dosya yazma hatası (Bot): {e}")
 
 
140
  chat = chatbot.copy()
141
  if partial_words and chat and chat[-1]["role"] == "user":
142
  chat.append({"role": "assistant", "content": partial_words})
143
  elif partial_words and chat and chat[-1]["role"] == "assistant":
144
  chat[-1] = {"role": "assistant", "content": partial_words}
 
145
  yield chat, history, chat_counter
 
146
  print(f"Son chatbot durumu: {chatbot}")
147
  return chatbot, history, chat_counter
148
 
 
162
  def reset_textbox():
163
  return gr.update(value='')
164
 
 
 
 
 
 
 
165
  def upload_logs_to_hf(repo_id: str, hf_token: str, local_log_file: str = "chat_logs.txt"):
166
  """
167
  Log dosyasını Hugging Face Hub repository'sine yükler.
 
172
  local_log_file (str): Yüklenecek log dosyasının yolu.
173
  """
174
  api = HfApi(token=hf_token)
 
175
  try:
176
  api.upload_file(
177
  path_or_fileobj=local_log_file,
 
184
  except Exception as e:
185
  print(f"Log dosyası yüklenirken hata oluştu: {e}")
186
 
 
187
  def save_chat_and_upload(chatbot):
 
188
  save_status = save_chat(chatbot)
 
189
  HF_REPO_ID = "SamiKoen/BF" # Kendi repo kimliğinizi girin.
190
+ HF_TOKEN = os.getenv("HF_TOKEN")
191
  upload_logs_to_hf(HF_REPO_ID, HF_TOKEN)
 
192
  return save_status
193
 
 
 
 
 
 
 
 
 
 
 
 
 
 
194
  # Gradio arayüzü
195
  demo_css = """
196
  #send_button, #save_button {