Spaces:
Runtime error
Runtime error
Create app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204import uuidimport urllib.requestimport jsonimport gradio as grimport os
# ------------------ Gemini API ------------------API_KEY = os.environ.get("API_KEY") # β οΈ Gemini API ν€ μ
λ ₯API_URL = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key={API_KEY}"
USER_FILE = "users.json"CHAT_FILE = "chat.dat"
# ------------------ λ°μ΄ν° λ‘λ ------------------if os.path.exists(USER_FILE): with open(USER_FILE, "r", encoding="utf-8") as f: USER_DATA = json.load(f)else: USER_DATA = {}
if os.path.exists(CHAT_FILE): with open(CHAT_FILE, "r", encoding="utf-8") as f: try: all_sessions = json.load(f) except: all_sessions = {}else: all_sessions = {}
# ------------------ μ νΈ ------------------def save_users(): with open(USER_FILE, "w", encoding="utf-8") as f: json.dump(USER_DATA, f, ensure_ascii=False, indent=2)
def save_chats(user, sessions_state): all_sessions[user] = sessions_state with open(CHAT_FILE, "w", encoding="utf-8") as f: json.dump(all_sessions, f, ensure_ascii=False, indent=2)
# ------------------ Gemini νΈμΆ ------------------def call_gemini(history): if not history: return "μλ
νμΈμ! 무μμ λμλ릴κΉμ?"
contents = [] for h in history: role = "user" if h["role"] == "user" else "model" contents.append({ "role": role, "parts": [{"text": h["text"]}] })
data = { "contents": contents, "generationConfig": { "temperature": 0.7 } }
try: req = urllib.request.Request( API_URL, data=json.dumps(data).encode("utf-8"), 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"]
except urllib.error.HTTPError as e: return f"β μλ² μ€λ₯ (HTTP {e.code})" except urllib.error.URLError: return "β λ€νΈμν¬ μ°κ²° μ€ν¨" except Exception as e: return f"β μ μ μλ μ€λ₯: {e}"
# ------------------ μ±ν
κ΄λ¦¬ ------------------chat_id_map = {}
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, user): chat_id = str(uuid.uuid4())[:8] sessions_state[chat_id] = {"title": "μ μ±ν
", "history": [], "ui": []} titles = make_chat_list(sessions_state) save_chats(user, sessions_state) return chat_id, gr.update(choices=titles, value="μ μ±ν
"), [], sessions_state
def send_message(user_input, selected_title, sessions_state, user): 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(user, 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 delete_chat(selected_title, sessions_state, user): chat_id = chat_id_map.get(selected_title) if chat_id and chat_id in sessions_state: del sessions_state[chat_id] save_chats(user, sessions_state) titles = make_chat_list(sessions_state) return gr.update(choices=titles, value=None), [], sessions_state, "μ±ν
μ΄ μμ λμμ΅λλ€." return gr.update(), [], sessions_state, "μμ ν μ±ν
μ μ ννμΈμ."
# ------------------ λ‘κ·ΈμΈ/νμκ°μ
------------------def login(username, password): if username in USER_DATA and USER_DATA[username] == password: sessions_state = all_sessions.get(username, {}) return gr.update(visible=False), gr.update(visible=True), sessions_state, username, "" return gr.update(visible=True), gr.update(visible=False), {}, "", "μμ΄λ λλ λΉλ°λ²νΈ μ€λ₯"
def signup(username, password): if not username or not password: return "μμ΄λ/λΉλ°λ²νΈ μ
λ ₯ νμ" if username in USER_DATA: return "μ΄λ―Έ μ‘΄μ¬νλ μμ΄λ" USER_DATA[username] = password save_users() return "νμκ°μ
μλ£! λ‘κ·ΈμΈνμΈμ."
def logout(): return gr.update(visible=True), gr.update(visible=False), {}, "", ""
# ------------------ λͺ©λ‘ ν κΈ ------------------def toggle_chat_list(chat_list_visible): new_state = not chat_list_visible return new_state, gr.update(visible=new_state)
# ------------------ UI ------------------with gr.Blocks() as demo: current_title = gr.State("") chat_list_visible = gr.State(True) username_state = gr.State("") sessions_state = gr.State({})
# λ‘κ·ΈμΈ/νμκ°μ
with gr.Column(visible=True) as login_page: username_input = gr.Textbox(label="μμ΄λ") password_input = gr.Textbox(label="λΉλ°λ²νΈ", type="password") login_btn = gr.Button("λ‘κ·ΈμΈ") signup_btn = gr.Button("νμκ°μ
") login_message = gr.Markdown("") signup_message = gr.Markdown("")
# μ±ν
νλ©΄ with gr.Column(visible=False) as chat_page: with gr.Row(): logout_btn = gr.Button("λ‘κ·Έμμ") toggle_list_btn = gr.Button("λͺ©λ‘ ν κΈ") with gr.Row(): with gr.Column(scale=1, visible=True) as chat_list_column: new_btn = gr.Button("μ μ±ν
") delete_btn = gr.Button("μ±ν
μμ ") chat_list = gr.Radio(choices=[], label="μ±ν
λͺ©λ‘", interactive=True) with gr.Column(scale=3): chatbot = gr.Chatbot(type="messages") msg = gr.Textbox(label="μ§λ¬Έ μ
λ ₯") delete_message = gr.Markdown("")
# μ΄λ²€νΈ μ°κ²° login_btn.click(login, inputs=[username_input, password_input], outputs=[login_page, chat_page, sessions_state, username_state, login_message]) signup_btn.click(signup, inputs=[username_input, password_input], outputs=[signup_message]) logout_btn.click(logout, outputs=[login_page, chat_page, sessions_state, username_state, chatbot]) new_btn.click(new_chat, inputs=[sessions_state, username_state], outputs=[current_title, chat_list, chatbot, sessions_state]) msg.submit(send_message, inputs=[msg, chat_list, sessions_state, username_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]) delete_btn.click(delete_chat, inputs=[chat_list, sessions_state, username_state], outputs=[chat_list, chatbot, sessions_state, delete_message]) toggle_list_btn.click(toggle_chat_list, inputs=[chat_list_visible], outputs=[chat_list_visible, chat_list_column])
demo.launch()app.pyAdded+204