SamiKoen commited on
Commit
5e7c2bd
·
verified ·
1 Parent(s): 6328941

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +18 -51
app.py CHANGED
@@ -7,17 +7,10 @@ from huggingface_hub import HfApi, create_repo
7
  import schedule
8
  import time
9
  import threading
10
- from urllib.parse import parse_qs
11
 
12
- # Log dosyası ve sohbet geçmişi dizini
13
  LOG_FILE = '/data/chat_logs.txt' if os.path.exists('/data') else 'chat_logs.txt'
14
- CHAT_HISTORY_DIR = '/data/chat_histories' if os.path.exists('/data') else 'chat_histories'
15
  print(f"Dosya yolu: {os.path.abspath(LOG_FILE)}")
16
- print(f"Sohbet geçmişi dizini: {os.path.abspath(CHAT_HISTORY_DIR)}")
17
-
18
- # Chat history dizinini oluştur
19
- if not os.path.exists(CHAT_HISTORY_DIR):
20
- os.makedirs(CHAT_HISTORY_DIR)
21
 
22
  # API ayarları
23
  API_URL = "https://api.openai.com/v1/chat/completions"
@@ -51,7 +44,7 @@ create_repo("BF", token=hfapi, repo_type="space", space_sdk="gradio", exist_ok=T
51
  def save_chat(chatbot):
52
  file_path = os.path.abspath(LOG_FILE)
53
  try:
54
- with open(file_path, 'a', encoding='utf-8') as f:
55
  f.write("\n--- Zamanlanmış Kayıt: {} ---\n".format(time.strftime("%Y-%m-%d %H:%M:%S")))
56
  for msg in chatbot:
57
  f.write(f"{msg['role'].capitalize()}: {msg['content']}\n")
@@ -97,33 +90,11 @@ def run_scheduler(chatbot_ref):
97
  print(f"Zamanlayıcı çalışıyor, bekliyor: {time.strftime('%H:%M:%S')}")
98
  time.sleep(60)
99
 
100
- def load_chat_history(session_id):
101
- """Belirli bir oturum kimliğine ait sohbet geçmişini yükler."""
102
- history_file = os.path.join(CHAT_HISTORY_DIR, f"{session_id}.json")
103
- if os.path.exists(history_file):
104
- try:
105
- with open(history_file, 'r', encoding='utf-8') as f:
106
- chat_history = json.load(f)
107
- return chat_history
108
- except Exception as e:
109
- print(f"Sohbet geçmişi yükleme hatası (session {session_id}): {e}")
110
- return []
111
-
112
- def save_chat_history(session_id, chatbot):
113
- """Belirli bir oturum kimliğine ait sohbet geçmişini kaydeder."""
114
- history_file = os.path.join(CHAT_HISTORY_DIR, f"{session_id}.json")
115
- try:
116
- with open(history_file, 'w', encoding='utf-8') as f:
117
- json.dump(chatbot, f, ensure_ascii=False)
118
- print(f"Sohbet geçmişi kaydedildi: {history_file}")
119
- except Exception as e:
120
- print(f"Sohbet geçmişi kaydetme hatası (session {session_id}): {e}")
121
-
122
- def predict(session_id, system_msg, inputs, top_p, temperature, chat_counter, chatbot=None, history=None):
123
  if chatbot is None:
124
- chatbot = load_chat_history(session_id) # Oturum kimliğine göre geçmişi yükle
125
  if history is None:
126
- history = [msg["content"] for msg in chatbot if msg["role"] == "user"] # Kullanıcı mesajlarını history'ye ekle
127
 
128
  headers = {
129
  "Content-Type": "application/json",
@@ -183,11 +154,15 @@ def predict(session_id, system_msg, inputs, top_p, temperature, chat_counter, ch
183
  except Exception as e:
184
  print(f"Dosya yazma hatası (Kullanıcı): {e}")
185
 
 
186
  chatbot.append({"role": "user", "content": inputs})
 
 
187
  response = requests.post(API_URL, headers=headers, json=payload, stream=True)
188
 
189
  if response.status_code != 200:
190
  print(f"API hatası: {response.text}")
 
191
  yield chatbot, history, chat_counter
192
 
193
  partial_response = ""
@@ -201,12 +176,13 @@ def predict(session_id, system_msg, inputs, top_p, temperature, chat_counter, ch
201
  delta = chunk_data['choices'][0]['delta']
202
  if 'content' in delta and delta['content']:
203
  partial_response += delta['content']
204
- updated_chatbot = chatbot[:-1] + [{"role": "user", "content": inputs}, {"role": "assistant", "content": partial_response}]
205
- save_chat_history(session_id, updated_chatbot)
206
- yield updated_chatbot, history, chat_counter
207
  except json.JSONDecodeError as e:
208
  print(f"JSON parse hatası: {e} - Chunk: {chunk_str}")
209
  elif chunk_str == "data: [DONE]":
 
210
  chatbot[-1] = {"role": "assistant", "content": partial_response}
211
  try:
212
  with open(LOG_FILE, 'a', encoding='utf-8') as f:
@@ -214,7 +190,6 @@ def predict(session_id, system_msg, inputs, top_p, temperature, chat_counter, ch
214
  print(f"Bot yanıtı dosyaya yazıldı: {partial_response}")
215
  except Exception as e:
216
  print(f"Dosya yazma hatası (Bot): {e}")
217
- save_chat_history(session_id, chatbot)
218
  break
219
 
220
  yield chatbot, history, chat_counter
@@ -242,7 +217,7 @@ demo_css = """
242
  background-color: #0077c0;
243
  }
244
  .fixed_button_container {
245
- margin-top: -6px;
246
  padding: 0px;
247
  margin-left: 0px;
248
  margin-right: 0px;
@@ -269,20 +244,11 @@ theme = gr.themes.Base(
269
  spacing_size="sm",
270
  )
271
 
272
- def get_session_id():
273
- """URL parametresinden session_id’yi al, yoksa None döner."""
274
- query = os.environ.get('QUERY_STRING', '')
275
- params = parse_qs(query)
276
- session_id = params.get('session_id', [None])[0]
277
- return session_id
278
-
279
  with gr.Blocks(css=demo_css, theme=theme) as demo:
280
  if not os.path.exists(LOG_FILE):
281
  with open(LOG_FILE, 'w', encoding='utf-8') as f:
282
  f.write("--- Yeni Sohbet ---\n")
283
 
284
- session_id = gr.State(value=get_session_id) # Oturum kimliğini URL’den al
285
-
286
  with gr.Column(elem_id="col_container"):
287
  with gr.Accordion("", open=False, visible=False):
288
  system_msg = gr.Textbox(value="")
@@ -301,6 +267,7 @@ with gr.Blocks(css=demo_css, theme=theme) as demo:
301
  send_button = gr.Button(value="✈", elem_id="send_button")
302
 
303
  state = gr.State([])
 
304
  with gr.Accordion("", open=False, visible=False):
305
  top_p = gr.Slider(minimum=0, maximum=1.0, value=0.5, step=0.05, interactive=False, visible=False)
306
  temperature = gr.Slider(minimum=0, maximum=5.0, value=0.1, step=0.1, interactive=False, visible=False)
@@ -311,10 +278,10 @@ with gr.Blocks(css=demo_css, theme=theme) as demo:
311
  chatbot_ref[:] = chat
312
  return chat
313
 
314
- inputs.submit(predict, [session_id, system_msg, inputs, top_p, temperature, chat_counter, chatbot, state], [chatbot, state, chat_counter]).then(update_chatbot_ref, chatbot, chatbot).then(reset_textbox, [], [inputs])
315
- send_button.click(predict, [session_id, system_msg, inputs, top_p, temperature, chat_counter, chatbot, state], [chatbot, state, chat_counter]).then(update_chatbot_ref, chatbot, chatbot).then(reset_textbox, [], [inputs])
316
 
317
  scheduler_thread = threading.Thread(target=run_scheduler, args=(chatbot_ref,), daemon=True)
318
  scheduler_thread.start()
319
 
320
- demo.launch(server_name="0.0.0.0", server_port=7860, debug=True)
 
7
  import schedule
8
  import time
9
  import threading
 
10
 
11
+ # Log dosyası adı ve yolu
12
  LOG_FILE = '/data/chat_logs.txt' if os.path.exists('/data') else 'chat_logs.txt'
 
13
  print(f"Dosya yolu: {os.path.abspath(LOG_FILE)}")
 
 
 
 
 
14
 
15
  # API ayarları
16
  API_URL = "https://api.openai.com/v1/chat/completions"
 
44
  def save_chat(chatbot):
45
  file_path = os.path.abspath(LOG_FILE)
46
  try:
47
+ with open(LOG_FILE, 'a', encoding='utf-8') as f:
48
  f.write("\n--- Zamanlanmış Kayıt: {} ---\n".format(time.strftime("%Y-%m-%d %H:%M:%S")))
49
  for msg in chatbot:
50
  f.write(f"{msg['role'].capitalize()}: {msg['content']}\n")
 
90
  print(f"Zamanlayıcı çalışıyor, bekliyor: {time.strftime('%H:%M:%S')}")
91
  time.sleep(60)
92
 
93
+ def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=None, history=None):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
  if chatbot is None:
95
+ chatbot = []
96
  if history is None:
97
+ history = []
98
 
99
  headers = {
100
  "Content-Type": "application/json",
 
154
  except Exception as e:
155
  print(f"Dosya yazma hatası (Kullanıcı): {e}")
156
 
157
+ # Kullanıcı mesajını ekledikten sonra, ayrı bir assistant mesajı için yer açıyoruz
158
  chatbot.append({"role": "user", "content": inputs})
159
+ chatbot.append({"role": "assistant", "content": ""}) # Boş bir assistant mesajı ekliyoruz
160
+
161
  response = requests.post(API_URL, headers=headers, json=payload, stream=True)
162
 
163
  if response.status_code != 200:
164
  print(f"API hatası: {response.text}")
165
+ chatbot.pop() # Hata olursa boş assistant mesajını kaldır
166
  yield chatbot, history, chat_counter
167
 
168
  partial_response = ""
 
176
  delta = chunk_data['choices'][0]['delta']
177
  if 'content' in delta and delta['content']:
178
  partial_response += delta['content']
179
+ # Son assistant mesajını güncelle, önceki mesajları koru
180
+ chatbot[-1] = {"role": "assistant", "content": partial_response}
181
+ yield chatbot, history, chat_counter
182
  except json.JSONDecodeError as e:
183
  print(f"JSON parse hatası: {e} - Chunk: {chunk_str}")
184
  elif chunk_str == "data: [DONE]":
185
+ # Akış bittiğinde son haliyle assistant mesajını güncelle
186
  chatbot[-1] = {"role": "assistant", "content": partial_response}
187
  try:
188
  with open(LOG_FILE, 'a', encoding='utf-8') as f:
 
190
  print(f"Bot yanıtı dosyaya yazıldı: {partial_response}")
191
  except Exception as e:
192
  print(f"Dosya yazma hatası (Bot): {e}")
 
193
  break
194
 
195
  yield chatbot, history, chat_counter
 
217
  background-color: #0077c0;
218
  }
219
  .fixed_button_container {
220
+ margin-top: -6px; /* Butonu 6 piksel yukarı kaydırır */
221
  padding: 0px;
222
  margin-left: 0px;
223
  margin-right: 0px;
 
244
  spacing_size="sm",
245
  )
246
 
 
 
 
 
 
 
 
247
  with gr.Blocks(css=demo_css, theme=theme) as demo:
248
  if not os.path.exists(LOG_FILE):
249
  with open(LOG_FILE, 'w', encoding='utf-8') as f:
250
  f.write("--- Yeni Sohbet ---\n")
251
 
 
 
252
  with gr.Column(elem_id="col_container"):
253
  with gr.Accordion("", open=False, visible=False):
254
  system_msg = gr.Textbox(value="")
 
267
  send_button = gr.Button(value="✈", elem_id="send_button")
268
 
269
  state = gr.State([])
270
+
271
  with gr.Accordion("", open=False, visible=False):
272
  top_p = gr.Slider(minimum=0, maximum=1.0, value=0.5, step=0.05, interactive=False, visible=False)
273
  temperature = gr.Slider(minimum=0, maximum=5.0, value=0.1, step=0.1, interactive=False, visible=False)
 
278
  chatbot_ref[:] = chat
279
  return chat
280
 
281
+ 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])
282
+ 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])
283
 
284
  scheduler_thread = threading.Thread(target=run_scheduler, args=(chatbot_ref,), daemon=True)
285
  scheduler_thread.start()
286
 
287
+ demo.launch(debug=True)