Spaces:
Runtime error
Runtime error
File size: 8,498 Bytes
56da73c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 | import uuid
import json
import urllib.request
import gradio as gr
import os
# ------------------ Firebase Realtime Database URL ------------------
FIREBASE_URL = "https://chatbot-database-af5ef-default-rtdb.firebaseio.com/" # λ³ΈμΈ νλ‘μ νΈ URL
# ------------------ Firebase REST API ------------------
def save_user(username, password):
url = f"{FIREBASE_URL}/users/{username}.json"
data = json.dumps({"password": password}).encode()
req = urllib.request.Request(url, data=data, headers={"Content-Type":"application/json"}, method="PUT")
with urllib.request.urlopen(req) as resp:
return json.loads(resp.read().decode())
def load_users():
url = f"{FIREBASE_URL}/users.json"
try:
with urllib.request.urlopen(url) as resp:
data = json.loads(resp.read().decode())
return {k:v["password"] for k,v in data.items()} if data else {}
except:
return {}
def save_chats(username, sessions_state):
url = f"{FIREBASE_URL}/chats/{username}.json"
data = json.dumps(sessions_state).encode()
req = urllib.request.Request(url, data=data, headers={"Content-Type":"application/json"}, method="PUT")
with urllib.request.urlopen(req) as resp:
return json.loads(resp.read().decode())
def load_chats(username):
url = f"{FIREBASE_URL}/chats/{username}.json"
try:
with urllib.request.urlopen(url) as resp:
return json.loads(resp.read().decode()) or {}
except:
return {}
# ------------------ 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}"
def call_gemini(history):
if not history:
return "μλ
νμΈμ! 무μμ λμλ릴κΉμ?"
contents = [{"role": "user" if h["role"]=="user" else "model",
"parts":[{"text":h["text"]}]} for h in history]
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:
return "β μλ² μ€λ₯"
# ------------------ μ±ν
κ΄λ¦¬ ------------------
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
reply = call_gemini(conv["history"])
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):
users = load_users()
if username in users and users[username] == password:
sessions_state = load_chats(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 "μμ΄λ/λΉλ°λ²νΈ μ
λ ₯ νμ"
users = load_users()
if username in users:
return "μ΄λ―Έ μ‘΄μ¬νλ μμ΄λ"
save_user(username, password)
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()
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, current_title, 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()
|