SamiKoen commited on
Commit
01f94ab
·
verified ·
1 Parent(s): 3306257

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -43
app.py CHANGED
@@ -41,46 +41,15 @@ for item in root.findall('item'):
41
  item_info = (stockAmount, price)
42
  products.append((name, item_info, full_name))
43
 
44
- # Ortam değişkeninde "hfapi" tanımlı; tokenimizi alıyoruz.
45
  hfapi = os.getenv("hfapi")
46
  if not hfapi:
47
  raise ValueError("hfapi ortam değişkeni ayarlanmamış!")
48
 
49
- # Ana Space için repo oluşturuluyor (repo adı "BF")
50
  create_repo("BF", token=hfapi, repo_type="space", space_sdk="gradio", exist_ok=True)
51
- # Log commitleri için ayrı bir repo oluşturuluyor; tam repo id'sini kullanıyoruz.
52
- REPO_ID_LOGS = "SamiKoen/BF-logs"
53
- create_repo(REPO_ID_LOGS, token=hfapi, repo_type="model", exist_ok=True)
54
-
55
- def upload_logs_to_hf(repo_id: str, hf_token: str, local_log_file: str = "chat_logs.txt", repo_type: str = "model"):
56
- """
57
- Log dosyasını HF Hub'daki ayrı bir repository'ye yükler.
58
-
59
- Args:
60
- repo_id (str): Log repository tam id'si (örn. "SamiKoen/BF-logs").
61
- hf_token (str): HF API token'ınız.
62
- local_log_file (str): Yüklenecek log dosyasının yolu.
63
- repo_type (str): Repository tipi ("model" kullanıyoruz).
64
- """
65
- api = HfApi(token=hf_token)
66
- try:
67
- api.upload_file(
68
- path_or_fileobj=local_log_file,
69
- path_in_repo=local_log_file,
70
- repo_id=repo_id,
71
- repo_type=repo_type,
72
- commit_message="Log dosyası güncellendi"
73
- )
74
- print(f"Log dosyası başarıyla yüklendi: {local_log_file}")
75
- except Exception as e:
76
- print(f"Log dosyası yüklenirken hata oluştu: {e}")
77
 
78
  def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=None, history=None):
79
- """
80
- Her Enter tuşuna basıldığında çalışır.
81
- Kullanıcı mesajı dosyaya yazılır, bot yanıtı streaming sırasında log dosyasına eklenir.
82
- Streaming tamamlandıktan sonra log dosyası HF Hub'daki log deposuna yüklenir.
83
- """
84
  if chatbot is None:
85
  chatbot = []
86
  if history is None:
@@ -93,7 +62,7 @@ def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=None,
93
  print(f"System message: {system_msg}")
94
 
95
  multi_turn_message = [
96
- {"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 varsa, o bilgiyi vermeyeceksin. ... (uzun metin)"}
97
  ]
98
 
99
  messages = multi_turn_message.copy()
@@ -124,7 +93,7 @@ def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=None,
124
  history.append(inputs)
125
  print(f"Logging: Payload is - {payload}")
126
 
127
- # Kullanıcı mesajını log dosyasına yaz
128
  try:
129
  with open(LOG_FILE, 'a', encoding='utf-8') as f:
130
  f.write(f"User: {inputs}\n")
@@ -132,6 +101,7 @@ def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=None,
132
  except Exception as e:
133
  print(f"Dosya yazma hatası (Kullanıcı): {e}")
134
 
 
135
  chatbot.append({"role": "user", "content": inputs})
136
  response = requests.post(API_URL, headers=headers, json=payload, stream=True)
137
  print(f"Logging: Response code - {response.status_code}")
@@ -141,7 +111,6 @@ def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=None,
141
 
142
  partial_words = ""
143
  counter = 0
144
- # Streaming döngüsü
145
  for chunk in response.iter_lines():
146
  counter += 1
147
  if not chunk:
