SamiKoen commited on
Commit
85d90c4
·
verified ·
1 Parent(s): 9a3017f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -105
app.py CHANGED
@@ -8,28 +8,28 @@ import time
8
  import threading
9
  from huggingface_hub import HfApi, create_repo
10
 
11
- # Global değişken: sohbet geçmişi (otomatik kayıt için kullanılacak)
12
  global_chat_history = []
13
 
14
- # Dosya yolu: Kalıcı depolama için öncelik, yoksa geçici dizin
15
  LOG_FILE = '/persistent-storage/chat_logs.txt'
16
  persistent_dir = '/persistent-storage'
17
 
18
  if not os.path.exists(persistent_dir):
19
  try:
20
  os.makedirs(persistent_dir, exist_ok=True)
21
- print(f"Kalıcı depolama dizini oluşturuldu: {persistent_dir}")
22
  except Exception as e:
23
- print(f"Kalıcı depolama dizini oluşturulamadı: {e}. Geçici dizine geri dönülüyor.")
24
  LOG_FILE = 'chat_logs.txt'
25
 
26
- print(f"Dosya yolu: {os.path.abspath(LOG_FILE)}")
27
 
28
  # API ayarları
29
  API_URL = "https://api.openai.com/v1/chat/completions"
30
  OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
31
  if not OPENAI_API_KEY:
32
- print("Hata: OPENAI_API_KEY çevre değişkeni ayarlanmamış!")
33
 
34
  # Trek bisiklet ürünlerini çekme
35
  url = 'https://www.trekbisiklet.com.tr/output/8582384479'
@@ -44,18 +44,20 @@ for item in root.findall('item'):
44
  full_name = ' '.join(name_words)
45
  stockAmount = "stokta"
46
  price = item.find('priceWithTax').text
47
- item_info = (stockAmount, price)
48
- products.append((name, item_info, full_name))
49
 
50
- # HF_TOKEN yerine "hfapi" ortam değişkenini alıyoruz
51
  hfapi = os.getenv("hfapi")
52
  if not hfapi:
53
- raise ValueError("hfapi ortam değişkeni ayarlanmamış!")
54
 
55
- # Repository oluşturma (repo adı "BF" kullanıcı adınızla uyumlu olmalı; space_sdk eklenmiş)
56
  create_repo("BF", token=hfapi, repo_type="space", space_sdk="gradio", exist_ok=True)
57
 
58
- def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=None, history=None):
 
 
 
59
  global global_chat_history
60
  if chatbot is None:
61
  chatbot = []
@@ -66,23 +68,25 @@ def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=None,
66
  "Content-Type": "application/json",
67
  "Authorization": f"Bearer {OPENAI_API_KEY}"
68
  }
69
- print(f"System message: {system_msg}")
70
 
71
- multi_turn_message = [
 
72
  {"role": "system", "content": "Bir önceki sohbeti unutma. 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)"}
73
  ]
74
 
75
- messages = multi_turn_message.copy()
76
- input_words = [str(word).lower() for word in inputs.split()]
 
77
  for product_info in products:
78
  if product_info[0] in input_words:
79
  new_msg = f"{product_info[2]} {product_info[1][0]} ve fiyatı EURO {product_info[1][1]}"
80
- print(new_msg)
81
  messages.append({"role": "system", "content": new_msg})
82
 
 
83
  for data in chatbot:
84
  messages.append({"role": data["role"], "content": data["content"]})
85
 
 
86
  messages.append({"role": "user", "content": inputs})
87
 
88
  payload = {
@@ -91,29 +95,26 @@ def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=None,
91
  "temperature": 0.7,
92
  "top_p": 0.9,
93
  "n": 1,
94
- "stream": True, # streaming açık
95
  "presence_penalty": 0,
96
  "frequency_penalty": 0,
97
  }
98
 
99
  chat_counter += 1
100
  history.append(inputs)
101
- print(f"Logging: Payload is - {payload}")
102
 
103
- # Kullanıcı mesajını dosyaya yaz
104
  try:
105
  with open(LOG_FILE, 'a', encoding='utf-8') as f:
106
  f.write(f"User: {inputs}\n")
107
- print(f"Kullanıcı mesajı dosyaya yazıldı: {inputs}")
108
  except Exception as e:
109
- print(f"Dosya yazma hatası (Kullanıcı): {e}")
110
 
111
- # Chatbot'a kullanıcı mesajını ekle
112
  chatbot.append({"role": "user", "content": inputs})
