SamiKoen commited on
Commit
301ce8c
·
verified ·
1 Parent(s): 2e01090

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +98 -95
app.py CHANGED
@@ -48,7 +48,7 @@ if not hfapi:
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; repo id'yi tam olarak belirtelim:
52
  REPO_ID_LOGS = "SamiKoen/BF-logs"
53
  create_repo(REPO_ID_LOGS, token=hfapi, repo_type="model", exist_ok=True)
54
 
@@ -78,107 +78,110 @@ def upload_logs_to_hf(repo_id: str, hf_token: str, local_log_file: str = "chat_l
78
  def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=None, history=None):
79
  """
80
  Her Enter'a basıldığında çalışır. Kullanıcı mesajı dosyaya yazılır,
81
- bot yanıtı tamamlandığında log dosyasına eklenir ve ardından log dosyası
82
- HF Hub'daki log deposuna yüklenir.
83
  """
84
  if chatbot is None:
85
  chatbot = []
86
  if history is None:
87
  history = []
88
 
89
- headers = {
90
- "Content-Type": "application/json",
91
- "Authorization": f"Bearer {OPENAI_API_KEY}"
92
- }
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()
100
- input_words = [str(word).lower() for word in inputs.split()]
101
- for product_info in products:
102
- if product_info[0] in input_words:
103
- new_msg = f"{product_info[2]} {product_info[1][0]} ve fiyatı EURO {product_info[1][1]}"
104
- print(new_msg)
105
- messages.append({"role": "system", "content": new_msg})
106
-
107
- for data in chatbot:
108
- messages.append({"role": data["role"], "content": data["content"]})
109
-
110
- messages.append({"role": "user", "content": inputs})
111
-
112
- payload = {
113
- "model": "gpt-4o",
114
- "messages": messages,
115
- "temperature": 0.7,
116
- "top_p": 0.9,
117
- "n": 1,
118
- "stream": True,
119
- "presence_penalty": 0,
120
- "frequency_penalty": 0,
121
- }
122
-
123
- chat_counter += 1
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")
131
- print(f"Kullanıcı mesajı dosyaya yazıldı: {inputs}")
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}")
138
- if response.status_code != 200:
139
- print(f"API hatası: {response.text}")
140
- return chatbot, history, chat_counter
141
-
142
- partial_words = ""
143
- counter = 0
144
- for chunk in response.iter_lines():
145
- counter += 1
146
- if not chunk:
147
- continue
148
- chunk_str = chunk.decode('utf-8')
149
- print(f"Chunk {counter}: {chunk_str}")
150
- if chunk_str.startswith("data: ") and chunk_str != "data: [DONE]":
151
- try:
152
- chunk_data = json.loads(chunk_str[6:])
153
- delta = chunk_data['choices'][0]['delta']
154
- if 'content' in delta and delta['content']:
155
- content = delta['content']
156
- partial_words += content
157
- print(f"İçerik eklendi: {content}")
158
- print(f"Güncel partial_words: {partial_words}")
159
- except json.JSONDecodeError as e:
160
- print(f"JSON parse hatası: {e} - Chunk: {chunk_str}")
161
- elif chunk_str == "data: [DONE]":
162
- print("Akış tamamlandı: [DONE] alındı")
163
- if partial_words:
164
- history.append(partial_words)
165
- chatbot.append({"role": "assistant", "content": partial_words})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
  try:
167
- with open(LOG_FILE, 'a', encoding='utf-8') as f:
168
- f.write(f"Bot: {partial_words}\n")
169
- print(f"Bot yanıtı dosyaya yazıldı: {partial_words}")
170
- except Exception as e:
171
- print(f"Dosya yazma hatası (Bot): {e}")
172
- chat = chatbot.copy()
173
- if partial_words and chat and chat[-1]["role"] == "user":
174
- chat.append({"role": "assistant", "content": partial_words})
175
- elif partial_words and chat and chat[-1]["role"] == "assistant":
176
- chat[-1] = {"role": "assistant", "content": partial_words}
177
- yield chat, history, chat_counter
178
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
179
  print(f"Son chatbot durumu: {chatbot}")
180
- # Streaming tamamlandıktan sonra log dosyasını ayrı log deposuna yükle (Space'i etkilemeden)
181
- upload_logs_to_hf(REPO_ID_LOGS, hfapi, local_log_file=LOG_FILE, repo_type="model")
182
  return chatbot, history, chat_counter
183
 
184
  def reset_textbox():
@@ -256,9 +259,9 @@ with gr.Blocks(css=demo_css, theme=theme) as demo:
256
  chat_counter = gr.Number(value=0, visible=False, precision=0)
257
 
258
  # Hem Enter hem de Gönder butonuna basıldığında predict çalışıyor.
259
- inputs.submit(predict, [system_msg, inputs, top_p, temperature, chat_counter, chatbot, gr.State([])], [chatbot, gr.State([]), chat_counter])
260
  inputs.submit(reset_textbox, [], [inputs])
261
- send_button.click(predict, [system_msg, inputs, top_p, temperature, chat_counter, chatbot, gr.State([])], [chatbot, gr.State([]), chat_counter])
262
  send_button.click(reset_textbox, [], [inputs])
263
 
264
  demo.queue(max_size=10).launch(debug=True)
 
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; repo id'sini tam kullanıcı adı ile belirtelim.
52
  REPO_ID_LOGS = "SamiKoen/BF-logs"
53
  create_repo(REPO_ID_LOGS, token=hfapi, repo_type="model", exist_ok=True)
