Spaces:
Runtime error
Runtime error
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798023 unmodified lines10410510610710810911011111211319 unmodified lines133134135136137138139140141142143144145146147148149150import 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_statewith 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 = {}23 unmodified linesconv["history"].append({"role": "user", "text": user_input})if conv["title"] == "μ μ±ν ":conv["title"] = (user_input[:15] + "β¦") if len(user_input) > 15 else user_inputtry: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})19 unmodified lines# ------------------ λ‘κ·ΈμΈ/νμκ°μ ------------------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] = passwordsave_users()return "νμκ°μ μλ£! λ‘κ·ΈμΈνμΈμ."def logout():1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666723 unmodified lines9192939495969719 unmodified lines117118119120121122123124125126127128129130131132133134135import uuidimport jsonimport urllib.requestimport gradio as grimport 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 = {}23 unmodified linesconv["history"].append({"role": "user", "text": user_input})if conv["title"] == "μ μ±ν ":conv["title"] = (user_input[:15] + "β¦") if len(user_input) > 15 else user_inputreply = 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})19 unmodified lines# ------------------ λ‘κ·ΈμΈ/νμκ°μ ------------------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():
app.py+54-69