SamiKoen commited on
Commit
e7590dc
·
verified ·
1 Parent(s): 35d3ff2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +75 -62
app.py CHANGED
@@ -4,12 +4,14 @@ import json
4
  import requests
5
  import xml.etree.ElementTree as ET
6
  from huggingface_hub import HfApi, create_repo
 
 
 
7
 
8
- # Log dosyası adı: "chat_logs.txt"
9
  LOG_FILE = 'chat_logs.txt'
10
  persistent_dir = '/persistent-storage'
11
 
12
- # Eğer persistent dizini mevcutsa, log dosyasını oraya yerleştiriyoruz.
13
  if os.path.exists(persistent_dir):
14
  LOG_FILE = os.path.join(persistent_dir, LOG_FILE)
15
  else:
@@ -39,14 +41,64 @@ for item in root.findall('item'):
39
  item_info = (stockAmount, price)
40
  products.append((name, item_info, full_name))
41
 
42
- # HF_TOKEN yerine "hfapi" ortam değişkenini alıyoruz
43
  hfapi = os.getenv("hfapi")
44
  if not hfapi:
45
  raise ValueError("hfapi ortam değişkeni ayarlanmamış!")
46
 
47
- # Repository oluşturma (repo adı "BF" kullanıcı adınızla uyumlu olmalı; space_sdk eklenmiş)
48
  create_repo("BF", token=hfapi, repo_type="space", space_sdk="gradio", exist_ok=True)
49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=None, history=None):
51
  if chatbot is None:
52
  chatbot = []
@@ -60,7 +112,7 @@ def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=None,
60
  print(f"System message: {system_msg}")
61
 
62
  multi_turn_message = [
63
- {"role": "system", "content": "Bir önceki sohbeti unut. Vereceğin ürün bilgisi, bu bilginin içinde yan yana yazılmıyorsa veya arada başka bilgiler yazıyor ise, o bilgiyi vermeyeceksin çünkü o bilgi yanlıştır. ... (uzun metin)"}
64
  ]
65
 
66
  messages = multi_turn_message.copy()
@@ -90,7 +142,6 @@ def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=None,
90
  chat_counter += 1
91
  history.append(inputs)
92
 
93
- # Kullanıcı mesajını log dosyasına yazıyoruz
94
  try:
95
  with open(LOG_FILE, 'a', encoding='utf-8') as f:
96
  f.write(f"User: {inputs}\n")
@@ -98,7 +149,6 @@ def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=None,
98
  except Exception as e:
99
  print(f"Dosya yazma hatası (Kullanıcı): {e}")
100
 
101
- # Chatbot'a kullanıcı mesajını ekle
102
  chatbot.append({"role": "user", "content": inputs})
103
  response = requests.post(API_URL, headers=headers, json=payload, stream=True)
104
 
@@ -106,7 +156,6 @@ def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=None,
106
  print(f"API hatası: {response.text}")
107
  return chatbot, history, chat_counter
108
 
109
- # Gelen yanıt parçalarını toplayıp tek bir yanıt oluşturuyoruz
110
  assistant_response = ""
111
  for chunk in response.iter_lines():
112
  if not chunk:
@@ -123,7 +172,6 @@ def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=None,
123
  elif chunk_str == "data: [DONE]":
124
  break
125
 
126
- # Tüm yanıtı tek parça halinde log dosyasına yazıyoruz
127
  if assistant_response:
128
  history.append(assistant_response)
129
  chatbot.append({"role": "assistant", "content": assistant_response})
@@ -136,54 +184,13 @@ def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=None,
136
 
137
  return chatbot, history, chat_counter
138
 