54
 
 
78
  def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=None, history=None):
79
  """
80
  Her Enter'a basıldığında çalışır. Kullanıcı mesajı dosyaya yazılır,
81
+ bot yanıtı tamamlandığında log dosyasına eklenir ve predict fonksiyonunun
82
+ sonlanması sırasında log dosyası HF Hub'daki log deposuna yüklenir.
83
  """
84
  if chatbot is None:
85
  chatbot = []
86
  if history is None:
87
  history = []
88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  try:
90
+ headers = {
91
+ "Content-Type": "application/json",
92
+ "Authorization": f"Bearer {OPENAI_API_KEY}"
93
+ }
94
+ print(f"System message: {system_msg}")
95
+
96
+ multi_turn_message = [
97
+ {"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)"}
98
+ ]
99
+
100
+ messages = multi_turn_message.copy()
101
+ input_words = [str(word).lower() for word in inputs.split()]
102
+ for product_info in products:
103
+ if product_info[0] in input_words:
104
+ new_msg = f"{product_info[2]} {product_info[1][0]} ve fiyatı EURO {product_info[1][1]}"
105
+ print(new_msg)
106
+ messages.append({"role": "system", "content": new_msg})
107
+
108
+ for data in chatbot:
109
+ messages.append({"role": data["role"], "content": data["content"]})
110
+
111
+ messages.append({"role": "user", "content": inputs})
112
+
113
+ payload = {
114
+ "model": "gpt-4o",
115
+ "messages": messages,
116
+ "temperature": 0.7,
117
+ "top_p": 0.9,
118
+ "n": 1,
119
+ "stream": True,
120
+ "presence_penalty": 0,
121
+ "frequency_penalty": 0,
122
+ }
123
+
124
+ chat_counter += 1
125
+ history.append(inputs)
126
+ print(f"Logging: Payload is - {payload}")
127
+
128
+ # Kullanıcı mesajını log dosyasına yaz
129
+ try:
130
+ with open(LOG_FILE, 'a', encoding='utf-8') as f:
131
+ f.write(f"User: {inputs}\n")
132
+ print(f"Kullanıcı mesajı dosyaya yazıldı: {inputs}")
133
+ except Exception as e:
134
+ print(f"Dosya yazma hatası (Kullanıcı): {e}")
135
+
136
+ chatbot.append({"role": "user", "content": inputs})
137
+ response = requests.post(API_URL, headers=headers, json=payload, stream=True)
138
+ print(f"Logging: Response code - {response.status_code}")
139
+ if response.status_code != 200:
140
+ print(f"API hatası: {response.text}")
141
+ return chatbot, history, chat_counter
142
+
143
+ partial_words = ""
144
+ counter = 0
145
+ for chunk in response.iter_lines():
146
+ counter += 1
147
+ if not chunk:
148
+ continue
149
+ chunk_str = chunk.decode('utf-8')
150
+ print(f"Chunk {counter}: {chunk_str}")
151
+ if chunk_str.startswith("data: ") and chunk_str != "data: [DONE]":
152
  try:
153
+ chunk_data = json.loads(chunk_str[6:])
154
+ delta = chunk_data['choices'][0]['delta']
155
+ if 'content' in delta and delta['content']:
156
+ content = delta['content']
157
+ partial_words += content
158
+ print(f"İçerik eklendi: {content}")
159
+ print(f"Güncel partial_words: {partial_words}")
160
+ except json.JSONDecodeError as e:
161
+ print(f"JSON parse hatası: {e} - Chunk: {chunk_str}")
162
+ elif chunk_str == "data: [DONE]":
163
+ print("Akış tamamlandı: [DONE] alındı")
164
+ if partial_words:
165
+ history.append(partial_words)
166
+ chatbot.append({"role": "assistant", "content": partial_words})
167
+ try:
168
+ with open(LOG_FILE, 'a', encoding='utf-8') as f:
169
+ f.write(f"Bot: {partial_words}\n")
170
+ print(f"Bot yanıtı dosyaya yazıldı: {partial_words}")
171
+ except Exception as e:
172
+ print(f"Dosya yazma hatası (Bot): {e}")
173
+ chat = chatbot.copy()
174
+ if partial_words and chat and chat[-1]["role"] == "user":
175
+ chat.append({"role": "assistant", "content": partial_words})
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
+ finally:
180
+ # Predict fonksiyonu kapatıldığında (streaming tamamlandığında veya iptal olduğunda) log dosyasını HF Hub'a yükle.
181
+ print("Predict fonksiyonu sonlanıyor, log dosyası yüklenecek.")
182
+ upload_logs_to_hf(REPO_ID_LOGS, hfapi, local_log_file=LOG_FILE, repo_type="model")
183
+
184
  print(f"Son chatbot durumu: {chatbot}")
 
 
185
  return chatbot, history, chat_counter
186
 
187
  def reset_textbox():
 
259
  chat_counter = gr.Number(value=0, visible=False, precision=0)
260
 
261
  # Hem Enter hem de Gönder butonuna basıldığında predict çalışıyor.
262
+ inputs.submit(predict, [system_msg, inputs, top_p, temperature, chat_counter, chatbot, state], [chatbot, state, chat_counter])
263
  inputs.submit(reset_textbox, [], [inputs])
264
+ send_button.click(predict, [system_msg, inputs, top_p, temperature, chat_counter, chatbot, state], [chatbot, state, chat_counter])
265
  send_button.click(reset_textbox, [], [inputs])
266
 
267
  demo.queue(max_size=10).launch(debug=True)