SamiKoen commited on
Commit
42c9a95
·
verified ·
1 Parent(s): 5942ddb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -57
app.py CHANGED
@@ -41,59 +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ı; repo oluşturuluyor.
45
  hfapi = os.getenv("hfapi")
46
  if not hfapi:
47
  raise ValueError("hfapi ortam değişkeni ayarlanmamış!")
48
- # Kod deposu (Space) için repo oluşturuluyor.
49
- create_repo("BF", token=hfapi, repo_type="space", space_sdk="gradio", exist_ok=True)
50
- # Loglar için ayrı bir repo (commitler log dosyasını güncelleyecek ancak bu, Space’i yeniden başlatmayacak)
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ı Hugging Face Hub üzerindeki ayrı bir repository'ye yükler.
56
-
57
- Args:
58
- repo_id (str): Log repository kimliği (örn. "BF-logs" -> Hub'da "KullaniciAdiniz/BF-logs").
59
- hf_token (str): Hugging Face API token'ınız.
60
- local_log_file (str): Yüklenecek log dosyasının yolu.
61
- repo_type (str): Repository tipi ("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 save_chat(chatbot):
77
- file_path = os.path.abspath(LOG_FILE)
78
- try:
79
- with open(LOG_FILE, 'a', encoding='utf-8') as f:
80
- f.write("\n--- Kayıt Edilen Sohbet ---\n")
81
- for msg in chatbot:
82
- f.write(f"{msg['role'].capitalize()}: {msg['content']}\n")
83
- print(f"Sohbet dosyaya kaydedildi: {file_path}")
84
- return f"Sohbet başarıyla kaydedildi!\nDosya: {file_path}"
85
- except Exception as e:
86
- print(f"Kayıt hatası: {e}")
87
- return f"Kayıt hatası: {e}\nDosya: {file_path}"
88
-
89
- def reset_textbox():
90
- return gr.update(value='')
91
 
92
  def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=None, history=None):
93
- """
94
- Her Enter'a basıldığında çalışır. Kullanıcı mesajı log dosyasına yazılır,
95
- bot yanıtı tamamlandığında log dosyasına eklenir ve ardından loglar HF Hub'daki log repo'suna yüklenir.
96
- """
97
  if chatbot is None:
98
  chatbot = []
99
  if history is None:
@@ -106,7 +62,7 @@ def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=None,
106
  print(f"System message: {system_msg}")
107
 
108
  multi_turn_message = [
109
- {"role": "system", "content": "Bir önceki sohbeti unut. Vereceğin ürün bilgisi ... (uzun metin)"}
110
  ]
111
 
112
  messages = multi_turn_message.copy()
@@ -137,7 +93,7 @@ def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=None,
137
  history.append(inputs)
138
  print(f"Logging: Payload is - {payload}")
139
 
140
- # Kullanıcı mesajını log dosyasına yaz
141
  try:
142
  with open(LOG_FILE, 'a', encoding='utf-8') as f:
143
  f.write(f"User: {inputs}\n")
@@ -145,6 +101,7 @@ def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=None,
145
  except Exception as e:
146
  print(f"Dosya yazma hatası (Kullanıcı): {e}")
147
 
 
148
  chatbot.append({"role": "user", "content": inputs})
149
  response = requests.post(API_URL, headers=headers, json=payload, stream=True)
150
  print(f"Logging: Response code - {response.status_code}")
@@ -188,15 +145,57 @@ def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=None,
188
  elif partial_words and chat and chat[-1]["role"] == "assistant":
189
  chat[-1] = {"role": "assistant", "content": partial_words}
190
  yield chat, history, chat_counter
191
-
192
  print(f"Son chatbot durumu: {chatbot}")
193
- # Tüm streaming tamamlandıktan sonra log dosyası ayrı log reposuna yüklenir.
194
- upload_logs_to_hf("BF-logs", hfapi, local_log_file=LOG_FILE, repo_type="model")
195
  return chatbot, history, chat_counter
196
 
197
- # Gradio arayüzü CSS ve tema ayarları
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
198
  demo_css = """
199
- #send_button {
200
  background-color: #0b93f6;
201
  border: none;
202
  color: white;
@@ -211,6 +210,9 @@ demo_css = """
211
  transition: background-color 0.3s;
212
  margin: 5px;
213
  }
 
 
 
214
  .fixed_button_container {
215
  padding: 0px;
216
  margin: 0px 0 0 0px;
@@ -255,20 +257,22 @@ with gr.Blocks(css=demo_css, theme=theme) as demo:
255
  show_label=False,
256
  container=False,
257
  )
258
- # Yalnızca "Gönder" butonu bulunuyor.
259
- send_button = gr.Button(value="Gönder", elem_id="send_button")
 
260
 
261
  state = gr.State([])
 
262
 
263
  with gr.Accordion("", open=False, visible=False):
264
  top_p = gr.Slider(minimum=0, maximum=1.0, value=0.5, step=0.05, interactive=False, visible=False)
265
  temperature = gr.Slider(minimum=0, maximum=5.0, value=0.1, step=0.1, interactive=False, visible=False)
266
  chat_counter = gr.Number(value=0, visible=False, precision=0)
267
 
268
- # Hem Enter hem de Gönder butonuna basıldığında predict çalışıyor.
269
  inputs.submit(predict, [system_msg, inputs, top_p, temperature, chat_counter, chatbot, state], [chatbot, state, chat_counter])
270
  inputs.submit(reset_textbox, [], [inputs])
271
  send_button.click(predict, [system_msg, inputs, top_p, temperature, chat_counter, chatbot, state], [chatbot, state, chat_counter])
272
  send_button.click(reset_textbox, [], [inputs])
 
273
 
274
  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}")
 
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;
 
257
  show_label=False,
258
  container=False,
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)