Spaces:
Runtime error
Runtime error
Upload app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134import uuid
import urllib.request
import json
import gradio as gr
import os
API_KEY = "AIzaSyD5k7dO2fEzxlCC5y5lkxyap39-tXqfLSE"
API_URL = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key={API_KEY}"
sessions = {}
chat_id_map = {}
if os.path.exists("chat.dat"):
with open("chat.dat", "r", encoding="utf-8") as f:
try:
sessions = json.load(f)
except:
sessions = {}
def save_chats(sessions_state):
with open("chat.dat", "w", encoding="utf-8") as f:
json.dump(sessions_state, f, ensure_ascii=False, indent=2)
def call_gemini(history):
contents = [{"role": h["role"], "parts": [{"text": h["text"]}]} for h in history]
data = {"contents": contents}
json_data = json.dumps(data).encode("utf-8")
req = urllib.request.Request(API_URL, data=json_data, headers={"Content-Type":"application/json"}, method="POST")
with urllib.request.urlopen(req) as response:
result = json.loads(response.read().decode("utf-8"))
return result["candidates"][0]["content"]["parts"][0]["text"]
def make_chat_list(sessions_state):
titles = []
chat_id_map.clear()
for cid, conv in sessions_state.items():
titles.append(conv["title"])
chat_id_map[conv["title"]] = cid
return titles
def new_chat(sessions_state):
chat_id = str(uuid.uuid4())[:8]
sessions_state[chat_id] = {"title": "새 채팅", "history": [], "ui": []}
titles = make_chat_list(sessions_state)
save_chats(sessions_state)
return chat_id, gr.update(choices=titles, value="새 채팅"), [], sessions_state
def send_message(user_input, selected_title, sessions_state):
if not user_input:
return "", selected_title, gr.update(), [], sessions_state
chat_id = chat_id_map.get(selected_title, str(uuid.uuid4())[:8])
if chat_id not in sessions_state:
sessions_state[chat_id] = {"title": "새 채팅", "history": [], "ui": []}
conv = sessions_state[chat_id]
conv["history"].append({"role": "user", "text": user_input})
if conv["title"] == "새 채팅":
conv["title"] = (user_input[:15] + "…") if len(user_input) > 15 else user_input
try:
reply = call_gemini(conv["history"])
except Exception as e:
reply = f"[Error] {e}"
conv["history"].append({"role": "model", "text": reply})
conv["ui"].append({"role": "user", "content": user_input})
conv["ui"].append({"role": "assistant", "content": reply})
titles = make_chat_list(sessions_state)
save_chats(sessions_state)
return "", conv["title"], gr.update(choices=titles, value=conv["title"]), conv["ui"], sessions_state
def switch_chat(selected_title, sessions_state):
chat_id = chat_id_map.get(selected_title)
if chat_id and chat_id in sessions_state:
conv = sessions_state[chat_id]
return conv["title"], conv["ui"], sessions_state
return "", [], sessions_state
# 토글 버튼: 왼쪽 컬럼 숨기기/보이기
def toggle_chat_list(toggle_state):
new_state = not toggle_state
if new_state: # 왼쪽 컬럼 보이기
return new_state, gr.update(visible=True, scale=1), gr.update(visible=True), gr.update(scale=3)
else: # 왼쪽 컬럼 숨기기
return new_state, gr.update(visible=False, scale=0), gr.update(visible=False), gr.update(scale=1)
with gr.Blocks(css="""
body, html {height:100%; margin:0;}
.gradio-container {height:100vh;}
.chat-column {overflow-y:auto; height:100vh;}
.chatbot-column {display:flex; flex-direction:column; height:100vh;}
.chatbot-column .chatbot {flex:1; overflow-y:auto;}
.chatbot-column .textbox {flex:none;}
.toggle-btn {width:100%; margin-bottom:5px;}
""") as demo:
chat_list_visible = gr.State(True)
toggle_btn = gr.Button("목록 토글", elem_classes="toggle-btn")
with gr.Row(elem_classes="full-height"):
with gr.Column(scale=1, elem_classes="chat-column") as chat_column:
new_btn = gr.Button("새 채팅")
chat_list = gr.Radio(choices=[], label="채팅 목록", interactive=True)
with gr.Column(scale=3, elem_classes="chatbot-column") as chatbot_column:
chatbot = gr.Chatbot(type="messages")
msg = gr.Textbox(label="질문을 입력하세요")
sessions_state = gr.State(sessions)
current_title = gr.State("")
# 토글 버튼 클릭
toggle_btn.click(toggle_chat_list, inputs=[chat_list_visible],
outputs=[chat_list_visible, chat_column, new_btn, chatbot_column])
# 새 채팅
new_btn.click(new_chat, inputs=[sessions_state],
outputs=[current_title, chat_list, chatbot, sessions_state])
# 메시지 전송
msg.submit(send_message, inputs=[msg, chat_list, sessions_state],
outputs=[msg, chat_list, chat_list, chatbot, sessions_state])
# 채팅 선택
chat_list.change(switch_chat, inputs=[chat_list, sessions_state],
outputs=[current_title, chatbot, sessions_state])
# 초기 로드
demo.load(new_chat, inputs=[sessions_state],
outputs=[current_title, chat_list, chatbot, sessions_state])
demo.launch()app.pyAdded+134