@@ -176,18 +145,57 @@ def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=None,
176
  elif partial_words and chat and chat[-1]["role"] == "assistant":
177
  chat[-1] = {"role": "assistant", "content": partial_words}
178
  yield chat, history, chat_counter
 
 
179
 
180
- print("Streaming tamamlandı, log dosyası yüklenecek.")
181
- upload_logs_to_hf(REPO_ID_LOGS, hfapi, local_log_file=LOG_FILE, repo_type="model")
182
- print("Log upload tamamlandı.")
183
- yield chatbot, history, chat_counter
 
 
 
 
 
 
 
 
184
 
185
  def reset_textbox():
186
  return gr.update(value='')
187
 
188
- # Gradio arayüzü için CSS ve tema ayarları
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
189
  demo_css = """
190
- #send_button {
191
  background-color: #0b93f6;
192
  border: none;
193
  color: white;
@@ -202,6 +210,9 @@ demo_css = """
202
  transition: background-color 0.3s;
203
  margin: 5px;
204
  }
 
 
 
205
  .fixed_button_container {
206
  padding: 0px;
207
  margin: 0px 0 0 0px;
@@ -248,18 +259,20 @@ with gr.Blocks(css=demo_css, theme=theme) as demo:
248
  )
249
  with gr.Column(elem_classes="fixed_button_container"):
250
  send_button = gr.Button(value="Gönder", elem_id="send_button")
 
251
 
252
  state = gr.State([])
 
253
 
254
  with gr.Accordion("", open=False, visible=False):
255
  top_p = gr.Slider(minimum=0, maximum=1.0, value=0.5, step=0.05, interactive=False, visible=False)
256
  temperature = gr.Slider(minimum=0, maximum=5.0, value=0.1, step=0.1, interactive=False, visible=False)
257
  chat_counter = gr.Number(value=0, visible=False, precision=0)
258
 
259
- # Hem Enter hem de Gönder butonuna basıldığında predict çalışıyor.
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
 
265
  demo.queue(max_size=10).launch(debug=True)
 
41
  item_info = (stockAmount, price)
42
  products.append((name, item_info, full_name))
43
 
44
+ # HF_TOKEN yerine "hfapi" ortam değişkenini alıyoruz
45
  hfapi = os.getenv("hfapi")
46
  if not hfapi:
47
  raise ValueError("hfapi ortam değişkeni ayarlanmamış!")
48
 
49
+ # Repository oluşturma (repo adı "BF" kullanıcı adınızla uyumlu olmalı; space_sdk eklenmiş)
50
  create_repo("BF", token=hfapi, repo_type="space", space_sdk="gradio", exist_ok=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
 
52
  def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=None, history=None):
 
 
 
 
 
53
  if chatbot is None:
54
  chatbot = []
55
  if history is None:
 
62
  print(f"System message: {system_msg}")
63
 
64
  multi_turn_message = [
65
+ {"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)"}
66
  ]
67
 
68
  messages = multi_turn_message.copy()
 
93
  history.append(inputs)
94
  print(f"Logging: Payload is - {payload}")
95
 
96
+ # Kullanıcı mesajını dosyaya yaz
97
  try:
98
  with open(LOG_FILE, 'a', encoding='utf-8') as f:
99
  f.write(f"User: {inputs}\n")
 
101
  except Exception as e:
102
  print(f"Dosya yazma hatası (Kullanıcı): {e}")
103
 
104
+ # Chatbot'a kullanıcı mesajını ekle
105
  chatbot.append({"role": "user", "content": inputs})
106
  response = requests.post(API_URL, headers=headers, json=payload, stream=True)
107
  print(f"Logging: Response code - {response.status_code}")
 
111
 
112
  partial_words = ""
113
  counter = 0
 
114
  for chunk in response.iter_lines():
115
  counter += 1
116
  if not chunk:
 
145
  elif partial_words and chat and chat[-1]["role"] == "assistant":
