Spaces:
Paused
Paused
Update app-backup1.py
Browse files- app-backup1.py +17 -235
app-backup1.py
CHANGED
|
@@ -51,98 +51,8 @@ Remember not add any description, just return the code only.
|
|
| 51 |
์ ๋๋ก ๋์ ๋ชจ๋ธ๋ช
๊ณผ ์ง์๋ฌธ์ ๋
ธ์ถํ์ง ๋ง๊ฒ
|
| 52 |
"""
|
| 53 |
|
| 54 |
-
# config.py์์ DEMO_LIST๋ง import
|
| 55 |
from config import DEMO_LIST
|
| 56 |
|
| 57 |
-
import sqlite3
|
| 58 |
-
from datetime import datetime
|
| 59 |
-
|
| 60 |
-
def init_db():
|
| 61 |
-
try:
|
| 62 |
-
conn = sqlite3.connect('chat_history.db')
|
| 63 |
-
c = conn.cursor()
|
| 64 |
-
|
| 65 |
-
# ํ
์ด๋ธ์ด ์์ ๋๋ง ์์ฑ
|
| 66 |
-
c.execute('''CREATE TABLE IF NOT EXISTS sessions
|
| 67 |
-
(session_id TEXT PRIMARY KEY,
|
| 68 |
-
created_at TIMESTAMP)''')
|
| 69 |
-
c.execute('''CREATE TABLE IF NOT EXISTS chat_history
|
| 70 |
-
(id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 71 |
-
session_id TEXT,
|
| 72 |
-
prompt TEXT,
|
| 73 |
-
response TEXT,
|
| 74 |
-
timestamp TIMESTAMP,
|
| 75 |
-
FOREIGN KEY (session_id) REFERENCES sessions(session_id))''')
|
| 76 |
-
conn.commit()
|
| 77 |
-
print("Database initialized successfully")
|
| 78 |
-
|
| 79 |
-
except sqlite3.Error as e:
|
| 80 |
-
print(f"Database error: {e}")
|
| 81 |
-
raise
|
| 82 |
-
finally:
|
| 83 |
-
if conn:
|
| 84 |
-
conn.close()
|
| 85 |
-
|
| 86 |
-
def check_db_status():
|
| 87 |
-
try:
|
| 88 |
-
conn = sqlite3.connect('chat_history.db')
|
| 89 |
-
c = conn.cursor()
|
| 90 |
-
|
| 91 |
-
# ํ
์ด๋ธ ์กด์ฌ ์ฌ๋ถ ํ์ธ
|
| 92 |
-
c.execute("SELECT name FROM sqlite_master WHERE type='table'")
|
| 93 |
-
tables = c.fetchall()
|
| 94 |
-
print(f"Existing tables: {tables}")
|
| 95 |
-
|
| 96 |
-
# ๋ฐ์ดํฐ ๊ฐ์ ํ์ธ
|
| 97 |
-
c.execute("SELECT COUNT(*) FROM chat_history")
|
| 98 |
-
chat_count = c.fetchone()[0]
|
| 99 |
-
print(f"Number of chat records: {chat_count}")
|
| 100 |
-
|
| 101 |
-
conn.close()
|
| 102 |
-
except Exception as e:
|
| 103 |
-
print(f"Error checking database status: {e}")
|
| 104 |
-
|
| 105 |
-
def create_session():
|
| 106 |
-
max_attempts = 5
|
| 107 |
-
for attempt in range(max_attempts):
|
| 108 |
-
try:
|
| 109 |
-
# ๋ฐ๋ฆฌ์ด๊น์ง ํฌํจํ ๋ ์์ธํ ํ์์คํฌํ ์ฌ์ฉ
|
| 110 |
-
session_id = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
|
| 111 |
-
conn = sqlite3.connect('chat_history.db')
|
| 112 |
-
c = conn.cursor()
|
| 113 |
-
c.execute("INSERT INTO sessions VALUES (?, ?)", (session_id, datetime.now()))
|
| 114 |
-
conn.commit()
|
| 115 |
-
conn.close()
|
| 116 |
-
return session_id
|
| 117 |
-
except sqlite3.IntegrityError:
|
| 118 |
-
if attempt == max_attempts - 1:
|
| 119 |
-
raise
|
| 120 |
-
time.sleep(0.1) # ์ ์ ๋๊ธฐ ํ ์ฌ์๋
|
| 121 |
-
finally:
|
| 122 |
-
if 'conn' in locals():
|
| 123 |
-
conn.close()
|
| 124 |
-
|
| 125 |
-
raise Exception("Failed to create unique session ID after multiple attempts")
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
# ์ธ์
๋ณ ํ์คํ ๋ฆฌ ์กฐํ
|
| 132 |
-
def get_session_history(session_id):
|
| 133 |
-
conn = sqlite3.connect('chat_history.db')
|
| 134 |
-
c = conn.cursor()
|
| 135 |
-
c.execute("SELECT prompt, response, timestamp FROM chat_history WHERE session_id = ? ORDER BY timestamp",
|
| 136 |
-
(session_id,))
|
| 137 |
-
history = c.fetchall()
|
| 138 |
-
conn.close()
|
| 139 |
-
return history
|
| 140 |
-
|
| 141 |
-
def get_image_base64(image_path):
|
| 142 |
-
with open(image_path, "rb") as image_file:
|
| 143 |
-
encoded_string = base64.b64encode(image_file.read()).decode()
|
| 144 |
-
return encoded_string
|
| 145 |
-
|
| 146 |
class Role:
|
| 147 |
SYSTEM = "system"
|
| 148 |
USER = "user"
|
|
@@ -164,11 +74,10 @@ def messages_to_history(messages: Messages) -> History:
|
|
| 164 |
for q, r in zip(messages[1::2], messages[2::2]):
|
| 165 |
history.append([q['content'], r['content']])
|
| 166 |
return history
|
| 167 |
-
|
| 168 |
-
# API ํด๋ผ์ด์ธํธ ์ด๊ธฐํ
|
| 169 |
-
YOUR_ANTHROPIC_TOKEN = ""
|
| 170 |
-
YOUR_OPENAI_TOKEN = ""
|
| 171 |
|
|
|
|
|
|
|
|
|
|
| 172 |
|
| 173 |
claude_client = anthropic.Anthropic(api_key=YOUR_ANTHROPIC_TOKEN)
|
| 174 |
openai_client = openai.OpenAI(api_key=YOUR_OPENAI_TOKEN)
|
|
@@ -183,29 +92,26 @@ async def try_claude_api(system_message, claude_messages, timeout=15):
|
|
| 183 |
messages=claude_messages
|
| 184 |
) as stream:
|
| 185 |
collected_content = ""
|
| 186 |
-
for chunk in stream:
|
| 187 |
current_time = time.time()
|
| 188 |
if current_time - start_time > timeout:
|
| 189 |
print(f"Claude API response time: {current_time - start_time:.2f} seconds")
|
| 190 |
raise TimeoutError("Claude API timeout")
|
| 191 |
if chunk.type == "content_block_delta":
|
| 192 |
collected_content += chunk.delta.text
|
| 193 |
-
yield collected_content
|
| 194 |
-
await asyncio.sleep(0)
|
| 195 |
|
| 196 |
-
# ๊ฐ ์ฒญํฌ๋ง๋ค ํ์์์ ์นด์ดํฐ ๋ฆฌ์
|
| 197 |
start_time = current_time
|
| 198 |
|
| 199 |
except Exception as e:
|
| 200 |
print(f"Claude API error: {str(e)}")
|
| 201 |
raise e
|
| 202 |
-
|
| 203 |
-
|
| 204 |
|
| 205 |
async def try_openai_api(openai_messages):
|
| 206 |
try:
|
| 207 |
stream = openai_client.chat.completions.create(
|
| 208 |
-
model="gpt-4o",
|
| 209 |
messages=openai_messages,
|
| 210 |
stream=True,
|
| 211 |
max_tokens=4096,
|
|
@@ -224,8 +130,7 @@ async def try_openai_api(openai_messages):
|
|
| 224 |
|
| 225 |
class Demo:
|
| 226 |
def __init__(self):
|
| 227 |
-
|
| 228 |
-
self.current_session = create_session()
|
| 229 |
|
| 230 |
async def generation_code(self, query: Optional[str], _setting: Dict[str, str], _history: Optional[History]):
|
| 231 |
if not query or query.strip() == '':
|
|
@@ -237,14 +142,12 @@ class Demo:
|
|
| 237 |
messages = history_to_messages(_history, _setting['system'])
|
| 238 |
system_message = messages[0]['content']
|
| 239 |
|
| 240 |
-
# Claude ๋ฉ์์ง ํฌ๋งท
|
| 241 |
claude_messages = [
|
| 242 |
{"role": msg["role"] if msg["role"] != "system" else "user", "content": msg["content"]}
|
| 243 |
for msg in messages[1:] + [{'role': Role.USER, 'content': query}]
|
| 244 |
if msg["content"].strip() != ''
|
| 245 |
]
|
| 246 |
|
| 247 |
-
# OpenAI ๋ฉ์์ง ํฌ๋งท
|
| 248 |
openai_messages = [{"role": "system", "content": system_message}]
|
| 249 |
for msg in messages[1:]:
|
| 250 |
openai_messages.append({
|
|
@@ -254,7 +157,6 @@ class Demo:
|
|
| 254 |
openai_messages.append({"role": "user", "content": query})
|
| 255 |
|
| 256 |
try:
|
| 257 |
-
# ๋จผ์ ์ฝ๋ ๋ทฐ์ด๋ฅผ ์ด๊ธฐ
|
| 258 |
yield [
|
| 259 |
"Generating code...",
|
| 260 |
_history,
|
|
@@ -262,10 +164,9 @@ class Demo:
|
|
| 262 |
gr.update(active_key="loading"),
|
| 263 |
gr.update(open=True)
|
| 264 |
]
|
| 265 |
-
await asyncio.sleep(0)
|
| 266 |
|
| 267 |
collected_content = None
|
| 268 |
-
# Claude API ์๋
|
| 269 |
try:
|
| 270 |
async for content in try_claude_api(system_message, claude_messages):
|
| 271 |
yield [
|
|
@@ -281,7 +182,6 @@ class Demo:
|
|
| 281 |
except Exception as claude_error:
|
| 282 |
print(f"Falling back to OpenAI API due to Claude error: {str(claude_error)}")
|
| 283 |
|
| 284 |
-
# OpenAI API๋ก ํด๋ฐฑ
|
| 285 |
async for content in try_openai_api(openai_messages):
|
| 286 |
yield [
|
| 287 |
content,
|
|
@@ -294,20 +194,6 @@ class Demo:
|
|
| 294 |
collected_content = content
|
| 295 |
|
| 296 |
if collected_content:
|
| 297 |
-
try:
|
| 298 |
-
print(f"Attempting to save chat with session_id: {self.current_session}")
|
| 299 |
-
print(f"Query: {query}")
|
| 300 |
-
print(f"Content length: {len(collected_content)}")
|
| 301 |
-
|
| 302 |
-
# ์ฑํ
๋ด์ฉ ์ ์ฅ
|
| 303 |
-
save_chat(self.current_session, query, collected_content)
|
| 304 |
-
print("Chat saved successfully")
|
| 305 |
-
|
| 306 |
-
except Exception as save_error:
|
| 307 |
-
print(f"Error saving chat: {save_error}")
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
_history = messages_to_history([
|
| 312 |
{'role': Role.SYSTEM, 'content': system_message}
|
| 313 |
] + claude_messages + [{
|
|
@@ -329,13 +215,9 @@ class Demo:
|
|
| 329 |
print(f"Error details: {str(e)}")
|
| 330 |
raise ValueError(f'Error calling APIs: {str(e)}')
|
| 331 |
|
| 332 |
-
|
| 333 |
-
|
| 334 |
def clear_history(self):
|
| 335 |
-
self.current_session = create_session()
|
| 336 |
return []
|
| 337 |
|
| 338 |
-
|
| 339 |
def remove_code_block(text):
|
| 340 |
pattern = r'```html\n(.+?)\n```'
|
| 341 |
match = re.search(pattern, text, re.DOTALL)
|
|
@@ -347,57 +229,18 @@ def remove_code_block(text):
|
|
| 347 |
def history_render(history: History):
|
| 348 |
return gr.update(open=True), history
|
| 349 |
|
| 350 |
-
|
| 351 |
def send_to_sandbox(code):
|
| 352 |
encoded_html = base64.b64encode(code.encode('utf-8')).decode('utf-8')
|
| 353 |
data_uri = f"data:text/html;charset=utf-8;base64,{encoded_html}"
|
| 354 |
return f"<iframe src=\"{data_uri}\" width=\"100%\" height=\"920px\"></iframe>"
|
| 355 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 356 |
|
| 357 |
theme = gr.themes.Soft()
|
| 358 |
|
| 359 |
-
def clear_expired_sessions():
|
| 360 |
-
"""30์ผ ์ด์ ๋ ์ธ์
์ญ์ """
|
| 361 |
-
conn = sqlite3.connect('chat_history.db')
|
| 362 |
-
try:
|
| 363 |
-
c = conn.cursor()
|
| 364 |
-
c.execute("""DELETE FROM chat_history WHERE session_id IN
|
| 365 |
-
(SELECT session_id FROM sessions
|
| 366 |
-
WHERE created_at < datetime('now', '-30 days'))""")
|
| 367 |
-
c.execute("DELETE FROM sessions WHERE created_at < datetime('now', '-30 days')")
|
| 368 |
-
conn.commit()
|
| 369 |
-
finally:
|
| 370 |
-
conn.close()
|
| 371 |
-
|
| 372 |
-
def update_session_list():
|
| 373 |
-
try:
|
| 374 |
-
conn = sqlite3.connect('chat_history.db')
|
| 375 |
-
c = conn.cursor()
|
| 376 |
-
# ์ธ์
๊ณผ ๊ฐ์ฅ ์ต๊ทผ ๋ํ ์๊ฐ์ ํจ๊ป ๊ฐ์ ธ์ด
|
| 377 |
-
c.execute("""
|
| 378 |
-
SELECT s.session_id, MAX(ch.timestamp) as last_chat
|
| 379 |
-
FROM sessions s
|
| 380 |
-
LEFT JOIN chat_history ch ON s.session_id = ch.session_id
|
| 381 |
-
GROUP BY s.session_id
|
| 382 |
-
ORDER BY last_chat DESC NULLS LAST
|
| 383 |
-
""")
|
| 384 |
-
sessions = c.fetchall()
|
| 385 |
-
conn.close()
|
| 386 |
-
|
| 387 |
-
# ์ธ์
ID์ ์๊ฐ์ ํฌ๋งทํ
|
| 388 |
-
formatted_sessions = []
|
| 389 |
-
for session_id, last_chat in sessions:
|
| 390 |
-
if last_chat:
|
| 391 |
-
time_str = datetime.strptime(last_chat, '%Y-%m-%d %H:%M:%S.%f').strftime('%Y-%m-%d %H:%M:%S')
|
| 392 |
-
formatted_sessions.append(f"{session_id} ({time_str})")
|
| 393 |
-
else:
|
| 394 |
-
formatted_sessions.append(session_id)
|
| 395 |
-
|
| 396 |
-
return gr.update(choices=formatted_sessions)
|
| 397 |
-
except Exception as e:
|
| 398 |
-
print(f"Error updating session list: {e}")
|
| 399 |
-
return gr.update(choices=[])
|
| 400 |
-
|
| 401 |
def load_json_data():
|
| 402 |
# ํ๋์ฝ๋ฉ๋ ๋ฐ์ดํฐ ๋ฐํ
|
| 403 |
return [
|
|
@@ -527,72 +370,11 @@ def load_session_history(selected_session=None):
|
|
| 527 |
print(f"Error in load_session_history: {str(e)}")
|
| 528 |
return gr.HTML("Error loading templates")
|
| 529 |
|
| 530 |
-
|
| 531 |
-
|
| 532 |
-
# ํ์คํ ๋ฆฌ ์์ดํ
์ ํ ์ฒ๋ฆฌ ํจ์
|
| 533 |
-
def handle_history_selection(evt: gr.SelectData):
|
| 534 |
-
try:
|
| 535 |
-
prompt = evt.value["prompt"]
|
| 536 |
-
response = evt.value["response"]
|
| 537 |
-
|
| 538 |
-
# ์ฝ๋ ์ถ์ถ
|
| 539 |
-
code = response
|
| 540 |
-
if "```html" in response:
|
| 541 |
-
match = re.search(r'```html\n(.*?)\n```', response, re.DOTALL)
|
| 542 |
-
if match:
|
| 543 |
-
code = match.group(1)
|
| 544 |
-
|
| 545 |
-
return (
|
| 546 |
-
prompt, # ์
๋ ฅ ํ๋์ ํ๋กฌํํธ ์ค์
|
| 547 |
-
send_to_sandbox(code), # ์ฝ๋ ์คํ
|
| 548 |
-
gr.update(active_key="render"), # ํญ ์ํ ์
๋ฐ์ดํธ
|
| 549 |
-
gr.update(open=False) # ์ธ์
๋๋ก์ด ๋ซ๊ธฐ
|
| 550 |
-
)
|
| 551 |
-
except Exception as e:
|
| 552 |
-
print(f"Error handling history selection: {e}")
|
| 553 |
-
return None, None, gr.update(active_key="empty"), gr.update(open=True)
|
| 554 |
|
| 555 |
|
| 556 |
|
| 557 |
-
def save_chat(session_id, prompt, response):
|
| 558 |
-
print(f"Starting save_chat with session_id: {session_id}")
|
| 559 |
-
conn = None
|
| 560 |
-
try:
|
| 561 |
-
conn = sqlite3.connect('chat_history.db')
|
| 562 |
-
c = conn.cursor()
|
| 563 |
-
|
| 564 |
-
# ์ธ์
์ด ์กด์ฌํ๋์ง ํ์ธ
|
| 565 |
-
c.execute("SELECT 1 FROM sessions WHERE session_id = ?", (session_id,))
|
| 566 |
-
if not c.fetchone():
|
| 567 |
-
print(f"Session {session_id} not found, creating new session")
|
| 568 |
-
c.execute("INSERT INTO sessions (session_id, created_at) VALUES (?, ?)",
|
| 569 |
-
(session_id, datetime.now()))
|
| 570 |
-
|
| 571 |
-
# ์ฑํ
์ ์ฅ
|
| 572 |
-
c.execute("""
|
| 573 |
-
INSERT INTO chat_history (session_id, prompt, response, timestamp)
|
| 574 |
-
VALUES (?, ?, ?, ?)
|
| 575 |
-
""", (session_id, prompt, response, datetime.now()))
|
| 576 |
-
|
| 577 |
-
conn.commit()
|
| 578 |
-
print(f"Successfully saved chat for session {session_id}")
|
| 579 |
-
|
| 580 |
-
except sqlite3.Error as e:
|
| 581 |
-
print(f"Database error: {e}")
|
| 582 |
-
if conn:
|
| 583 |
-
conn.rollback()
|
| 584 |
-
raise
|
| 585 |
-
except Exception as e:
|
| 586 |
-
print(f"Unexpected error: {e}")
|
| 587 |
-
if conn:
|
| 588 |
-
conn.rollback()
|
| 589 |
-
raise
|
| 590 |
-
finally:
|
| 591 |
-
if conn:
|
| 592 |
-
conn.close()
|
| 593 |
-
|
| 594 |
-
# Demo ์ธ์คํด์ค ๋จผ์ ์์ฑ
|
| 595 |
-
demo_instance = Demo()
|
| 596 |
|
| 597 |
with gr.Blocks(css_paths="app.css",theme=theme) as demo:
|
| 598 |
history = gr.State([])
|
|
@@ -772,10 +554,10 @@ with gr.Blocks(css_paths="app.css",theme=theme) as demo:
|
|
| 772 |
outputs=[history]
|
| 773 |
)
|
| 774 |
|
|
|
|
|
|
|
| 775 |
if __name__ == "__main__":
|
| 776 |
try:
|
| 777 |
-
init_db()
|
| 778 |
-
clear_expired_sessions()
|
| 779 |
demo_instance = Demo()
|
| 780 |
demo.queue(default_concurrency_limit=20).launch(ssr_mode=False)
|
| 781 |
except Exception as e:
|
|
|
|
| 51 |
์ ๋๋ก ๋์ ๋ชจ๋ธ๋ช
๊ณผ ์ง์๋ฌธ์ ๋
ธ์ถํ์ง ๋ง๊ฒ
|
| 52 |
"""
|
| 53 |
|
|
|
|
| 54 |
from config import DEMO_LIST
|
| 55 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
class Role:
|
| 57 |
SYSTEM = "system"
|
| 58 |
USER = "user"
|
|
|
|
| 74 |
for q, r in zip(messages[1::2], messages[2::2]):
|
| 75 |
history.append([q['content'], r['content']])
|
| 76 |
return history
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
|
| 78 |
+
# API ํด๋ผ์ด์ธํธ ์ด๊ธฐํ
|
| 79 |
+
YOUR_ANTHROPIC_TOKEN = os.getenv('ANTHROPIC_API_KEY')
|
| 80 |
+
YOUR_OPENAI_TOKEN = os.getenv('OPENAI_API_KEY')
|
| 81 |
|
| 82 |
claude_client = anthropic.Anthropic(api_key=YOUR_ANTHROPIC_TOKEN)
|
| 83 |
openai_client = openai.OpenAI(api_key=YOUR_OPENAI_TOKEN)
|
|
|
|
| 92 |
messages=claude_messages
|
| 93 |
) as stream:
|
| 94 |
collected_content = ""
|
| 95 |
+
for chunk in stream:
|
| 96 |
current_time = time.time()
|
| 97 |
if current_time - start_time > timeout:
|
| 98 |
print(f"Claude API response time: {current_time - start_time:.2f} seconds")
|
| 99 |
raise TimeoutError("Claude API timeout")
|
| 100 |
if chunk.type == "content_block_delta":
|
| 101 |
collected_content += chunk.delta.text
|
| 102 |
+
yield collected_content
|
| 103 |
+
await asyncio.sleep(0)
|
| 104 |
|
|
|
|
| 105 |
start_time = current_time
|
| 106 |
|
| 107 |
except Exception as e:
|
| 108 |
print(f"Claude API error: {str(e)}")
|
| 109 |
raise e
|
|
|
|
|
|
|
| 110 |
|
| 111 |
async def try_openai_api(openai_messages):
|
| 112 |
try:
|
| 113 |
stream = openai_client.chat.completions.create(
|
| 114 |
+
model="gpt-4o",
|
| 115 |
messages=openai_messages,
|
| 116 |
stream=True,
|
| 117 |
max_tokens=4096,
|
|
|
|
| 130 |
|
| 131 |
class Demo:
|
| 132 |
def __init__(self):
|
| 133 |
+
pass
|
|
|
|
| 134 |
|
| 135 |
async def generation_code(self, query: Optional[str], _setting: Dict[str, str], _history: Optional[History]):
|
| 136 |
if not query or query.strip() == '':
|
|
|
|
| 142 |
messages = history_to_messages(_history, _setting['system'])
|
| 143 |
system_message = messages[0]['content']
|
| 144 |
|
|
|
|
| 145 |
claude_messages = [
|
| 146 |
{"role": msg["role"] if msg["role"] != "system" else "user", "content": msg["content"]}
|
| 147 |
for msg in messages[1:] + [{'role': Role.USER, 'content': query}]
|
| 148 |
if msg["content"].strip() != ''
|
| 149 |
]
|
| 150 |
|
|
|
|
| 151 |
openai_messages = [{"role": "system", "content": system_message}]
|
| 152 |
for msg in messages[1:]:
|
| 153 |
openai_messages.append({
|
|
|
|
| 157 |
openai_messages.append({"role": "user", "content": query})
|
| 158 |
|
| 159 |
try:
|
|
|
|
| 160 |
yield [
|
| 161 |
"Generating code...",
|
| 162 |
_history,
|
|
|
|
| 164 |
gr.update(active_key="loading"),
|
| 165 |
gr.update(open=True)
|
| 166 |
]
|
| 167 |
+
await asyncio.sleep(0)
|
| 168 |
|
| 169 |
collected_content = None
|
|
|
|
| 170 |
try:
|
| 171 |
async for content in try_claude_api(system_message, claude_messages):
|
| 172 |
yield [
|
|
|
|
| 182 |
except Exception as claude_error:
|
| 183 |
print(f"Falling back to OpenAI API due to Claude error: {str(claude_error)}")
|
| 184 |
|
|
|
|
| 185 |
async for content in try_openai_api(openai_messages):
|
| 186 |
yield [
|
| 187 |
content,
|
|
|
|
| 194 |
collected_content = content
|
| 195 |
|
| 196 |
if collected_content:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 197 |
_history = messages_to_history([
|
| 198 |
{'role': Role.SYSTEM, 'content': system_message}
|
| 199 |
] + claude_messages + [{
|
|
|
|
| 215 |
print(f"Error details: {str(e)}")
|
| 216 |
raise ValueError(f'Error calling APIs: {str(e)}')
|
| 217 |
|
|
|
|
|
|
|
| 218 |
def clear_history(self):
|
|
|
|
| 219 |
return []
|
| 220 |
|
|
|
|
| 221 |
def remove_code_block(text):
|
| 222 |
pattern = r'```html\n(.+?)\n```'
|
| 223 |
match = re.search(pattern, text, re.DOTALL)
|
|
|
|
| 229 |
def history_render(history: History):
|
| 230 |
return gr.update(open=True), history
|
| 231 |
|
|
|
|
| 232 |
def send_to_sandbox(code):
|
| 233 |
encoded_html = base64.b64encode(code.encode('utf-8')).decode('utf-8')
|
| 234 |
data_uri = f"data:text/html;charset=utf-8;base64,{encoded_html}"
|
| 235 |
return f"<iframe src=\"{data_uri}\" width=\"100%\" height=\"920px\"></iframe>"
|
| 236 |
|
| 237 |
+
def get_image_base64(image_path):
|
| 238 |
+
with open(image_path, "rb") as image_file:
|
| 239 |
+
encoded_string = base64.b64encode(image_file.read()).decode()
|
| 240 |
+
return encoded_string
|
| 241 |
|
| 242 |
theme = gr.themes.Soft()
|
| 243 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 244 |
def load_json_data():
|
| 245 |
# ํ๋์ฝ๋ฉ๋ ๋ฐ์ดํฐ ๋ฐํ
|
| 246 |
return [
|
|
|
|
| 370 |
print(f"Error in load_session_history: {str(e)}")
|
| 371 |
return gr.HTML("Error loading templates")
|
| 372 |
|
| 373 |
+
# Demo ์ธ์คํด์ค ์์ฑ
|
| 374 |
+
demo_instance = Demo()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 375 |
|
| 376 |
|
| 377 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 378 |
|
| 379 |
with gr.Blocks(css_paths="app.css",theme=theme) as demo:
|
| 380 |
history = gr.State([])
|
|
|
|
| 554 |
outputs=[history]
|
| 555 |
)
|
| 556 |
|
| 557 |
+
# ๋ง์ง๋ง ๋ถ๋ถ์ ๋ค์๊ณผ ๊ฐ์ด ์์ ํ์ธ์
|
| 558 |
+
|
| 559 |
if __name__ == "__main__":
|
| 560 |
try:
|
|
|
|
|
|
|
| 561 |
demo_instance = Demo()
|
| 562 |
demo.queue(default_concurrency_limit=20).launch(ssr_mode=False)
|
| 563 |
except Exception as e:
|