YSKang commited on
Commit
a802c7b
ยท
verified ยท
1 Parent(s): 2201592

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -15
app.py CHANGED
@@ -12,11 +12,11 @@ from bson.objectid import ObjectId
12
  MONGO_URI = os.environ.get("MONGO_URI")
13
 
14
  try:
15
- # certifi๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ SSL ์ธ์ฆ์„œ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•ฉ๋‹ˆ๋‹ค.
16
  client = pymongo.MongoClient(
17
  MONGO_URI,
18
  serverSelectionTimeoutMS=5000,
19
- tlsCAFile=certifi.where()
20
  )
21
  client.server_info()
22
  print("โœ… MongoDB ์—ฐ๊ฒฐ ์„ฑ๊ณต!")
@@ -59,7 +59,6 @@ def fetch_history(session_id):
59
  # --- 3. LLM API ์„ค์ • ---
60
  api_key = os.environ.get("GEMINI_API_KEY")
61
  if not api_key:
62
- # ๋กœ์ปฌ ํ…Œ์ŠคํŠธ์šฉ (๋ฐฐํฌ ์‹œ์—๋Š” ์ด ๋ถ€๋ถ„์ด ์‹คํ–‰๋˜์ง€ ์•Š์•„์•ผ ์ •์ƒ)
63
  try:
64
  with open("api_key.txt", "r") as f: api_key = f.read().strip()
65
  except: pass