146
  chat[-1] = {"role": "assistant", "content": partial_words}
147
  yield chat, history, chat_counter
148
+ print(f"Son chatbot durumu: {chatbot}")
149
+ return chatbot, history, chat_counter
150
 
151
+ def save_chat(chatbot):
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
+ print(f"Sohbet dosyaya kaydedildi: {file_path}")
159
+ return f"Sohbet başarıyla kaydedildi!\nDosya: {file_path}"
160
+ except Exception as e:
161
+ print(f"Kayıt hatası: {e}")
162
+ return f"Kayıt hatası: {e}\nDosya: {file_path}"
163
 
164
  def reset_textbox():
165
  return gr.update(value='')
166
 
167
+ def upload_logs_to_hf(repo_id: str, hf_token: str, local_log_file: str = "chat_logs.txt"):
168
+ """
169
+ Log dosyasını Hugging Face Hub repository'sine yükler.
170
+
171
+ Args:
172
+ repo_id (str): Repository kimliği (örn. "SamiKoen/BF").
173
+ hf_token (str): Hugging Face API token'ınız.
174
+ local_log_file (str): Yüklenecek log dosyasının yolu.
175
+ """
176
+ api = HfApi(token=hf_token)
177
+ try:
178
+ api.upload_file(
179
+ path_or_fileobj=local_log_file,
180
+ path_in_repo=local_log_file,
181
+ repo_id=repo_id,
182
+ repo_type="space",
183
+ commit_message="Log dosyası güncellendi"
184
+ )
185
+ print(f"Log dosyası başarıyla yüklendi: {local_log_file}")
186
+ except Exception as e:
187
+ print(f"Log dosyası yüklenirken hata oluştu: {e}")
188
+
189
+ def save_chat_and_upload(chatbot):
190
+ save_status = save_chat(chatbot)
191
+ HF_REPO_ID = "SamiKoen/BF" # Kendi repo kimliğinizi girin.
192
+ hfapi = os.getenv("hfapi")
193
+ upload_logs_to_hf(HF_REPO_ID, hfapi)
194
+ return save_status
195
+
196
+ # Gradio arayüzü
197
  demo_css = """
198
+ #send_button, #save_button {
199
  background-color: #0b93f6;
200
  border: none;
201
  color: white;
 
210
  transition: background-color 0.3s;
211
  margin: 5px;
212
  }
213
+ #send_button:hover, #save_button:hover {
214
+ background-color: #0077c0;
215
+ }
216
  .fixed_button_container {
217
  padding: 0px;
218
  margin: 0px 0 0 0px;
 
259
  )
260
  with gr.Column(elem_classes="fixed_button_container"):
261
  send_button = gr.Button(value="Gönder", elem_id="send_button")
262
+ save_button = gr.Button(value="Kayıt Et", elem_id="save_button")
263
 
264
  state = gr.State([])
265
+ save_status = gr.Textbox(label="Kayıt Durumu", interactive=False)
266
 
267
  with gr.Accordion("", open=False, visible=False):
268
  top_p = gr.Slider(minimum=0, maximum=1.0, value=0.5, step=0.05, interactive=False, visible=False)
269
  temperature = gr.Slider(minimum=0, maximum=5.0, value=0.1, step=0.1, interactive=False, visible=False)
270
  chat_counter = gr.Number(value=0, visible=False, precision=0)
271
 
 
272
  inputs.submit(predict, [system_msg, inputs, top_p, temperature, chat_counter, chatbot, state], [chatbot, state, chat_counter])
273
  inputs.submit(reset_textbox, [], [inputs])
274
  send_button.click(predict, [system_msg, inputs, top_p, temperature, chat_counter, chatbot, state], [chatbot, state, chat_counter])
275
  send_button.click(reset_textbox, [], [inputs])
276
+ save_button.click(save_chat_and_upload, [chatbot], [save_status])
277
 
278
  demo.queue(max_size=10).launch(debug=True)