Spaces:
Runtime error

ChatBot1 / app.py
KevGamerXPlus1's picture
Update app.py
cc6857f verified
Raw History Blame Contribute Delete
27.8 kB
import os
import json
import hashlib
import uuid
from datetime import datetime
from pathlib import Path
import gradio as gr
import requests
# Configuration
ACCOUNTS_DIR = Path("accounts")
CHATS_DIR = Path("chats")
ACCOUNTS_DIR.mkdir(exist_ok=True)
CHATS_DIR.mkdir(exist_ok=True)
# NVIDIA API Configuration
NVIDIA_API_KEY = "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"
NVIDIA_BASE_URL = "https://integrate.api.nvidia.com/v1"
# Model configurations
CHAT_MODEL = "qwen/qwen2.5-coder-32b-instruct"
CODING_MODEL = "qwen/qwen3-235b-a22b"
# Custom CSS for ultra modern dark UI
CUSTOM_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;
}
/* Hide default Gradio elements */
.prose, .gradio-container > .flex > .prose {
display: none !important;
}
/* Main container */
.contain {
padding: 0 !important;
max-width: 100% !important;
}
/* 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;
}
/* 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: '...'; }
}
"""
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 app
def create_app():
with gr.Blocks(title="AI Assistant") 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"]
)
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__":
app = create_app()
app.launch(server_name="0.0.0.0", server_port=7860, css=CUSTOM_CSS, theme=gr.themes.Soft())