SamiKoen commited on
Commit
2d4ab02
·
verified ·
1 Parent(s): 078f67c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -55
app.py CHANGED
@@ -41,15 +41,44 @@ for item in root.findall('item'):
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,7 +91,7 @@ def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=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,7 +122,7 @@ def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=None,
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,7 +130,6 @@ def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=None,
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}")
@@ -145,57 +173,18 @@ def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=None,
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,9 +199,6 @@ demo_css = """
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,20 +245,19 @@ with gr.Blocks(css=demo_css, theme=theme) as demo:
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)
 
41
  item_info = (stockAmount, price)
42
  products.append((name, item_info, full_name))
43
 
44
+ # Ortam değişkeninde "hfapi" tanımlı; repo oluşturuluyor.
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") ve log commitleri için ayrı bir repo ("BF-logs", repo_type="model")
50
  create_repo("BF", token=hfapi, repo_type="space", space_sdk="gradio", exist_ok=True)
51
+ create_repo("BF-logs", token=hfapi, repo_type="model", exist_ok=True)
52
+
53
+ def upload_logs_to_hf(repo_id: str, hf_token: str, local_log_file: str = "chat_logs.txt", repo_type: str = "model"):
54
+ """
55
+ Log dosyasını HF Hub'daki ayrı bir repository'ye yükler.
56
+
57
+ Args:
58
+ repo_id (str): Log repository kimliği (örn. "SamiKoen/BF-logs").
59
+ hf_token (str): HF API token'ınız.
60
+ local_log_file (str): Yüklenecek log dosyasının yolu.
61
+ repo_type (str): Repository tipi. (Burada "model" kullanıyoruz.)
62
+ """
63
+ api = HfApi(token=hf_token)
64
+ try:
65
+ api.upload_file(
66
+ path_or_fileobj=local_log_file,
67
+ path_in_repo=local_log_file,
68
+ repo_id=repo_id,
69
+ repo_type=repo_type,
70
+ commit_message="Log dosyası güncellendi"
71
+ )
72
+ print(f"Log dosyası başarıyla yüklendi: {local_log_file}")
73
+ except Exception as e:
74
+ print(f"Log dosyası yüklenirken hata oluştu: {e}")
75
 
76
  def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=None, history=None):
77
+ """
78
+ Her Enter'a basıldığında çalışır;
79
+ kullanıcı mesajı log dosyasına yazılır, bot yanıtı tamamlandığında log dosyasına eklenir
80
+ ve tüm mesajlar HF Hub'daki log repo'suna yüklenir.
81
+ """
82
  if chatbot is None:
83
  chatbot = []
84
  if history is None:
 
91
  print(f"System message: {system_msg}")
92
 
93
  multi_turn_message = [
94
+ {"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)"}
95
  ]
96
 
97
  messages = multi_turn_message.copy()
 
122
  history.append(inputs)
123
  print(f"Logging: Payload is - {payload}")
124
 
125
+ # Kullanıcı mesajını log dosyasına yaz
126
  try:
127
  with open(LOG_FILE, 'a', encoding='utf-8') as f:
128
  f.write(f"User: {inputs}\n")
 
130
  except Exception as e:
131
  print(f"Dosya yazma hatası (Kullanıcı): {e}")
132
 
 
133
  chatbot.append({"role": "user", "content": inputs})
134
  response = requests.post(API_URL, headers=headers, json=payload, stream=True)
135
  print(f"Logging: Response code - {response.status_code}")
 
173
  elif partial_words and chat and chat[-1]["role"] == "assistant":
174
  chat[-1] = {"role": "assistant", "content": partial_words}
175
  yield chat, history, chat_counter
176
+
177
  print(f"Son chatbot durumu: {chatbot}")
178
+ # Tüm streaming tamamlandıktan sonra log dosyası otomatik olarak HF Hub'daki log repo'suna yüklenir.
179
+ upload_logs_to_hf("BF-logs", hfapi, local_log_file=LOG_FILE, repo_type="model")
180
  return chatbot, history, chat_counter
181
 
 
 
 
 
 
 
 
 
 
 
 
 
 
182
  def reset_textbox():
183
  return gr.update(value='')
184
 
185
+ # Gradio arayüzü için CSS ve tema ayarları
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186
  demo_css = """
187
+ #send_button {
188
  background-color: #0b93f6;
189
  border: none;
190
  color: white;
 
199
  transition: background-color 0.3s;
200
  margin: 5px;
201
  }
 
 
 
202
  .fixed_button_container {
203
  padding: 0px;
204
  margin: 0px 0 0 0px;
 
245
  )
246
  with gr.Column(elem_classes="fixed_button_container"):
247
  send_button = gr.Button(value="Gönder", elem_id="send_button")
248
+ # Kayıt Et butonu kaldırıldı.
249
 
250
  state = gr.State([])
 
251
 
252
  with gr.Accordion("", open=False, visible=False):
253
  top_p = gr.Slider(minimum=0, maximum=1.0, value=0.5, step=0.05, interactive=False, visible=False)
254
  temperature = gr.Slider(minimum=0, maximum=5.0, value=0.1, step=0.1, interactive=False, visible=False)
255
  chat_counter = gr.Number(value=0, visible=False, precision=0)
256
 
257
+ # Hem Enter hem de Gönder butonuna basıldığında predict çalışıyor.
258
  inputs.submit(predict, [system_msg, inputs, top_p, temperature, chat_counter, chatbot, state], [chatbot, state, chat_counter])
259
  inputs.submit(reset_textbox, [], [inputs])
260
  send_button.click(predict, [system_msg, inputs, top_p, temperature, chat_counter, chatbot, state], [chatbot, state, chat_counter])
261
  send_button.click(reset_textbox, [], [inputs])
 
262
 
263
  demo.queue(max_size=10).launch(debug=True)