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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -24
app.py CHANGED
@@ -7,10 +7,17 @@ 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 = '/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,7 +51,7 @@ create_repo("BF", token=hfapi, repo_type="space", space_sdk="gradio", exist_ok=T
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,11 +97,33 @@ def run_scheduler(chatbot_ref):
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",
@@ -159,9 +188,9 @@ def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=None,
159
 
160
  if response.status_code != 200:
161
  print(f"API hatası: {response.text}")
162
- return chatbot, history, chat_counter
163
 
164
- assistant_response = ""
165
  for chunk in response.iter_lines():
166
  if not chunk:
167
  continue
@@ -171,23 +200,24 @@ def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=None,
171
  chunk_data = json.loads(chunk_str[6:])
172
  delta = chunk_data['choices'][0]['delta']
173
  if 'content' in delta and delta['content']:
174
- assistant_response += delta['content']
 
 
 
175
  except json.JSONDecodeError as e:
176
  print(f"JSON parse hatası: {e} - Chunk: {chunk_str}")
177
  elif chunk_str == "data: [DONE]":
 
 
 
 
 
 
 
 
178
  break
179
-
180
- if assistant_response:
181
- history.append(assistant_response)
182
- chatbot.append({"role": "assistant", "content": assistant_response})
183
- try:
184
- with open(LOG_FILE, 'a', encoding='utf-8') as f:
185
- f.write(f"Bot: {assistant_response}\n")
186
- print(f"Bot yanıtı dosyaya yazıldı: {assistant_response}")
187
- except Exception as e:
188
- print(f"Dosya yazma hatası (Bot): {e}")
189
 
190
- return chatbot, history, chat_counter
191
 
192
  def reset_textbox():
193
  return gr.update(value='')
@@ -212,7 +242,7 @@ demo_css = """
212
  background-color: #0077c0;
213
  }
214
  .fixed_button_container {
215
- margin-top: -6px; /* Butonu 10 piksel yukarı kaydırır */
216
  padding: 0px;
217
  margin-left: 0px;
218
  margin-right: 0px;
@@ -239,11 +269,20 @@ theme = gr.themes.Base(
239
  spacing_size="sm",
240
  )
241
 
 
 
 
 
 
 
 
242
  with gr.Blocks(css=demo_css, theme=theme) as demo:
243
  if not os.path.exists(LOG_FILE):
244
  with open(LOG_FILE, 'w', encoding='utf-8') as f:
245
  f.write("--- Yeni Sohbet ---\n")
246
 
 
 
247
  with gr.Column(elem_id="col_container"):
248
  with gr.Accordion("", open=False, visible=False):
249
  system_msg = gr.Textbox(value="")
@@ -262,7 +301,6 @@ with gr.Blocks(css=demo_css, theme=theme) as demo:
262
  send_button = gr.Button(value="✈", elem_id="send_button")
263
 
264
  state = gr.State([])
265
-
266
  with gr.Accordion("", open=False, visible=False):
267
  top_p = gr.Slider(minimum=0, maximum=1.0, value=0.5, step=0.05, interactive=False, visible=False)
268
  temperature = gr.Slider(minimum=0, maximum=5.0, value=0.1, step=0.1, interactive=False, visible=False)
@@ -273,10 +311,10 @@ with gr.Blocks(css=demo_css, theme=theme) as demo:
273
  chatbot_ref[:] = chat
274
  return chat
275
 
276
- 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])
277
- 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])
278
 
279
  scheduler_thread = threading.Thread(target=run_scheduler, args=(chatbot_ref,), daemon=True)
280
  scheduler_thread.start()
281
 
282
- demo.launch(debug=True) # HF Spaces için share=True kaldırıldı
 
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
  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
  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",
 
188
 
189
  if response.status_code != 200:
190
  print(f"API hatası: {response.text}")
191
+ yield chatbot, history, chat_counter
192
 
193
+ partial_response = ""
194
  for chunk in response.iter_lines():
195
  if not chunk:
196
  continue
 
200
  chunk_data = json.loads(chunk_str[6:])
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:
213
+ f.write(f"Bot: {partial_response}\n")
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
221
 
222
  def reset_textbox():
223
  return gr.update(value='')
 
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
  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
  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
  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)