seawolf2357 commited on
Commit
19ea20e
ยท
verified ยท
1 Parent(s): 2803195

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +132 -16
app.py CHANGED
@@ -52,6 +52,60 @@ Remember not add any description, just return the code only.
52
  # config.py์—์„œ DEMO_LIST๋งŒ import
53
  from config import DEMO_LIST
54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  def get_image_base64(image_path):
56
  with open(image_path, "rb") as image_file:
57
  encoded_string = base64.b64encode(image_file.read()).decode()
@@ -136,9 +190,17 @@ async def try_openai_api(openai_messages):
136
  raise e
137
 
138
 
139
- async def generation_code(query: Optional[str], _setting: Dict[str, str], _history: Optional[History]):
140
- if not query or query.strip() == '':
141
- query = random.choice(DEMO_LIST)['description']
 
 
 
 
 
 
 
 
142
 
143
  if _history is None:
144
  _history = []
@@ -202,8 +264,12 @@ async def generation_code(query: Optional[str], _setting: Dict[str, str], _histo
202
  await asyncio.sleep(0) # UI ์—…๋ฐ์ดํŠธ๋ฅผ ์œ„ํ•œ ์–‘๋ณด
203
  collected_content = content
204
 
 
205
  if collected_content:
206
- _history = messages_to_history([
 
 
 
207
  {'role': Role.SYSTEM, 'content': system_message}
208
  ] + claude_messages + [{
209
  'role': Role.ASSISTANT,
@@ -220,11 +286,15 @@ async def generation_code(query: Optional[str], _setting: Dict[str, str], _histo
220
  else:
221
  raise ValueError("No content was generated from either API")
222
 
223
- except Exception as e:
224
- print(f"Error details: {str(e)}")
225
- raise ValueError(f'Error calling APIs: {str(e)}')
226
-
227
 
 
 
 
 
 
 
 
 
228
 
229
 
230
  def remove_code_block(text):
@@ -238,8 +308,6 @@ def remove_code_block(text):
238
  def history_render(history: History):
239
  return gr.update(open=True), history
240
 
241
- def clear_history():
242
- return []
243
 
244
  def send_to_sandbox(code):
245
  encoded_html = base64.b64encode(code.encode('utf-8')).decode('utf-8')
@@ -249,7 +317,19 @@ def send_to_sandbox(code):
249
 
250
  theme = gr.themes.Soft()
251
 
252
-
 
 
 
 
 
 
 
 
 
 
 
 
253
  with gr.Blocks(css_paths="app.css",theme=theme) as demo:
254
  history = gr.State([])
255
  setting = gr.State({
@@ -401,7 +481,15 @@ with gr.Blocks(css_paths="app.css",theme=theme) as demo:
401
  with antd.Flex(gap="small", elem_classes="setting-buttons"):
402
  codeBtn = antd.Button("๐Ÿง‘โ€๐Ÿ’ป view code", type="default")
403
  historyBtn = antd.Button("๐Ÿ“œ history", type="default")
404
-
 
 
 
 
 
 
 
 
405
  gr.HTML('<div class="render_header"><span class="header_btn"></span><span class="header_btn"></span><span class="header_btn"></span></div>')
406
  with antd.Tabs(active_key="empty", render_tab_bar="() => null") as state_tab:
407
  with antd.Tabs.Item(key="empty"):
@@ -446,16 +534,44 @@ with gr.Blocks(css_paths="app.css",theme=theme) as demo:
446
  history_drawer.close(lambda: gr.update(
447
  open=False), inputs=[], outputs=[history_drawer])
448
 
449
- # ์ˆ˜์ •๋œ ์ฝ”๋“œ
450
  btn.click(
451
- generation_code, # ๋น„๋™๊ธฐ ํ•จ์ˆ˜๋ฅผ ์ง์ ‘ ์ „๋‹ฌ
452
  inputs=[input, setting, history],
453
  outputs=[code_output, history, sandbox, state_tab, code_drawer]
454
  )
455
 
 
 
 
 
 
 
456
 
457
-
458
- clear_btn.click(clear_history, inputs=[], outputs=[history])
459
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
460
  if __name__ == "__main__":
 
 
 
461
  demo.queue(default_concurrency_limit=20).launch(ssr_mode=False)
 
52
  # config.py์—์„œ DEMO_LIST๋งŒ import
53
  from config import DEMO_LIST
54
 
55
+ import sqlite3
56
+ from datetime import datetime
57
+
58
+
59
+ def init_db():
60
+ try:
61
+ conn = sqlite3.connect('chat_history.db')
62
+ c = conn.cursor()
63
+ c.execute('''CREATE TABLE IF NOT EXISTS sessions
64
+ (session_id TEXT PRIMARY KEY,
65
+ created_at TIMESTAMP)''')
66
+ c.execute('''CREATE TABLE IF NOT EXISTS chat_history
67
+ (id INTEGER PRIMARY KEY AUTOINCREMENT,
68
+ session_id TEXT,
69
+ prompt TEXT,
70
+ response TEXT,
71
+ timestamp TIMESTAMP,
72
+ FOREIGN KEY (session_id) REFERENCES sessions(session_id))''')
73
+ conn.commit()
74
+ except sqlite3.Error as e:
75
+ print(f"Database error: {e}")
76
+ finally:
77
+ if conn:
78
+ conn.close()
79
+
80
+ # ์ƒˆ๋กœ์šด ์„ธ์…˜ ์ƒ์„ฑ
81
+ def create_session():
82
+ session_id = datetime.now().strftime("%Y%m%d_%H%M%S")
83
+ conn = sqlite3.connect('chat_history.db')
84
+ c = conn.cursor()
85
+ c.execute("INSERT INTO sessions VALUES (?, ?)", (session_id, datetime.now()))
86
+ conn.commit()
87
+ conn.close()
88
+ return session_id
89
+
90
+ # ๋Œ€ํ™” ๋‚ด์šฉ ์ €์žฅ
91
+ def save_chat(session_id, prompt, response):
92
+ conn = sqlite3.connect('chat_history.db')
93
+ c = conn.cursor()
94
+ c.execute("INSERT INTO chat_history (session_id, prompt, response, timestamp) VALUES (?, ?, ?, ?)",
95
+ (session_id, prompt, response, datetime.now()))
96
+ conn.commit()
97
+ conn.close()
98
+
99
+ # ์„ธ์…˜๋ณ„ ํžˆ์Šคํ† ๋ฆฌ ์กฐํšŒ
100
+ def get_session_history(session_id):
101
+ conn = sqlite3.connect('chat_history.db')
102
+ c = conn.cursor()
103
+ c.execute("SELECT prompt, response, timestamp FROM chat_history WHERE session_id = ? ORDER BY timestamp",
104
+ (session_id,))
105
+ history = c.fetchall()
106
+ conn.close()
107
+ return history
108
+
109
  def get_image_base64(image_path):
110
  with open(image_path, "rb") as image_file:
111
  encoded_string = base64.b64encode(image_file.read()).decode()
 
190
  raise e
191
 
192
 
193
+
194
+ class Demo:
195
+ def __init__(self):
196
+ init_db()
197
+ self.current_session = create_session()
198
+
199
+ async def generation_code(self, query: Optional[str], _setting: Dict[str, str], _history: Optional[History]):
200
+ if not query or query.strip() == '':
201
+ query = random.choice(DEMO_LIST)['description']
202
+
203
+
204
 
205
  if _history is None:
206
  _history = []
 
264
  await asyncio.sleep(0) # UI ์—…๋ฐ์ดํŠธ๋ฅผ ์œ„ํ•œ ์–‘๋ณด
265
  collected_content = content
266
 
267
+
268
  if collected_content:
269
+ # ์ฑ„ํŒ… ๋‚ด์šฉ ์ €์žฅ
270
+ save_chat(self.current_session, query, collected_content)
271
+ _history = messages_to_history([...])
272
+
273
  {'role': Role.SYSTEM, 'content': system_message}
274
  ] + claude_messages + [{
275
  'role': Role.ASSISTANT,
 
286
  else:
287
  raise ValueError("No content was generated from either API")
288
 
 
 
 
 
289
 
290
+
291
+ except Exception as e:
292
+ print(f"Error details: {str(e)}")
293
+ raise ValueError(f'Error calling APIs: {str(e)}')
294
+
295
+ def clear_history(self):
296
+ self.current_session = create_session()
297
+ return []
298
 
299
 
300
  def remove_code_block(text):
 
308
  def history_render(history: History):
309
  return gr.update(open=True), history
310
 
 
 
311
 
312
  def send_to_sandbox(code):
313
  encoded_html = base64.b64encode(code.encode('utf-8')).decode('utf-8')
 
317
 
318
  theme = gr.themes.Soft()
319
 
320
+ def clear_expired_sessions():
321
+ """30์ผ ์ด์ƒ ๋œ ์„ธ์…˜ ์‚ญ์ œ"""
322
+ conn = sqlite3.connect('chat_history.db')
323
+ try:
324
+ c = conn.cursor()
325
+ c.execute("""DELETE FROM chat_history WHERE session_id IN
326
+ (SELECT session_id FROM sessions
327
+ WHERE created_at < datetime('now', '-30 days'))""")
328
+ c.execute("DELETE FROM sessions WHERE created_at < datetime('now', '-30 days')")
329
+ conn.commit()
330
+ finally:
331
+ conn.close()
332
+
333
  with gr.Blocks(css_paths="app.css",theme=theme) as demo:
334
  history = gr.State([])
335
  setting = gr.State({
 
481
  with antd.Flex(gap="small", elem_classes="setting-buttons"):
482
  codeBtn = antd.Button("๐Ÿง‘โ€๐Ÿ’ป view code", type="default")
483
  historyBtn = antd.Button("๐Ÿ“œ history", type="default")
484
+ sessionBtn = antd.Button("๐Ÿ“š sessions", type="default") # ์„ธ์…˜ ๋ฒ„ํŠผ ์ถ”๊ฐ€
485
+
486
+ # ์„ธ์…˜ ๋ฒ„ํŠผ ์ด๋ฒคํŠธ ํ•ธ๋“ค๋Ÿฌ
487
+ sessionBtn.click(
488
+ lambda: (gr.update(open=True), update_session_list()),
489
+ inputs=[],
490
+ outputs=[session_drawer, session_list]
491
+ )
492
+
493
  gr.HTML('<div class="render_header"><span class="header_btn"></span><span class="header_btn"></span><span class="header_btn"></span></div>')
494
  with antd.Tabs(active_key="empty", render_tab_bar="() => null") as state_tab:
495
  with antd.Tabs.Item(key="empty"):
 
534
  history_drawer.close(lambda: gr.update(
535
  open=False), inputs=[], outputs=[history_drawer])
536
 
537
+
538
  btn.click(
539
+ demo_instance.generation_code, # Demo ์ธ์Šคํ„ด์Šค์˜ ๋ฉ”์„œ๋“œ ์‚ฌ์šฉ
540
  inputs=[input, setting, history],
541
  outputs=[code_output, history, sandbox, state_tab, code_drawer]
542
  )
543
 
544
+ clear_btn.click(
545
+ demo_instance.clear_history, # Demo ์ธ์Šคํ„ด์Šค์˜ ๋ฉ”์„œ๋“œ ์‚ฌ์šฉ
546
+ inputs=[],
547
+ outputs=[history]
548
+ )
549
+
550
 
 
 
551
 
552
+
553
+ with antd.Drawer(open=False, title="Session History", placement="left", width="900px") as session_drawer:
554
+ session_list = gr.Dropdown(label="Select Session", choices=[])
555
+ session_history = legacy.Chatbot(show_label=False, height=960)
556
+
557
+ def update_session_list():
558
+ conn = sqlite3.connect('chat_history.db')
559
+ c = conn.cursor()
560
+ c.execute("SELECT session_id FROM sessions ORDER BY created_at DESC")
561
+ sessions = [row[0] for row in c.fetchall()]
562
+ conn.close()
563
+ return gr.update(choices=sessions)
564
+
565
+ def load_session_history(session_id):
566
+ history = get_session_history(session_id)
567
+ return [[p, r] for p, r, _ in history]
568
+
569
+ session_list.change(load_session_history,
570
+ inputs=[session_list],
571
+ outputs=[session_history])
572
+
573
  if __name__ == "__main__":
574
+ init_db()
575
+ clear_expired_sessions() # ๋งŒ๋ฃŒ๋œ ์„ธ์…˜ ์ •๋ฆฌ
576
+ demo_instance = Demo()
577
  demo.queue(default_concurrency_limit=20).launch(ssr_mode=False)