113
  response = requests.post(API_URL, headers=headers, json=payload, stream=True)
114
- print(f"Logging: Response code - {response.status_code}")
115
  if response.status_code != 200:
116
- print(f"API hatası: {response.text}")
117
  return chatbot, history, chat_counter
118
 
119
  partial_words = ""
@@ -121,56 +122,43 @@ def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=None,
121
  if not chunk:
122
  continue
123
  chunk_str = chunk.decode('utf-8')
124
- # Her chunk için loglama yerine yalnızca tamamlanmış yanıtı logluyoruz.
125
  if chunk_str.startswith("data: ") and chunk_str != "data: [DONE]":
126
  try:
127
  chunk_data = json.loads(chunk_str[6:])
128
  delta = chunk_data['choices'][0]['delta']
129
  if 'content' in delta and delta['content']:
130
- content = delta['content']
131
- partial_words += content
132
  except json.JSONDecodeError as e:
133
- print(f"JSON parse hatası: {e} - Chunk: {chunk_str}")
134
  elif chunk_str == "data: [DONE]":
135
- print("Akış tamamlandı: [DONE] alındı")
136
  if partial_words:
137
- # Yanıt tamamlandığında tek seferde log yazıyoruz.
138
- print(f"Tamamlanan mesaj: {partial_words}")
139
  history.append(partial_words)
140
  chatbot.append({"role": "assistant", "content": partial_words})
141
  try:
142
  with open(LOG_FILE, 'a', encoding='utf-8') as f:
143
  f.write(f"Bot: {partial_words}\n")
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
- chat = chatbot.copy()
148
- if partial_words and chat and chat[-1]["role"] == "user":
149
- chat.append({"role": "assistant", "content": partial_words})
150
- elif partial_words and chat and chat[-1]["role"] == "assistant":
151
- chat[-1] = {"role": "assistant", "content": partial_words}
152
  global_chat_history = chatbot.copy()
153
- yield chat, history, chat_counter
154
- print(f"Son chatbot durumu: {chatbot}")
155
  global_chat_history = chatbot.copy()
156
  return chatbot, history, chat_counter
157
 
158
  def save_chat(chatbot):
 
 
 
159
  file_path = os.path.abspath(LOG_FILE)
160
  try:
161
  with open(LOG_FILE, 'a', encoding='utf-8') as f:
162
  f.write("\n--- Kayıt Edilen Sohbet ---\n")
163
  for msg in chatbot:
164
  f.write(f"{msg['role'].capitalize()}: {msg['content']}\n")
165
- print(f"Sohbet dosyaya kaydedildi: {file_path}")
166
  return f"Sohbet başarıyla kaydedildi!\nDosya: {file_path}"
167
  except Exception as e:
168
- print(f"Kayıt hatası: {e}")
169
  return f"Kayıt hatası: {e}\nDosya: {file_path}"
170
 
171
- def reset_textbox():
172
- return gr.update(value='')
173
-
174
  def upload_logs_to_hf(repo_id: str, hf_token: str, local_log_file: str = "chat_logs.txt"):
175
  """
176
  Log dosyasını Hugging Face Hub repository'sine yükler.
@@ -184,46 +172,47 @@ def upload_logs_to_hf(repo_id: str, hf_token: str, local_log_file: str = "chat_l
184
  repo_type="space",
185
  commit_message="Log dosyası güncellendi"
186
  )
187
- print(f"Log dosyası başarıyla yüklendi: {local_log_file}")
188
  except Exception as e:
189
- print(f"Log dosyası yüklenirken hata oluştu: {e}")
190
 
191
  def save_chat_and_upload(chatbot):
 
 
 
192
  save_status = save_chat(chatbot)
193
- HF_REPO_ID = "SamiKoen/BF" # Kendi repo kimliğinizi girin.
194
- hfapi = os.getenv("hfapi")
195
- upload_logs_to_hf(HF_REPO_ID, hfapi)
196
  return save_status
197
 
198
- # Otomatik kayıt fonksiyonu (schedule ile çağrılacak)
199
  def scheduled_save():
 
 
 
200
  global global_chat_history
201
- print("DEBUG: scheduled_save() fonksiyonu tetiklendi:", time.ctime())
202
  if global_chat_history:
203
- print("DEBUG: global_chat_history boş değil, sohbet kaydediliyor...")
204
  save_chat_and_upload(global_chat_history)
205
- else:
206
- print("DEBUG: global_chat_history boş, kaydedilecek sohbet bulunamadı.")
207
 
208
- # Scheduler'ı arka planda çalıştıracak fonksiyon
209
  def run_scheduler():
210
- print("DEBUG: Scheduler thread başlatıldı:", time.ctime())
 
 
211
  while True:
212
  schedule.run_pending()
213
  time.sleep(1)
214
 
215
- # Belirli saatlerde otomatik kayıt (örn. 12:00, 18:00 ve 23:00)
216
  schedule.every().day.at("12:00").do(scheduled_save)
217
  schedule.every().day.at("18:00").do(scheduled_save)
218
  schedule.every().day.at("23:00").do(scheduled_save)
219
 
220
- # Scheduler'ı daemon thread ile başlatıyoruz
221
  scheduler_thread = threading.Thread(target=run_scheduler, daemon=True)
222
  scheduler_thread.start()
223
 
224
  # Gradio arayüzü
225
  demo_css = """
