Spaces:
Runtime error
Runtime error
Update app.py
Browse files123456728910111213141556789101112131415161716171819192021222321242526272829303132332334353637382539404142434427282930313233343536374546474849505152535439405556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093104445464748495051525354555657585960616263646531131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482569826827import osimport jsonimport hashlibimport uuidfrom datetime import datetimefrom pathlib import Pathimport gradio as grfrom huggingface_hub import InferenceClientimport requests
# ConfigurationACCOUNTS_DIR = Path("accounts")CHATS_DIR = Path("chats")ACCOUNTS_DIR.mkdir(exist_ok=True)CHATS_DIR.mkdir(exist_ok=True)
def respond( message, history: list[dict[str, str]], system_message, max_tokens, temperature, top_p, hf_token: gr.OAuthToken,): """ For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference """ client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")# NVIDIA API ConfigurationNVIDIA_API_KEY = "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"NVIDIA_BASE_URL = "https://integrate.api.nvidia.com/v1"
messages = [{"role": "system", "content": system_message}]# Model configurationsCHAT_MODEL = "qwen/qwen2.5-coder-32b-instruct"CODING_MODEL = "qwen/qwen3-235b-a22b"
messages.extend(history)# Custom CSS for ultra modern dark UICUSTOM_CSS = """/* Global Styles */.gradio-container { max-width: 100% !important; padding: 0 !important; background: linear-gradient(135deg, #0f0f1a 0%, #1a1a2e 50%, #16213e 100%) !important; min-height: 100vh;}
messages.append({"role": "user", "content": message})/* Hide default Gradio elements */.prose, .gradio-container > .flex > .prose { display: none !important;}
response = ""/* Main container */.contain { padding: 0 !important; max-width: 100% !important;}
for message in client.chat_completion( messages, max_tokens=max_tokens, stream=True, temperature=temperature, top_p=top_p, ): choices = message.choices token = "" if len(choices) and choices[0].delta.content: token = choices[0].delta.content/* Auth container styling */.auth-box { background: rgba(26, 26, 46, 0.95) !important; border: 1px solid rgba(99, 102, 241, 0.3) !important; border-radius: 20px !important; padding: 30px !important; box-shadow: 0 25px 50px rgba(0, 0, 0, 0.5), 0 0 100px rgba(99, 102, 241, 0.1) !important; backdrop-filter: blur(20px) !important;}
response += token yield response/* Input styling */.input-box input, .input-box textarea { background: rgba(15, 15, 26, 0.8) !important; border: 1px solid rgba(99, 102, 241, 0.3) !important; border-radius: 12px !important; color: #f8fafc !important; font-size: 15px !important; padding: 14px 18px !important; transition: all 0.3s ease !important;}
.input-box input:focus, .input-box textarea:focus { border-color: #6366f1 !important; box-shadow: 0 0 20px rgba(99, 102, 241, 0.3) !important;}
.input-box input::placeholder, .input-box textarea::placeholder { color: #64748b !important;}
/* Button styling */.primary-btn { background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 50%, #a855f7 100%) !important; border: none !important; border-radius: 12px !important; color: white !important; font-weight: 600 !important; padding: 14px 28px !important; font-size: 15px !important; transition: all 0.3s ease !important; box-shadow: 0 4px 15px rgba(99, 102, 241, 0.4) !important;}
.primary-btn:hover { transform: translateY(-2px) !important; box-shadow: 0 8px 25px rgba(99, 102, 241, 0.5) !important;}
.secondary-btn { background: rgba(99, 102, 241, 0.1) !important; border: 1px solid rgba(99, 102, 241, 0.3) !important; border-radius: 12px !important; color: #a5b4fc !important; font-weight: 500 !important; padding: 12px 24px !important; transition: all 0.3s ease !important;}
.secondary-btn:hover { background: rgba(99, 102, 241, 0.2) !important; border-color: #6366f1 !important;}
.danger-btn { background: rgba(239, 68, 68, 0.1) !important; border: 1px solid rgba(239, 68, 68, 0.3) !important; border-radius: 10px !important; color: #f87171 !important; font-weight: 500 !important; padding: 10px 20px !important; transition: all 0.3s ease !important;}
.danger-btn:hover { background: rgba(239, 68, 68, 0.2) !important; border-color: #ef4444 !important;}
/* Chat container */.chat-container { background: rgba(15, 15, 26, 0.6) !important; border: 1px solid rgba(99, 102, 241, 0.2) !important; border-radius: 16px !important; overflow: hidden !important;}
/* Message styling */.message.user { background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%) !important; border-radius: 18px 18px 4px 18px !important; color: white !important; padding: 14px 18px !important; margin: 8px 0 !important; max-width: 80% !important; margin-left: auto !important; box-shadow: 0 4px 15px rgba(99, 102, 241, 0.3) !important;}
.message.bot { background: rgba(30, 30, 50, 0.8) !important; border: 1px solid rgba(99, 102, 241, 0.2) !important; border-radius: 18px 18px 18px 4px !important; color: #f8fafc !important; padding: 14px 18px !important; margin: 8px 0 !important; max-width: 80% !important;}
/* Chat input */.chat-input textarea { background: rgba(15, 15, 26, 0.9) !important; border: 1px solid rgba(99, 102, 241, 0.3) !important; border-radius: 16px !important; color: #f8fafc !important; min-height: 120px !important; max-height: 200px !important; padding: 16px 20px !important; font-size: 15px !important; line-height: 1.6 !important; resize: none !important;}
.chat-input textarea:focus { border-color: #6366f1 !important; box-shadow: 0 0 30px rgba(99, 102, 241, 0.2) !important;}
/* Dropdown styling */.dropdown select { background: rgba(15, 15, 26, 0.9) !important; border: 1px solid rgba(99, 102, 241, 0.3) !important; border-radius: 10px !important; color: #f8fafc !important; padding: 10px 16px !important; font-size: 14px !important;}
/* Radio button styling */.radio-group label { background: rgba(15, 15, 26, 0.6) !important; border: 1px solid rgba(99, 102, 241, 0.2) !important; border-radius: 10px !important; color: #94a3b8 !important; padding: 10px 16px !important; transition: all 0.3s ease !important;}
.radio-group label.selected { background: linear-gradient(135deg, rgba(99, 102, 241, 0.3) 0%, rgba(139, 92, 246, 0.3) 100%) !important; border-color: #6366f1 !important; color: #f8fafc !important;}
/* Chat list */.chat-list-item { background: rgba(15, 15, 26, 0.4) !important; border: 1px solid rgba(99, 102, 241, 0.1) !important; border-radius: 12px !important; padding: 12px 16px !important; margin: 6px 0 !important; cursor: pointer !important; transition: all 0.3s ease !important;}
.chat-list-item:hover { background: rgba(99, 102, 241, 0.1) !important; border-color: rgba(99, 102, 241, 0.3) !important;}
.chat-list-item.active { background: linear-gradient(135deg, rgba(99, 102, 241, 0.2) 0%, rgba(139, 92, 246, 0.2) 100%) !important; border-color: #6366f1 !important;}
/* Title styling */.title-text { background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 50%, #a855f7 100%) !important; -webkit-background-clip: text !important; -webkit-text-fill-color: transparent !important; background-clip: text !important; font-size: 28px !important; font-weight: 700 !important;}
/* Status text */.status-text { color: #22c55e !important; font-size: 13px !important;}
.error-text { color: #ef4444 !important; font-size: 14px !important; background: rgba(239, 68, 68, 0.1) !important; padding: 10px 16px !important; border-radius: 10px !important; border: 1px solid rgba(239, 68, 68, 0.2) !important;}
.success-text { color: #22c55e !important; font-size: 14px !important; background: rgba(34, 197, 94, 0.1) !important; padding: 10px 16px !important; border-radius: 10px !important; border: 1px solid rgba(34, 197, 94, 0.2) !important;}
/* Scrollbar */::-webkit-scrollbar { width: 6px;}
::-webkit-scrollbar-track { background: transparent;}
::-webkit-scrollbar-thumb { background: rgba(99, 102, 241, 0.3); border-radius: 3px;}
::-webkit-scrollbar-thumb:hover { background: rgba(99, 102, 241, 0.5);}
/* User info */.user-badge { background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%) !important; border-radius: 12px !important; padding: 8px 16px !important; color: white !important; font-weight: 500 !important;}
/* Mode selector */.mode-selector { background: rgba(15, 15, 26, 0.6) !important; border: 1px solid rgba(99, 102, 241, 0.2) !important; border-radius: 12px !important; padding: 16px !important;}
/* Animation */@keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); }}
.fade-in { animation: fadeIn 0.3s ease !important;}
/* Loading dots */.loading-dots::after { content: '...'; animation: dots 1.5s steps(4, end) infinite;}
@keyframes dots { 0%, 20% { content: ''; } 40% { content: '.'; } 60% { content: '..'; } 80%, 100% { content: '...'; }}"""For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface"""chatbot = gr.ChatInterface( respond, additional_inputs=[ gr.Textbox(value="You are a friendly Chatbot.", label="System message"), gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"), gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"), gr.Slider( minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)", ), ],)
with gr.Blocks() as demo: with gr.Sidebar(): gr.LoginButton() chatbot.render()
def hash_password(password: str) -> str: """Hash password using SHA-256""" return hashlib.sha256(password.encode()).hexdigest()
def get_user_file(username: str) -> Path: """Get the user's account file path""" return ACCOUNTS_DIR / f"{username}.json"
def get_user_chats_dir(username: str) -> Path: """Get the user's chats directory""" user_dir = CHATS_DIR / username user_dir.mkdir(exist_ok=True, parents=True) return user_dir
def register_user(username: str, password: str) -> tuple[bool, str]: """Register a new user""" if not username or not password: return False, "Username and password are required" if len(username) < 3: return False, "Username must be at least 3 characters" if len(password) < 6: return False, "Password must be at least 6 characters" user_file = get_user_file(username) if user_file.exists(): return False, "Username already exists" user_data = { "username": username, "password": hash_password(password), "created_at": datetime.now().isoformat() } with open(user_file, 'w') as f: json.dump(user_data, f, indent=2) get_user_chats_dir(username) return True, "Registration successful! Please login."
def login_user(username: str, password: str) -> tuple[bool, str]: """Login a user""" if not username or not password: return False, "Username and password are required" user_file = get_user_file(username) if not user_file.exists(): return False, "User not found" with open(user_file, 'r') as f: user_data = json.load(f) if user_data["password"] != hash_password(password): return False, "Invalid password" return True, f"Welcome back, {username}!"
def create_chat(username: str, title: str = "New Chat") -> dict: """Create a new chat for a user""" chat_id = str(uuid.uuid4())[:8] chat_data = { "id": chat_id, "title": title, "created_at": datetime.now().isoformat(), "messages": [] } chats_dir = get_user_chats_dir(username) chat_file = chats_dir / f"{chat_id}.json" with open(chat_file, 'w') as f: json.dump(chat_data, f, indent=2) return chat_data
def get_user_chats(username: str) -> list[dict]: """Get all chats for a user""" chats_dir = get_user_chats_dir(username) chats = [] for chat_file in chats_dir.glob("*.json"): with open(chat_file, 'r') as f: chat_data = json.load(f) chats.append(chat_data) chats.sort(key=lambda x: x["created_at"], reverse=True) return chats
def get_chat(username: str, chat_id: str) -> dict | None: """Get a specific chat""" chats_dir = get_user_chats_dir(username) chat_file = chats_dir / f"{chat_id}.json" if not chat_file.exists(): return None with open(chat_file, 'r') as f: return json.load(f)
def save_chat(username: str, chat_id: str, chat_data: dict): """Save chat data""" chats_dir = get_user_chats_dir(username) chat_file = chats_dir / f"{chat_id}.json" with open(chat_file, 'w') as f: json.dump(chat_data, f, indent=2)
def delete_chat_file(username: str, chat_id: str): """Delete a chat file""" chats_dir = get_user_chats_dir(username) chat_file = chats_dir / f"{chat_id}.json" if chat_file.exists(): chat_file.unlink()
def stream_nvidia_response(messages: list[dict], mode: str = "chat"): """Stream response from NVIDIA API""" model = CODING_MODEL if mode == "coding" else CHAT_MODEL max_tokens = 8192 if mode == "coding" else 4096 headers = { "Authorization": f"Bearer {NVIDIA_API_KEY}", "Content-Type": "application/json" } payload = { "model": model, "messages": messages, "temperature": 0.2, "top_p": 0.7, "max_tokens": max_tokens, "stream": True } if mode == "coding": payload["chat_template_kwargs"] = {"thinking": False} try: response = requests.post( f"{NVIDIA_BASE_URL}/chat/completions", headers=headers, json=payload, stream=True, timeout=120 ) for line in response.iter_lines(): if line: line = line.decode('utf-8') if line.startswith("data: "): data = line[6:] if data == "[DONE]": break try: chunk = json.loads(data) if chunk.get("choices") and chunk["choices"][0].get("delta", {}).get("content"): yield chunk["choices"][0]["delta"]["content"] except json.JSONDecodeError: continue except Exception as e: yield f"\n[Error: {str(e)}]"
def format_chat_history(messages: list[dict]) -> list: """Format messages for display in Gradio Chatbot""" formatted = [] for msg in messages: role = "user" if msg["role"] == "user" else "assistant" formatted.append([msg["content"] if role == "user" else None, msg["content"] if role == "assistant" else None]) return formatted
# Create the Gradio appdef create_app(): with gr.Blocks(css=CUSTOM_CSS, title="AI Assistant", theme=gr.themes.Soft()) as app: # State variables current_user = gr.State(None) current_chat_id = gr.State(None) chat_history = gr.State([]) # ==================== AUTH SECTION ==================== with gr.Group(visible=True, elem_classes=["auth-box"]) as auth_section: gr.Markdown("# ✨ AI Assistant", elem_classes=["title-text"]) gr.Markdown("Your intelligent conversation partner") with gr.Tabs() as auth_tabs: with gr.Tab("Login", id="login_tab"): login_username = gr.Textbox( label="Username", placeholder="Enter your username", elem_classes=["input-box"] ) login_password = gr.Textbox( label="Password", placeholder="Enter your password", type="password", elem_classes=["input-box"] ) login_btn = gr.Button("Login", variant="primary", elem_classes=["primary-btn"]) login_status = gr.Markdown("", elem_classes=["error-text"]) with gr.Tab("Register", id="register_tab"): reg_username = gr.Textbox( label="Username", placeholder="Choose a username (min 3 characters)", elem_classes=["input-box"] ) reg_password = gr.Textbox( label="Password", placeholder="Choose a password (min 6 characters)", type="password", elem_classes=["input-box"] ) reg_btn = gr.Button("Register", variant="primary", elem_classes=["primary-btn"]) reg_status = gr.Markdown("", elem_classes=["error-text"]) # ==================== MAIN APP SECTION ==================== with gr.Group(visible=False) as main_section: with gr.Row(): # Sidebar with gr.Column(scale=1, min_width=280): with gr.Group(elem_classes=["mode-selector"]): gr.Markdown("### 💬 AI Assistant") user_display = gr.Markdown("", elem_classes=["user-badge"]) gr.Markdown("### 📁 Your Chats") chat_list = gr.Dataset( label="Select a chat", components=["text"], samples=[["No chats yet"]], elem_classes=["chat-list"] ) with gr.Row(): new_chat_btn = gr.Button("➕ New Chat", elem_classes=["secondary-btn"]) delete_chat_btn = gr.Button("🗑️ Delete", elem_classes=["danger-btn"]) logout_btn = gr.Button("Logout", elem_classes=["danger-btn"]) # Main chat area with gr.Column(scale=3): with gr.Group(elem_classes=["chat-container"]): chat_title = gr.Markdown("### Select or create a chat") with gr.Row(): mode_dropdown = gr.Dropdown( choices=[("💬 Chat", "chat"), ("💻 Coding", "coding")], value="chat", label="Mode", interactive=True, elem_classes=["dropdown"] ) current_chat_display = gr.Textbox( value="No chat selected", label="Current Chat", interactive=False ) chatbot = gr.Chatbot( label="Conversation", height=500, show_label=False, elem_classes=["chat-container"], type="messages" ) with gr.Row(): msg_input = gr.Textbox( placeholder="Type your message here... (Press Enter to send, Shift+Enter for new line)", lines=4, max_lines=7, show_label=False, elem_classes=["chat-input"] ) with gr.Row(): send_btn = gr.Button("Send", variant="primary", elem_classes=["primary-btn"]) clear_btn = gr.Button("Clear Display", elem_classes=["secondary-btn"]) # ==================== EVENT HANDLERS ==================== def handle_login(username, password): if not username or not password: return None, None, [], "Please enter username and password", gr.update() success, message = login_user(username, password) if success: chats = get_user_chats(username) chat_samples = [[c["title"]] for c in chats] if chats else [["No chats yet"]] return ( username, None, [], gr.update(visible=False), gr.update(visible=True), gr.update(value=f"**{username}**"), gr.update(samples=chat_samples), "No chat selected", [] ) return None, None, [], message, gr.update(), gr.update(), gr.update(), gr.update(), gr.update() def handle_register(username, password): if not username or not password: return "Please enter username and password" success, message = register_user(username, password) return message def handle_new_chat(username): if not username: return None, "Please login first", gr.update(), [] chat = create_chat(username) chats = get_user_chats(username) chat_samples = [[c["title"]] for c in chats] return ( chat["id"], chat["title"], gr.update(samples=chat_samples), [] ) def handle_select_chat(evt: gr.SelectData, username): if not username: return None, "No chat selected", [], gr.update() chats = get_user_chats(username) if evt.index < len(chats): selected_chat = chats[evt.index] chat_data = get_chat(username, selected_chat["id"]) if chat_data: history = [[m["content"], None] if m["role"] == "user" else [None, m["content"]] for m in chat_data["messages"]] # Convert to messages format msg_history = [] for m in chat_data["messages"]: msg_history.append({"role": m["role"], "content": m["content"]}) return ( selected_chat["id"], selected_chat["title"], msg_history, gr.update(value=msg_history) ) return None, "No chat selected", [], gr.update() def handle_delete_chat(username, chat_id): if username and chat_id: delete_chat_file(username, chat_id) chats = get_user_chats(username) chat_samples = [[c["title"]] for c in chats] if chats else [["No chats yet"]] return None, "No chat selected", [], gr.update(samples=chat_samples), gr.update(value=[]) return chat_id, gr.update(), gr.update(), gr.update(), gr.update() def handle_logout(): return ( None, # current_user None, # current_chat_id [], # chat_history gr.update(visible=True), # auth_section gr.update(visible=False), # main_section gr.update(value=""), # user_display gr.update(samples=[["No chats yet"]]), # chat_list "No chat selected", # current_chat_display gr.update(value=[]), # chatbot "", # login_username "", # login_password "" # login_status ) def handle_message(username, chat_id, history, message, mode): if not username: yield history, "Please login first" return if not chat_id: # Create new chat if none selected chat = create_chat(username) chat_id = chat["id"] if not message or not message.strip(): yield history, chat_id return # Add user message to history user_msg = {"role": "user", "content": message} history = history or [] history.append(user_msg) # Update chatbot display yield history, chat_id # Get chat data and add user message chat_data = get_chat(username, chat_id) if not chat_data: chat_data = {"id": chat_id, "title": "New Chat", "messages": []} chat_data["messages"].append(user_msg) # Update title if first message if len(chat_data["messages"]) == 1: chat_data["title"] = message[:40] + ("..." if len(message) > 40 else "") # Prepare messages for API api_messages = [{"role": m["role"], "content": m["content"]} for m in chat_data["messages"]] # Stream response full_response = "" assistant_msg = {"role": "assistant", "content": ""} for chunk in stream_nvidia_response(api_messages, mode): full_response += chunk assistant_msg["content"] = full_response # Update history with streaming response temp_history = history.copy() temp_history.append(assistant_msg.copy()) yield temp_history, chat_id # Save the complete response chat_data["messages"].append({"role": "assistant", "content": full_response}) save_chat(username, chat_id, chat_data) # Update final history history.append({"role": "assistant", "content": full_response}) yield history, chat_id def clear_chat_display(): return [] # Connect event handlers login_btn.click( handle_login, inputs=[login_username, login_password], outputs=[current_user, current_chat_id, chat_history, login_status, auth_section, main_section, user_display, chat_list, current_chat_display, chatbot] ) reg_btn.click( handle_register, inputs=[reg_username, reg_password], outputs=[reg_status] ) new_chat_btn.click( handle_new_chat, inputs=[current_user], outputs=[current_chat_id, current_chat_display, chat_list, chatbot] ) chat_list.select( handle_select_chat, inputs=[current_user], outputs=[current_chat_id, current_chat_display, chat_history, chatbot] ) delete_chat_btn.click( handle_delete_chat, inputs=[current_user, current_chat_id], outputs=[current_chat_id, current_chat_display, chat_history, chat_list, chatbot] ) logout_btn.click( handle_logout, outputs=[current_user, current_chat_id, chat_history, auth_section, main_section, user_display, chat_list, current_chat_display, chatbot, login_username, login_password, login_status] ) send_btn.click( handle_message, inputs=[current_user, current_chat_id, chat_history, msg_input, mode_dropdown], outputs=[chatbot, current_chat_id] ).then( lambda: "", outputs=[msg_input] ) # Also allow Enter to send msg_input.submit( handle_message, inputs=[current_user, current_chat_id, chat_history, msg_input, mode_dropdown], outputs=[chatbot, current_chat_id] ).then( lambda: "", outputs=[msg_input] ) clear_btn.click( clear_chat_display, outputs=[chatbot] ) return app
if __name__ == "__main__": demo.launch() app = create_app() app.launch(server_name="0.0.0.0", server_port=7860)app.py+812-54