openfree commited on
Commit
95ce689
β€’
1 Parent(s): 7d860cd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -65
app.py CHANGED
@@ -20,20 +20,30 @@ LLM_MODELS = {
20
  class ChatHistory:
21
  def __init__(self):
22
  self.history = []
23
- self.history_file = "/tmp/chat_history.json" # HF Spaceμ—μ„œ μ‚¬μš©ν•  μž„μ‹œ 경둜
24
  self.load_history()
25
 
26
- def add_message(self, role: str, content: str):
27
- message = {
28
- "role": role,
29
- "content": content,
30
- "timestamp": datetime.now().isoformat()
 
 
31
  }
32
- self.history.append(message)
33
  self.save_history()
34
 
35
- def get_history(self):
36
- return self.history
 
 
 
 
 
 
 
 
37
 
38
  def clear_history(self):
39
  self.history = []
@@ -135,15 +145,11 @@ def read_uploaded_file(file):
135
  except Exception as e:
136
  return f"❌ 파일 읽기 였λ₯˜: {str(e)}", "error"
137
 
138
- def format_history(history):
139
- formatted_history = []
140
- for user_msg, assistant_msg in history:
141
- formatted_history.append({"role": "user", "content": user_msg})
142
- if assistant_msg:
143
- formatted_history.append({"role": "assistant", "content": assistant_msg})
144
- return formatted_history
145
 
146
  def chat(message, history, uploaded_file, system_message="", max_tokens=4000, temperature=0.7, top_p=0.9):
 
 
 
147
  system_prefix = """μ €λŠ” μ—¬λŸ¬λΆ„μ˜ μΉœκ·Όν•˜κ³  지적인 AI μ–΄μ‹œμŠ€ν„΄νŠΈ 'GiniGEN'μž…λ‹ˆλ‹€.. λ‹€μŒκ³Ό 같은 μ›μΉ™μœΌλ‘œ μ†Œν†΅ν•˜κ² μŠ΅λ‹ˆλ‹€:
148
 
149
  1. 🀝 μΉœκ·Όν•˜κ³  곡감적인 νƒœλ„λ‘œ λŒ€ν™”
@@ -155,26 +161,23 @@ def chat(message, history, uploaded_file, system_message="", max_tokens=4000, te
155
  항상 예의 λ°”λ₯΄κ³  μΉœμ ˆν•˜κ²Œ μ‘λ‹΅ν•˜λ©°, ν•„μš”ν•œ 경우 ꡬ체적인 μ˜ˆμ‹œλ‚˜ μ„€λͺ…을 μΆ”κ°€ν•˜μ—¬
156
  이해λ₯Ό λ•κ² μŠ΅λ‹ˆλ‹€."""
157
 
158
- # μ‚¬μš©μž λ©”μ‹œμ§€ μ €μž₯
159
- chat_history.add_message("user", message)
160
-
161
- if uploaded_file:
162
- content, file_type = read_uploaded_file(uploaded_file)
163
- if file_type == "error":
164
- error_message = content
165
- chat_history.add_message("assistant", error_message)
166
- return "", [{"role": "user", "content": message},
167
- {"role": "assistant", "content": error_message}]
168
-
169
- file_summary = analyze_file_content(content, file_type)
170
-
171
- if file_type in ['parquet', 'csv']:
172
- system_message += f"\n\n파일 λ‚΄μš©:\n```markdown\n{content}\n```"
173
- else:
174
- system_message += f"\n\n파일 λ‚΄μš©:\n```\n{content}\n```"
175
 
176
- if message == "파일 뢄석을 μ‹œμž‘ν•©λ‹ˆλ‹€...":
177
- message = f"""[파일 ꡬ쑰 뢄석] {file_summary}
 
 
 
 
 
178
 
179
  λ‹€μŒ κ΄€μ μ—μ„œ 도움을 λ“œλ¦¬κ² μŠ΅λ‹ˆλ‹€:
180
  1. πŸ“‹ μ „λ°˜μ μΈ λ‚΄μš© νŒŒμ•…
@@ -183,24 +186,22 @@ def chat(message, history, uploaded_file, system_message="", max_tokens=4000, te
183
  4. ✨ κ°œμ„  μ œμ•ˆ
184
  5. πŸ’¬ μΆ”κ°€ μ§ˆλ¬Έμ΄λ‚˜ ν•„μš”ν•œ μ„€λͺ…"""
185
 
186
- messages = [{"role": "system", "content": f"{system_prefix} {system_message}"}]
187
-
188
- if history is not None:
189
- for item in history:
190
- if isinstance(item, dict):
191
- messages.append(item)
192
- elif isinstance(item, (list, tuple)) and len(item) == 2:
193
- messages.append({"role": "user", "content": item[0]})
194
- if item[1]:
195
- messages.append({"role": "assistant", "content": item[1]})
196
-
197
- messages.append({"role": "user", "content": message})
198
 
199
- try:
200
  client = get_client()
201
  partial_message = ""
202
- current_history = []
203
 
 
204
  for msg in client.chat_completion(
205
  messages,
206
  max_tokens=max_tokens,
@@ -211,29 +212,26 @@ def chat(message, history, uploaded_file, system_message="", max_tokens=4000, te
211
  token = msg.choices[0].delta.get('content', None)
212
  if token:
213
  partial_message += token
214
- current_history = [
215
- {"role": "user", "content": message},
216
- {"role": "assistant", "content": partial_message}
217
- ]
218
  yield "", current_history
 
 
 
219
 
220
- # μ™„μ„±λœ 응닡 μ €μž₯
221
- chat_history.add_message("assistant", partial_message)
222
-
223
  except Exception as e:
224
  error_msg = f"❌ 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€: {str(e)}"
225
- chat_history.add_message("assistant", error_msg)
226
- error_history = [
227
- {"role": "user", "content": message},
228
- {"role": "assistant", "content": error_msg}
229
- ]
230
- yield "", error_history
231
 
232
- with gr.Blocks(theme="Yntec/HaleyCH_Theme_Orange", title="GiniGEN πŸ€–") as demo:
233
 
 
 
 
 
234
  with gr.Row():
235
  with gr.Column(scale=2):
236
  chatbot = gr.Chatbot(
 
237
  height=600,
238
  label="λŒ€ν™”μ°½ πŸ’¬",
239
  show_label=True,
@@ -267,7 +265,6 @@ with gr.Blocks(theme="Yntec/HaleyCH_Theme_Orange", title="GiniGEN πŸ€–") as demo
267
  gr.Examples(
268
  examples=[
269
  ["μ•ˆλ…•ν•˜μ„Έμš”! μ–΄λ–€ 도움이 ν•„μš”ν•˜μ‹ κ°€μš”? 🀝"],
270
- ["이 λ‚΄μš©μ— λŒ€ν•΄ μ’€ 더 μžμ„Ένžˆ μ„€λͺ…ν•΄ μ£Όμ‹€ 수 μžˆλ‚˜μš”? πŸ’‘"],
271
  ["μ œκ°€ μ΄ν•΄ν•˜κΈ° μ‰½κ²Œ μ„€λͺ…ν•΄ μ£Όμ‹œκ² μ–΄μš”? πŸ“š"],
272
  ["이 λ‚΄μš©μ„ μ‹€μ œλ‘œ μ–΄λ–»κ²Œ ν™œμš©ν•  수 μžˆμ„κΉŒμš”? 🎯"],
273
  ["μΆ”κ°€λ‘œ μ‘°μ–Έν•΄ μ£Όμ‹€ λ‚΄μš©μ΄ μžˆμœΌμ‹ κ°€μš”? ✨"],
@@ -310,4 +307,4 @@ with gr.Blocks(theme="Yntec/HaleyCH_Theme_Orange", title="GiniGEN πŸ€–") as demo
310
  )
311
 
312
  if __name__ == "__main__":
313
- demo.launch()
 
20
  class ChatHistory:
21
  def __init__(self):
22
  self.history = []
23
+ self.history_file = "/tmp/chat_history.json"
24
  self.load_history()
25
 
26
+ def add_conversation(self, user_msg: str, assistant_msg: str):
27
+ conversation = {
28
+ "timestamp": datetime.now().isoformat(),
29
+ "conversation": [
30
+ {"role": "user", "content": user_msg},
31
+ {"role": "assistant", "content": assistant_msg}
32
+ ]
33
  }
34
+ self.history.append(conversation)
35
  self.save_history()
36
 
37
+ def get_recent_conversations(self, limit=10):
38
+ return self.history[-limit:] if self.history else []
39
+
40
+ def format_for_display(self):
41
+ formatted = []
42
+ for conv in self.history:
43
+ formatted.extend([
44
+ [conv["conversation"][0]["content"], conv["conversation"][1]["content"]]
45
+ ])
46
+ return formatted
47
 
48
  def clear_history(self):
49
  self.history = []
 
145
  except Exception as e:
146
  return f"❌ 파일 읽기 였λ₯˜: {str(e)}", "error"
147
 
 
 
 
 
 
 
 
148
 
149
  def chat(message, history, uploaded_file, system_message="", max_tokens=4000, temperature=0.7, top_p=0.9):
150
+ if not message:
151
+ return "", history
152
+
153
  system_prefix = """μ €λŠ” μ—¬λŸ¬λΆ„μ˜ μΉœκ·Όν•˜κ³  지적인 AI μ–΄μ‹œμŠ€ν„΄νŠΈ 'GiniGEN'μž…λ‹ˆλ‹€.. λ‹€μŒκ³Ό 같은 μ›μΉ™μœΌλ‘œ μ†Œν†΅ν•˜κ² μŠ΅λ‹ˆλ‹€:
154
 
155
  1. 🀝 μΉœκ·Όν•˜κ³  곡감적인 νƒœλ„λ‘œ λŒ€ν™”
 
161
  항상 예의 λ°”λ₯΄κ³  μΉœμ ˆν•˜κ²Œ μ‘λ‹΅ν•˜λ©°, ν•„μš”ν•œ 경우 ꡬ체적인 μ˜ˆμ‹œλ‚˜ μ„€λͺ…을 μΆ”κ°€ν•˜μ—¬
162
  이해λ₯Ό λ•κ² μŠ΅λ‹ˆλ‹€."""
163
 
164
+ try:
165
+ if uploaded_file:
166
+ content, file_type = read_uploaded_file(uploaded_file)
167
+ if file_type == "error":
168
+ error_message = content
169
+ chat_history.add_conversation(message, error_message)
170
+ return "", history + [[message, error_message]]
171
+
172
+ file_summary = analyze_file_content(content, file_type)
 
 
 
 
 
 
 
 
173
 
174
+ if file_type in ['parquet', 'csv']:
175
+ system_message += f"\n\n파일 λ‚΄μš©:\n```markdown\n{content}\n```"
176
+ else:
177
+ system_message += f"\n\n파일 λ‚΄μš©:\n```\n{content}\n```"
178
+
179
+ if message == "파일 뢄석을 μ‹œμž‘ν•©λ‹ˆλ‹€...":
180
+ message = f"""[파일 ꡬ쑰 뢄석] {file_summary}
181
 
182
  λ‹€μŒ κ΄€μ μ—μ„œ 도움을 λ“œλ¦¬κ² μŠ΅λ‹ˆλ‹€:
183
  1. πŸ“‹ μ „λ°˜μ μΈ λ‚΄μš© νŒŒμ•…
 
186
  4. ✨ κ°œμ„  μ œμ•ˆ
187
  5. πŸ’¬ μΆ”κ°€ μ§ˆλ¬Έμ΄λ‚˜ ν•„μš”ν•œ μ„€λͺ…"""
188
 
189
+ # μ‹œμŠ€ν…œ λ©”μ‹œμ§€ 및 νžˆμŠ€ν† λ¦¬ μ„€μ •
190
+ messages = [{"role": "system", "content": system_prefix + system_message}]
191
+
192
+ # 이전 λŒ€ν™” νžˆμŠ€ν† λ¦¬ μΆ”κ°€
193
+ if history:
194
+ for h in history:
195
+ messages.append({"role": "user", "content": h[0]})
196
+ if h[1]:
197
+ messages.append({"role": "assistant", "content": h[1]})
198
+
199
+ messages.append({"role": "user", "content": message})
 
200
 
 
201
  client = get_client()
202
  partial_message = ""
 
203
 
204
+ # 슀트리밍 응닡 처리
205
  for msg in client.chat_completion(
206
  messages,
207
  max_tokens=max_tokens,
 
212
  token = msg.choices[0].delta.get('content', None)
213
  if token:
214
  partial_message += token
215
+ current_history = history + [[message, partial_message]]
 
 
 
216
  yield "", current_history
217
+
218
+ # μ™„μ„±λœ λŒ€ν™” μ €μž₯
219
+ chat_history.add_conversation(message, partial_message)
220
 
 
 
 
221
  except Exception as e:
222
  error_msg = f"❌ 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€: {str(e)}"
223
+ chat_history.add_conversation(message, error_msg)
224
+ yield "", history + [[message, error_msg]]
 
 
 
 
225
 
 
226
 
227
+ with gr.Blocks(theme="Yntec/HaleyCH_Theme_Orange", title="GiniGEN πŸ€–") as demo:
228
+ # κΈ°μ‘΄ νžˆμŠ€ν† λ¦¬ λ‘œλ“œ
229
+ initial_history = chat_history.format_for_display()
230
+
231
  with gr.Row():
232
  with gr.Column(scale=2):
233
  chatbot = gr.Chatbot(
234
+ value=initial_history, # 초기 νžˆμŠ€ν† λ¦¬ μ„€μ •
235
  height=600,
236
  label="λŒ€ν™”μ°½ πŸ’¬",
237
  show_label=True,
 
265
  gr.Examples(
266
  examples=[
267
  ["μ•ˆλ…•ν•˜μ„Έμš”! μ–΄λ–€ 도움이 ν•„μš”ν•˜μ‹ κ°€μš”? 🀝"],
 
268
  ["μ œκ°€ μ΄ν•΄ν•˜κΈ° μ‰½κ²Œ μ„€λͺ…ν•΄ μ£Όμ‹œκ² μ–΄μš”? πŸ“š"],
269
  ["이 λ‚΄μš©μ„ μ‹€μ œλ‘œ μ–΄λ–»κ²Œ ν™œμš©ν•  수 μžˆμ„κΉŒμš”? 🎯"],
270
  ["μΆ”κ°€λ‘œ μ‘°μ–Έν•΄ μ£Όμ‹€ λ‚΄μš©μ΄ μžˆμœΌμ‹ κ°€μš”? ✨"],
 
307
  )
308
 
309
  if __name__ == "__main__":
310
+ demo.launch()