226
- #send_button, #save_button {
227
  background-color: #0b93f6;
228
  border: none;
229
  color: white;
@@ -238,22 +227,9 @@ demo_css = """
238
  transition: background-color 0.3s;
239
  margin: 5px;
240
  }
241
- #send_button:hover, #save_button:hover {
242
  background-color: #0077c0;
243
  }
244
- .fixed_button_container {
245
- padding: 0px;
246
- margin: 0px 0 0 0px;
247
- }
248
- #custom_row {
249
- width: 150% !important;
250
- flex-wrap: nowrap !important;
251
- }
252
- @media only screen and (max-width: 1000px) {
253
- .custom_row {
254
- flex-wrap: nowrap !important;
255
- }
256
- }
257
  #chatbot {
258
  height: 100vh;
259
  overflow-y: auto;
@@ -267,37 +243,17 @@ theme = gr.themes.Base(
267
  )
268
 
269
  with gr.Blocks(css=demo_css, theme=theme) as demo:
 
270
  if not os.path.exists(LOG_FILE):
271
  with open(LOG_FILE, 'w', encoding='utf-8') as f:
272
  f.write("--- Yeni Sohbet ---\n")
273
 
274
- with gr.Column(elem_id="col_container"):
275
- with gr.Accordion("", open=False, visible=False):
276
- system_msg = gr.Textbox(value="")
277
- new_msg = gr.Textbox(value="")
278
- accordion_msg = gr.HTML(value="", visible=False)
279
-
280
- chatbot = gr.Chatbot(label='Trek Asistanı', elem_id="chatbot", type="messages")
281
-
282
- with gr.Row(elem_id="custom_row"):
283
- inputs = gr.Textbox(
284
- placeholder="Buraya yazıp, entera basın",
285
- show_label=False,
286
- container=False,
287
- )
288
- with gr.Column(elem_classes="fixed_button_container"):
289
- send_button = gr.Button(value="Kapat", elem_id="send_button")
290
-
291
- state = gr.State([])
292
-
293
- with gr.Accordion("", open=False, visible=False):
294
- top_p = gr.Slider(minimum=0, maximum=1.0, value=0.5, step=0.05, interactive=False, visible=False)
295
- temperature = gr.Slider(minimum=0, maximum=5.0, value=0.1, step=0.1, interactive=False, visible=False)
296
- chat_counter = gr.Number(value=0, visible=False, precision=0)
297
-
298
- inputs.submit(predict, [system_msg, inputs, top_p, temperature, chat_counter, chatbot, state], [chatbot, state, chat_counter])
299
- inputs.submit(reset_textbox, [], [inputs])
300
- send_button.click(predict, [system_msg, inputs, top_p, temperature, chat_counter, chatbot, state], [chatbot, state, chat_counter])
301
- send_button.click(reset_textbox, [], [inputs])
302
-
303
- demo.queue(max_size=10).launch(debug=True)
 
8
  import threading
9
  from huggingface_hub import HfApi, create_repo
10
 
11
+ # Global sohbet geçmişi (otomatik kayıt için kullanılacak)
12
  global_chat_history = []
13
 
14
+ # Log dosyası ve kalıcı dizin ayarları
15
  LOG_FILE = '/persistent-storage/chat_logs.txt'
16
  persistent_dir = '/persistent-storage'
17
 
18
  if not os.path.exists(persistent_dir):
19
  try:
20
  os.makedirs(persistent_dir, exist_ok=True)
21
+ print(f"Persistent directory created: {persistent_dir}")
22
  except Exception as e:
23
+ print(f"Failed to create persistent directory: {e}. Using temporary directory.")
24
  LOG_FILE = 'chat_logs.txt'
25
 
26
+ print(f"Log file path: {os.path.abspath(LOG_FILE)}")
27
 
28
  # API ayarları
29
  API_URL = "https://api.openai.com/v1/chat/completions"
30
  OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
31
  if not OPENAI_API_KEY:
32
+ print("Error: OPENAI_API_KEY environment variable is not set!")
33
 
34
  # Trek bisiklet ürünlerini çekme
35
  url = 'https://www.trekbisiklet.com.tr/output/8582384479'
 
44
  full_name = ' '.join(name_words)
45
  stockAmount = "stokta"
46
  price = item.find('priceWithTax').text
47
+ products.append((name, (stockAmount, price), full_name))
 
48
 
49
+ # Hugging Face ayarları: hfapi ortam değişkeni kullanılacak
50
  hfapi = os.getenv("hfapi")
51
  if not hfapi:
52
+ raise ValueError("hfapi environment variable is not set!")
53
 
54
+ # Repository oluşturma (repo adı "BF" kullanıcı adınızla uyumlu olmalı)
55
  create_repo("BF", token=hfapi, repo_type="space", space_sdk="gradio", exist_ok=True)
56
 
57
+ def predict(inputs, chat_counter, chatbot=None, history=None):
58
+ """
59
+ Kullanıcı girişini işleyip API'ye gönderir ve gelen yanıtı stream olarak chatbot'a ekler.
60
+ """
61
  global global_chat_history
62
  if chatbot is None:
63
  chatbot = []
 
68
  "Content-Type": "application/json",
69
  "Authorization": f"Bearer {OPENAI_API_KEY}"
70
  }
 
71
 
72
+ # Çok aşamalı konuşmalar için temel sistem mesajı
73
+ system_messages = [
74
  {"role": "system", "content": "Bir önceki sohbeti unutma. 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)"}
75
  ]
76
 
77
+ # Kullanıcı girişiyle eşleşen ürün bilgilerini ekle
78
+ messages = system_messages.copy()
79
+ input_words = [word.lower() for word in inputs.split()]
80
  for product_info in products:
81
  if product_info[0] in input_words:
82
  new_msg = f"{product_info[2]} {product_info[1][0]} ve fiyatı EURO {product_info[1][1]}"
 
83
  messages.append({"role": "system", "content": new_msg})
84
 
85
+ # Önceki sohbet geçmişini ekle
86
  for data in chatbot:
87
  messages.append({"role": data["role"], "content": data["content"]})
88
 
89
+ # Kullanıcı girişini ekle
90
  messages.append({"role": "user", "content": inputs})
91
 
92
  payload = {
 
95
  "temperature": 0.7,
96
  "top_p": 0.9,
97
  "n": 1,
98
+ "stream": True, # Streaming mod açık
99
  "presence_penalty": 0,
100
  "frequency_penalty": 0,
101
  }
102
 
103
  chat_counter += 1
104
  history.append(inputs)
 
105
 
106
+ # Kullanıcı mesajını log dosyasına yaz
107
  try:
108
  with open(LOG_FILE, 'a', encoding='utf-8') as f:
109
  f.write(f"User: {inputs}\n")
 
110
  except Exception as e:
111
+ print(f"Error writing user message to log: {e}")
112
 
 
113
  chatbot.append({"role": "user", "content": inputs})
114
  response = requests.post(API_URL, headers=headers, json=payload, stream=True)
115
+
116
  if response.status_code != 200:
117
+ print(f"API error: {response.text}")
118
  return chatbot, history, chat_counter
119
 
120
  partial_words = ""
 
122
  if not chunk:
123
  continue
124
  chunk_str = chunk.decode('utf-8')
 
125
  if chunk_str.startswith("data: ") and chunk_str != "data: [DONE]":
126
  try:
127
  chunk_data = json.loads(chunk_str[6:])
128
  delta = chunk_data['choices'][0]['delta']
129
  if 'content' in delta and delta['content']:
130
+ partial_words += delta['content']
 
131
  except json.JSONDecodeError as e:
132
+ print(f"JSON parse error: {e} - Chunk: {chunk_str}")
133
  elif chunk_str == "data: [DONE]":
134
+ # Yanıt tamamlandığında, final cevabı logla ve kaydet
135
  if partial_words:
 
 
136
  history.append(partial_words)
137
  chatbot.append({"role": "assistant", "content": partial_words})
138
  try:
139
  with open(LOG_FILE, 'a', encoding='utf-8') as f:
140
  f.write(f"Bot: {partial_words}\n")
 
141
  except Exception as e:
142
+ print(f"Error writing bot message to log: {e}")
 
 
 
 
 
143
  global_chat_history = chatbot.copy()
144
+ yield chatbot, history, chat_counter
 
145
  global_chat_history = chatbot.copy()
146
  return chatbot, history, chat_counter
147
 
148
  def save_chat(chatbot):
149
+ """
150
+ Sohbet geçmişini log dosyasına kaydeder.
151
+ """
152
  file_path = os.path.abspath(LOG_FILE)
153
  try:
154
  with open(LOG_FILE, 'a', encoding='utf-8') as f:
155
  f.write("\n--- Kayıt Edilen Sohbet ---\n")
156
  for msg in chatbot:
157
  f.write(f"{msg['role'].capitalize()}: {msg['content']}\n")
 
158
  return f"Sohbet başarıyla kaydedildi!\nDosya: {file_path}"
159
  except Exception as e:
 
160
  return f"Kayıt hatası: {e}\nDosya: {file_path}"
161
 
 
 
 
162
  def upload_logs_to_hf(repo_id: str, hf_token: str, local_log_file: str = "chat_logs.txt"):
163
  """