139
- def save_chat(chatbot):
140
- file_path = os.path.abspath(LOG_FILE)
141
- try:
142
- with open(LOG_FILE, 'a', encoding='utf-8') as f:
143
- f.write("\n--- Kayıt Edilen Sohbet ---\n")
144
- for msg in chatbot:
145
- f.write(f"{msg['role'].capitalize()}: {msg['content']}\n")
146
- print(f"Sohbet dosyaya kaydedildi: {file_path}")
147
- return f"Sohbet başarıyla kaydedildi!\nDosya: {file_path}"
148
- except Exception as e:
149
- print(f"Kayıt hatası: {e}")
150
- return f"Kayıt hatası: {e}\nDosya: {file_path}"
151
-
152
  def reset_textbox():
153
  return gr.update(value='')
154
 
155
- def upload_logs_to_hf(repo_id: str, hf_token: str, local_log_file: str = "chat_logs.txt"):
156
- """
157
- Log dosyasını Hugging Face Hub repository'sine yükler.
158
-
159
- Args:
160
- repo_id (str): Repository kimliği (örn. "SamiKoen/BF").
161
- hf_token (str): Hugging Face API token'ınız.
162
- local_log_file (str): Yüklenecek log dosyasının yolu.
163
- """
164
- api = HfApi(token=hf_token)
165
- try:
166
- api.upload_file(
167
- path_or_fileobj=local_log_file,
168
- path_in_repo=local_log_file,
169
- repo_id=repo_id,
170
- repo_type="space",
171
- commit_message="Log dosyası güncellendi"
172
- )
173
- print(f"Log dosyası başarıyla yüklendi: {local_log_file}")
174
- except Exception as e:
175
- print(f"Log dosyası yüklenirken hata oluştu: {e}")
176
-
177
- def save_chat_and_upload(chatbot):
178
- save_status = save_chat(chatbot)
179
- HF_REPO_ID = "SamiKoen/BF" # Kendi repo kimliğinizi girin.
180
- hfapi = os.getenv("hfapi")
181
- upload_logs_to_hf(HF_REPO_ID, hfapi)
182
- return save_status
183
-
184
- # Gradio arayüzü
185
  demo_css = """
186
- #send_button, #save_button {
187
  background-color: #0b93f6;
188
  border: none;
189
  color: white;
@@ -198,7 +205,7 @@ demo_css = """
198
  transition: background-color 0.3s;
199
  margin: 5px;
200
  }
201
- #send_button:hover, #save_button:hover {
202
  background-color: #0077c0;
203
  }
204
  .fixed_button_container {
@@ -226,6 +233,7 @@ theme = gr.themes.Base(
226
  spacing_size="sm",
227
  )
228
 
 
229
  with gr.Blocks(css=demo_css, theme=theme) as demo:
230
  if not os.path.exists(LOG_FILE):
231
  with open(LOG_FILE, 'w', encoding='utf-8') as f:
@@ -247,20 +255,25 @@ with gr.Blocks(css=demo_css, theme=theme) as demo:
247
  )
248
  with gr.Column(elem_classes="fixed_button_container"):
249
  send_button = gr.Button(value="Gönder", elem_id="send_button")
250
- save_button = gr.Button(value="Kayıt Et", elem_id="save_button")
251
 
252
  state = gr.State([])
253
- save_status = gr.Textbox(label="Kayıt Durum", interactive=False)
254
 
255
  with gr.Accordion("", open=False, visible=False):
256
  top_p = gr.Slider(minimum=0, maximum=1.0, value=0.5, step=0.05, interactive=False, visible=False)
257
  temperature = gr.Slider(minimum=0, maximum=5.0, value=0.1, step=0.1, interactive=False, visible=False)
258
  chat_counter = gr.Number(value=0, visible=False, precision=0)
259
 
260
- inputs.submit(predict, [system_msg, inputs, top_p, temperature, chat_counter, chatbot, state], [chatbot, state, chat_counter])
261
- inputs.submit(reset_textbox, [], [inputs])
262
- send_button.click(predict, [system_msg, inputs, top_p, temperature, chat_counter, chatbot, state], [chatbot, state, chat_counter])
263
- send_button.click(reset_textbox, [], [inputs])
264
- save_button.click(save_chat_and_upload, [chatbot], [save_status])
 
 
 
 
 
 
 
