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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +97 -99
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; 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
 
@@ -77,112 +77,110 @@ def upload_logs_to_hf(repo_id: str, hf_token: str, local_log_file: str = "chat_l
77
 
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():
188
  return gr.update(value='')
 
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; tam repo id'sini kullanıyoruz.
52
  REPO_ID_LOGS = "SamiKoen/BF-logs"
53
  create_repo(REPO_ID_LOGS, token=hfapi, repo_type="model", exist_ok=True)
54
 
 
77
 
78
  def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=None, history=None):
79
  """
80
+ Her Enter tuşuna basıldığında çalışır.
81
+ Kullanıcı mesajı dosyaya yazılır, bot yanıtı streaming sırasında log dosyasına eklenir.
82
+ Streaming tamamlandıktan sonra 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
+ 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
+ # Streaming döngüsü
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
+
180
+ print("Streaming tamamlandı, log dosyası yüklenecek.")
181
+ upload_logs_to_hf(REPO_ID_LOGS, hfapi, local_log_file=LOG_FILE, repo_type="model")
182
+ print("Log upload tamamlandı.")
183
+ yield chatbot, history, chat_counter
184
 
185
  def reset_textbox():
186
  return gr.update(value='')