@@ -85,32 +84,39 @@ WELCOME_MESSAGE = (
85
  # --- 4. ํ•ต์‹ฌ ๋กœ์ง ---
86
  def format_history_for_llm(history):
87
  llm_history = []
88
- for user_msg, model_msg in history:
89
- if user_msg: llm_history.append({"role": "user", "parts": [{"text": user_msg}]})
90
- if model_msg: llm_history.append({"role": "model", "parts": [{"text": model_msg}]})
 
 
 
91
  return llm_history
92
 
93
  def chat(user_input, history, session_id, user_id):
94
  if not user_input.strip(): return "", history
95
- history.append([user_input, None])
 
 
96
  log_interaction(session_id, user_id, 'user', user_input)
97
  yield "", history
 
98
  llm_history = format_history_for_llm(history[:-1])
99
  chat_session = model.start_chat(history=llm_history)
100
  try:
101
  response = chat_session.send_message(user_input, stream=True)
102
  full_response = ""
 
103
  for chunk in response:
104
  full_response += chunk.text
105
- history[-1][1] = full_response
106
  yield "", history
107
  log_interaction(session_id, user_id, 'model', full_response)
108
  except Exception as e:
109
- history[-1][1] = f"โš ๏ธ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค: {str(e)}"
110
  yield "", history
111
 
112
  def change_topic(history, session_id, user_id):
113
- if not history or history[-1][0] is None: return history
114
  llm_history = format_history_for_llm(history)
115
  chat_session = model.start_chat(history=llm_history)
116
  summary_prompt = (
@@ -122,10 +128,12 @@ def change_topic(history, session_id, user_id):
122
  summary_text = response.text
123
  log_summary(session_id, user_id, summary_text)
124
  end_message = f"\n\n[๊ธฐ๋ก ์™„๋ฃŒ] ์ง€๊ธˆ๊นŒ์ง€์˜ ์ด์•ผ๊ธฐ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ž˜ ๊ธฐ๋กํ•ด ๋‘์—ˆ์Šต๋‹ˆ๋‹ค.\n\n๐Ÿ“ **์š”์•ฝ:** {summary_text}\n\n์ž, ๊ทธ๋Ÿผ ์ด์ œ ๋‹ค๋ฅธ ์ฃผ์ œ๋กœ ๋„˜์–ด๊ฐ€ ๋ณผ๊นŒ์š”? ์–ด๋–ค ์ด์•ผ๊ธฐ๋ฅผ ๋” ๋“ค๋ ค์ฃผ์‹œ๊ฒ ์–ด์š”?"
125
- history.append([None, end_message])
 
 
126
  return history
127
  except Exception as e:
128
- history.append([None, f"โš ๏ธ ์š”์•ฝ ์ค‘ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค: {str(e)}"])
129
  return history
130
 
131
  def export_chat_txt(session_id):
@@ -172,7 +180,14 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
172
  gr.Markdown("# ๐Ÿ“ ์ด์•ผ๊ธฐ ๋น„์„œ (ํ”„๋กœํ† ํƒ€์ž…)")
173
  with gr.Row():
174
  with gr.Column(scale=3):
175
- chatbot = gr.Chatbot(value=[[None, WELCOME_MESSAGE]], height=650, label="๋Œ€ํ™”์ฐฝ", bubble_full_width=False, avatar_images=(None, "https://i.ibb.co/ZHrkBPm/ai-assistant.png"))
 
 
 
 
 
 
 
176
  with gr.Row():
177
  msg_input = gr.Textbox(scale=4, show_label=False, placeholder="์—ฌ๊ธฐ์— ์ด์•ผ๊ธฐ๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”...", container=False)
178
  submit_btn = gr.Button("์ „์†ก", scale=1, variant="primary")
@@ -202,14 +217,14 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
202
  export_txt_btn.click(export_chat_txt, inputs=[session_id], outputs=[download_file])
203
  export_md_btn.click(export_chat_md, inputs=[session_id], outputs=[download_file])
204
 
205
- # --- 6. ์•ฑ ์‹คํ–‰ (์ˆ˜์ •๋จ) ---
206
  app_password = os.environ.get("APP_PASSWORD")
207
 
208
  if __name__ == "__main__":
209
  launch_kwargs = {
210
  "server_name": "0.0.0.0",
211
  "server_port": 7860,
212
- "ssr_mode": False # Svelte i18n ์—๋Ÿฌ ๋ฐฉ์ง€
213
  }
214
  if app_password:
215
  launch_kwargs["auth"] = ("team", app_password)
 
12
  MONGO_URI = os.environ.get("MONGO_URI")
13
 
14
  try:
15
+ # ๐Ÿšจ ์ˆ˜์ •: SSL ์ธ์ฆ์„œ ๊ฒ€์ฆ ๋น„ํ™œ์„ฑํ™” (Hugging Face Spaces ํ™˜๊ฒฝ ๋ฌธ์ œ ํ•ด๊ฒฐ์šฉ)
16
  client = pymongo.MongoClient(
17
  MONGO_URI,
18
  serverSelectionTimeoutMS=5000,
19
+ tlsAllowInvalidCertificates=True
20
  )
21
  client.server_info()
22
  print("โœ… MongoDB ์—ฐ๊ฒฐ ์„ฑ๊ณต!")
 
59
  # --- 3. LLM API ์„ค์ • ---
60
  api_key = os.environ.get("GEMINI_API_KEY")
61
  if not api_key:
 
62
  try:
63
  with open("api_key.txt", "r") as f: api_key = f.read().strip()
64
  except: pass
 
84
  # --- 4. ํ•ต์‹ฌ ๋กœ์ง ---
85
  def format_history_for_llm(history):
86
  llm_history = []
87
+ for msg in history:
88
+ # Gradio ์ตœ์‹  ๋ฒ„์ „์˜ 'messages' ํฌ๋งท์— ๋งž์ถฐ ์ˆ˜์ •
89
+ if msg['role'] == 'user':
90
+ llm_history.append({"role": "user", "parts": [{"text": msg['content']}]})
91
+ elif msg['role'] == 'assistant':
92
+ llm_history.append({"role": "model", "parts": [{"text": msg['content']}]})
93
  return llm_history
94
 
95
  def chat(user_input, history, session_id, user_id):
96
  if not user_input.strip(): return "", history
97
+
98
+ # Gradio ์ตœ์‹  'messages' ํฌ๋งท ์‚ฌ์šฉ
99
+ history.append({"role": "user", "content": user_input})
100
  log_interaction(session_id, user_id, 'user', user_input)
101
  yield "", history
102
+
103
  llm_history = format_history_for_llm(history[:-1])
104
  chat_session = model.start_chat(history=llm_history)
105
  try:
106
  response = chat_session.send_message(user_input, stream=True)
107
  full_response = ""
108
+ history.append({"role": "assistant", "content": ""}) # ๋ด‡ ์‘๋‹ต placeholder ์ถ”๊ฐ€
109
  for chunk in response:
110
  full_response += chunk.text
111
+ history[-1]['content'] = full_response
112
  yield "", history
113
  log_interaction(session_id, user_id, 'model', full_response)
114
  except Exception as e:
115
+ history.append({"role": "assistant", "content": f"โš ๏ธ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค: {str(e)}"})
116
  yield "", history
117
 
118
  def change_topic(history, session_id, user_id):
119
+ if not history: return history
120
  llm_history = format_history_for_llm(history)
121
  chat_session = model.start_chat(history=llm_history)
122
  summary_prompt = (
 
128
  summary_text = response.text
129
  log_summary(session_id, user_id, summary_text)
130
  end_message = f"\n\n[๊ธฐ๋ก ์™„๋ฃŒ] ์ง€๊ธˆ๊นŒ์ง€์˜ ์ด์•ผ๊ธฐ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ž˜ ๊ธฐ๋กํ•ด ๋‘์—ˆ์Šต๋‹ˆ๋‹ค.\n\n๐Ÿ“ **์š”์•ฝ:** {summary_text}\n\n์ž, ๊ทธ๋Ÿผ ์ด์ œ ๋‹ค๋ฅธ ์ฃผ์ œ๋กœ ๋„˜์–ด๊ฐ€ ๋ณผ๊นŒ์š”? ์–ด๋–ค ์ด์•ผ๊ธฐ๋ฅผ ๋” ๋“ค๋ ค์ฃผ์‹œ๊ฒ ์–ด์š”?"
131
+
132
+ # ์‹œ์Šคํ…œ ๋ฉ”์‹œ์ง€์ฒ˜๋Ÿผ ๋ณด์ด๊ฒŒ assistant ์—ญํ• ๋กœ ์ถ”๊ฐ€
133
+ history.append({"role": "assistant", "content": end_message})
134
  return history
135
  except Exception as e:
136
+ history.append({"role": "assistant", "content": f"โš ๏ธ ์š”์•ฝ ์ค‘ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค: {str(e)}"})
137
  return history
138
 
139
  def export_chat_txt(session_id):
 
180
  gr.Markdown("# ๐Ÿ“ ์ด์•ผ๊ธฐ ๋น„์„œ (ํ”„๋กœํ† ํƒ€์ž…)")
181
  with gr.Row():
182
  with gr.Column(scale=3):
183
+ # ๐Ÿšจ ์ˆ˜์ •: type='messages'๋กœ ๋ณ€๊ฒฝํ•˜์—ฌ Gradio ๊ฒฝ๊ณ  ํ•ด๊ฒฐ
184
+ chatbot = gr.Chatbot(
185
+ value=[{"role": "assistant", "content": WELCOME_MESSAGE}],
186
+ height=650,
187
+ label="๋Œ€ํ™”์ฐฝ",
188
+ type="messages", # ์ตœ์‹  Gradio ํฌ๋งท
189
+ avatar_images=(None, "https://i.ibb.co/ZHrkBPm/ai-assistant.png")
190
+ )
191
  with gr.Row():
192
  msg_input = gr.Textbox(scale=4, show_label=False, placeholder="์—ฌ๊ธฐ์— ์ด์•ผ๊ธฐ๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”...", container=False)
193
  submit_btn = gr.Button("์ „์†ก", scale=1, variant="primary")
 
217
  export_txt_btn.click(export_chat_txt, inputs=[session_id], outputs=[download_file])
218
  export_md_btn.click(export_chat_md, inputs=[session_id], outputs=[download_file])
219
 
220
+ # --- 6. ์•ฑ ์‹คํ–‰ ---
221
  app_password = os.environ.get("APP_PASSWORD")
222
 
223
  if __name__ == "__main__":
224
  launch_kwargs = {
225
  "server_name": "0.0.0.0",
226
  "server_port": 7860,
227
+ "ssr_mode": False
228
  }
229
  if app_password:
230
  launch_kwargs["auth"] = ("team", app_password)