265
 
266
- demo.queue(max_size=10).launch(debug=True, share=True)
 
4
  import requests
5
  import xml.etree.ElementTree as ET
6
  from huggingface_hub import HfApi, create_repo
7
+ import schedule
8
+ import time
9
+ import threading
10
 
11
+ # Log dosyası adı ve yolu
12
  LOG_FILE = 'chat_logs.txt'
13
  persistent_dir = '/persistent-storage'
14
 
 
15
  if os.path.exists(persistent_dir):
16
  LOG_FILE = os.path.join(persistent_dir, LOG_FILE)
17
  else:
 
41
  item_info = (stockAmount, price)
42
  products.append((name, item_info, full_name))
43
 
44
+ # Hugging Face token
45
  hfapi = os.getenv("hfapi")
46
  if not hfapi:
47
  raise ValueError("hfapi ortam değişkeni ayarlanmamış!")
48
 
49
+ # Repository oluşturma
50
  create_repo("BF", token=hfapi, repo_type="space", space_sdk="gradio", exist_ok=True)
51
 
52
+ # Sohbeti yerel dosyaya kaydetme
53
+ def save_chat(chatbot):
54
+ file_path = os.path.abspath(LOG_FILE)
55
+ try:
56
+ with open(LOG_FILE, 'a', encoding='utf-8') as f:
57
+ f.write("\n--- Zamanlanmış Kayıt: {} ---\n".format(time.strftime("%Y-%m-%d %H:%M:%S")))
58
+ for msg in chatbot:
59
+ f.write(f"{msg['role'].capitalize()}: {msg['content']}\n")
60
+ print(f"Sohbet dosyaya kaydedildi: {file_path}")
61
+ return True
62
+ except Exception as e:
63
+ print(f"Kayıt hatası: {e}")
64
+ return False
65
+
66
+ # Hugging Face’e log dosyasını yükleme
67
+ def upload_logs_to_hf(repo_id: str, hf_token: str, local_log_file: str = LOG_FILE):
68
+ api = HfApi(token=hf_token)
69
+ try:
70
+ api.upload_file(
71
+ path_or_fileobj=local_log_file,
72
+ path_in_repo="chat_logs.txt",
73
+ repo_id=repo_id,
74
+ repo_type="space",
75
+ commit_message="Otomatik log dosyası güncellemesi - {}".format(time.strftime("%Y-%m-%d %H:%M:%S"))
76
+ )
77
+ print(f"Log dosyası HF'ye yüklendi: {local_log_file}")
78
+ return True
79
+ except Exception as e:
80
+ print(f"HF yükleme hatası: {e}")
81
+ return False
82
+
83
+ # Zamanlayıcıyı arka planda çalıştırma
84
+ def run_scheduler(chatbot_ref):
85
+ def scheduled_save_and_upload():
86
+ if chatbot_ref:
87
+ save_success = save_chat(chatbot_ref)
88
+ if save_success:
89
+ HF_REPO_ID = "SamiKoen/BF" # Kendi repo ID’nizi buraya koyun
90
+ upload_logs_to_hf(HF_REPO_ID, hfapi)
91
+ print(f"Zamanlanmış işlem tamamlandı: {time.strftime('%H:%M:%S')}")
92
+
93
+ schedule.every().day.at("09:00").do(scheduled_save_and_upload)
94
+ schedule.every().day.at("15:00").do(scheduled_save_and_upload)
95
+ schedule.every().day.at("21:00").do(scheduled_save_and_upload)
96
+
97
+ while True:
98
+ schedule.run_pending()
99
+ time.sleep(60)
100
+
101
+ # Chatbot tahmin fonksiyonu
102
  def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=None, history=None):
103
  if chatbot is None:
104
  chatbot = []
 
112
  print(f"System message: {system_msg}")