164
  Log dosyasını Hugging Face Hub repository'sine yükler.
 
172
  repo_type="space",
173
  commit_message="Log dosyası güncellendi"
174
  )
 
175
  except Exception as e:
176
+ print(f"Error uploading log file: {e}")
177
 
178
  def save_chat_and_upload(chatbot):
179
+ """
180
+ Sohbeti kaydedip Hugging Face Hub'a yükler.
181
+ """
182
  save_status = save_chat(chatbot)
183
+ HF_REPO_ID = "SamiKoen/BF" # Kendi repository ID'nizi girin
184
+ hf_token = os.getenv("hfapi")
185
+ upload_logs_to_hf(HF_REPO_ID, hf_token)
186
  return save_status
187
 
 
188
  def scheduled_save():
189
+ """
190
+ Belirlenmiş saatlerde otomatik olarak sohbeti kaydeder.
191
+ """
192
  global global_chat_history
 
193
  if global_chat_history:
 
194
  save_chat_and_upload(global_chat_history)
 
 
195
 
 
196
  def run_scheduler():
197
+ """
198
+ Scheduler'ı arka planda çalıştırır.
199
+ """
200
  while True:
201
  schedule.run_pending()
202
  time.sleep(1)
203
 
204
+ # Belirli saatlerde otomatik kaydı planlama (ör: 12:00, 18:00, 23:00)
205
  schedule.every().day.at("12:00").do(scheduled_save)