113
 
114
  multi_turn_message = [
115
+ {"role": "system", "content": "Bir önceki sohbeti unut. Vereceğin ürün bilgisi, bu bilginin içinde yan yana yazılmıyorsa veya arada başka bilgiler yazıyor ise, o bilgiyi vermeyeceksin çünkü o bilgi yanlıştır."}
116
  ]
117
 
118
  messages = multi_turn_message.copy()
 
142
  chat_counter += 1
143
  history.append(inputs)
144
 
 
145
  try:
146
  with open(LOG_FILE, 'a', encoding='utf-8') as f:
147
  f.write(f"User: {inputs}\n")
 
149
  except Exception as e:
150
  print(f"Dosya yazma hatası (Kullanıcı): {e}")
151
 
 
152
  chatbot.append({"role": "user", "content": inputs})
153
  response = requests.post(API_URL, headers=headers, json=payload, stream=True)
154
 
 
156
  print(f"API hatası: {response.text}")
157
  return chatbot, history, chat_counter
158
 
 
159
  assistant_response = ""
160
  for chunk in response.iter_lines():
161
  if not chunk:
 
172
  elif chunk_str == "data: [DONE]":
173
  break
174
 
 
175
  if assistant_response:
176
  history.append(assistant_response)
177
  chatbot.append({"role": "assistant", "content": assistant_response})
 
184
 
185
  return chatbot, history, chat_counter
186
 
187
+ # Textbox’ı sıfırlama
 
 
 
 
 
 
 
 
 
 
 
 
188
  def reset_textbox():
189
  return gr.update(value='')
190
 
191
+ # Gradio CSS
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
192
  demo_css = """
193
+ #send_button {
194
  background-color: #0b93f6;
195
  border: none;
196
  color: white;
 
205
  transition: background-color 0.3s;
206
  margin: 5px;
207
  }
208
+ #send_button:hover {
209
  background-color: #0077c0;
210
  }
211
  .fixed_button_container {
 
233
  spacing_size="sm",
234
  )
235
 
236
+ # Gradio arayüzü
237
  with gr.Blocks(css=demo_css, theme=theme) as demo:
238
  if not os.path.exists(LOG_FILE):
239
  with open(LOG_FILE, 'w', encoding='utf-8') as f:
 
255
  )
256
  with gr.Column(elem_classes="fixed_button_container"):
257
  send_button = gr.Button(value="Gönder", elem_id="send_button")
 
258
 
259
  state = gr.State([])
 
260
 
261
  with gr.Accordion("", open=False, visible=False):
262
  top_p = gr.Slider(minimum=0, maximum=1.0, value=0.5, step=0.05, interactive=False, visible=False)
263
  temperature = gr.Slider(minimum=0, maximum=5.0, value=0.1, step=0.1, interactive=False, visible=False)
264
  chat_counter = gr.Number(value=0, visible=False, precision=0)
265
 
266
+ # Chatbot referansını güncelleme
267
+ chatbot_ref = []
268
+ def update_chatbot_ref(chat):
269
+ chatbot_ref[:] = chat
270
+ return chat
271
+
272
+ inputs.submit(predict, [system_msg, inputs, top_p, temperature, chat_counter, chatbot, state], [chatbot, state, chat_counter]).then(update_chatbot_ref, chatbot, chatbot).then(reset_textbox, [], [inputs])
273
+ send_button.click(predict, [system_msg, inputs, top_p, temperature, chat_counter, chatbot, state], [chatbot, state, chat_counter]).then(update_chatbot_ref, chatbot, chatbot).then(reset_textbox, [], [inputs])
274
+
275
+ # Zamanlayıcıyı başlat
276
+ scheduler_thread = threading.Thread(target=run_scheduler, args=(chatbot_ref,), daemon=True)
277
+ scheduler_thread.start()
278
 
279
+ demo.queue(max_size=10).launch(debug=True, share=True)