206
  schedule.every().day.at("18:00").do(scheduled_save)
207
  schedule.every().day.at("23:00").do(scheduled_save)
208
 
209
+ # Scheduler'ı daemon thread ile başlat
210
  scheduler_thread = threading.Thread(target=run_scheduler, daemon=True)
211
  scheduler_thread.start()
212
 
213
  # Gradio arayüzü
214
  demo_css = """
215
+ #send_button {
216
  background-color: #0b93f6;
217
  border: none;
218
  color: white;
 
227
  transition: background-color 0.3s;
228
  margin: 5px;
229
  }
230
+ #send_button:hover {
231
  background-color: #0077c0;
232
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
233
  #chatbot {
234
  height: 100vh;
235
  overflow-y: auto;
 
243
  )
244
 
245
  with gr.Blocks(css=demo_css, theme=theme) as demo:
246
+ # Log dosyası yoksa başlat
247
  if not os.path.exists(LOG_FILE):
248
  with open(LOG_FILE, 'w', encoding='utf-8') as f:
249
  f.write("--- Yeni Sohbet ---\n")
250
 
251
+ chatbot = gr.Chatbot(label='Trek Asistanı', elem_id="chatbot", type="messages")
252
+ inputs = gr.Textbox(placeholder="Buraya yazıp, entera basın", show_label=False)
253
+ state = gr.State([]) # Sohbet geçmişi için
254
+ chat_counter = gr.Number(value=0, visible=False, precision=0)
255
+
256
+ inputs.submit(predict, [inputs, chat_counter, chatbot, state], [chatbot, state, chat_counter])
257
+ inputs.submit(lambda: gr.update(value=""), [], [inputs])
258
+
259
+ demo.launch(debug=True, queue=True)