BlockAI / app.py
catalinulwu1234's picture
Update app.py
58168cf verified
Raw History Blame Contribute Delete
10.2 kB
import gradio as gr
from huggingface_hub import InferenceClient
# Custom CSS for cool animations and modern design
custom_css = """
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap');
:root {
--primary: #6366f1;
--primary-dark: #4f46e5;
--secondary: #ec4899;
--background: #0f172a;
--surface: #1e293b;
--text: #f1f5f9;
--text-secondary: #94a3b8;
}
body {
font-family: 'Poppins', sans-serif;
background: linear-gradient(135deg, #0f172a 0%, #1e1b4b 100%);
margin: 0;
padding: 0;
}
.gradio-container {
background: transparent !important;
}
.dark .block {
background: var(--surface) !important;
border: 1px solid #334155 !important;
border-radius: 16px !important;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3) !important;
}
.sidebar {
background: linear-gradient(180deg, var(--surface) 0%, rgba(30, 41, 59, 0.9) 100%) !important;
border-right: 1px solid #334155 !important;
}
.chatbot {
background: linear-gradient(135deg, var(--surface) 0%, #1e293b 100%) !important;
border: 1px solid #334155 !important;
border-radius: 16px !important;
min-height: 500px;
}
.message.user {
background: linear-gradient(135deg, var(--primary) 0%, var(--primary-dark) 100%) !important;
color: white !important;
border-radius: 18px 18px 4px 18px !important;
margin: 8px 0 !important;
padding: 12px 16px !important;
animation: slideInRight 0.3s ease-out;
}
.message.bot {
background: linear-gradient(135deg, #374151 0%, #4b5563 100%) !important;
color: var(--text) !important;
border-radius: 18px 18px 18px 4px !important;
margin: 8px 0 !important;
padding: 12px 16px !important;
animation: slideInLeft 0.3s ease-out;
}
.textbox {
border-radius: 12px !important;
border: 1px solid #334155 !important;
background: var(--surface) !important;
color: var(--text) !important;
}
.button {
background: linear-gradient(135deg, var(--primary) 0%, var(--primary-dark) 100%) !important;
border: none !important;
border-radius: 12px !important;
color: white !important;
font-weight: 500 !important;
transition: all 0.3s ease !important;
}
.button:hover {
transform: translateY(-2px) !important;
box-shadow: 0 8px 25px rgba(99, 102, 241, 0.4) !important;
}
.slider {
background: var(--surface) !important;
}
.login-button {
background: linear-gradient(135deg, var(--secondary) 0%, #db2777 100%) !important;
border: none !important;
border-radius: 12px !important;
color: white !important;
}
@keyframes slideInRight {
from {
opacity: 0;
transform: translateX(30px);
}
to {
opacity: 1;
transform: translateX(0);
}
}
@keyframes slideInLeft {
from {
opacity: 0;
transform: translateX(-30px);
}
to {
opacity: 1;
transform: translateX(0);
}
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
.gradio-container {
animation: fadeIn 1s ease-in;
}
.typing-dots {
display: inline-block;
}
.typing-dots::after {
content: '...';
animation: typing 1.5s infinite;
}
@keyframes typing {
0%, 20% { content: '.'; }
40% { content: '..'; }
60%, 100% { content: '...'; }
}
/* Header styling */
.header {
text-align: center;
padding: 20px;
background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
/* Sidebar content styling */
.sidebar-content {
padding: 20px;
}
.sidebar-content h1 {
color: var(--text);
font-size: 24px;
margin-bottom: 20px;
}
.sidebar-content h3 {
color: var(--text-secondary);
font-size: 16px;
margin-top: 20px;
}
.warning-message {
background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
color: white;
padding: 12px;
border-radius: 12px;
margin: 10px 0;
text-align: center;
animation: pulse 2s infinite;
}
.success-message {
background: linear-gradient(135deg, #10b981 0%, #059669 100%);
color: white;
padding: 12px;
border-radius: 12px;
margin: 10px 0;
text-align: center;
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.8; }
}
.login-status {
min-height: 60px;
display: flex;
align-items: center;
justify-content: center;
}
"""
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
"""
if not hf_token:
yield "πŸ” Please login with your Hugging Face token to start chatting! Click the login button in the sidebar."
return
try:
client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
messages = [{"role": "system", "content": system_message}]
messages.extend(history)
messages.append({"role": "user", "content": message})
response = ""
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
response += token
yield response
except Exception as e:
yield f"❌ Error: {str(e)}"
# Enhanced system message for helpful assistance
system_message = """You are a helpful and friendly AI assistant. Your purpose is to understand user needs and provide useful, accurate assistance. Be conversational, supportive, and focus on being genuinely helpful in any situation. Keep responses clear and practical."""
# Create the main interface
with gr.Blocks(
css=custom_css,
theme=gr.themes.Soft(primary_hue="indigo", secondary_hue="pink"),
title="πŸ€– AI Assistant"
) as demo:
gr.Markdown("""
<div class="header">
<h1>πŸ€– AI Assistant</h1>
<p>Welcome! I'm here to help you with anything you need. Ask me questions, seek advice, or just chat!</p>
</div>
""")
with gr.Row():
with gr.Column(scale=1, min_width=280):
# Sidebar content
gr.Markdown("""
<div class="sidebar-content">
<h1>🎯 Settings</h1>
</div>
""")
# Login section
gr.Markdown("### πŸ” Authentication")
login_btn = gr.LoginButton()
# Login status display
login_status = gr.Markdown(
"""
<div class="warning-message">
πŸ” Please login to use the AI assistant
</div>
""",
elem_classes="login-status"
)
# Settings
gr.Markdown("### βš™οΈ Parameters")
system_input = gr.Textbox(
value=system_message,
label="πŸ€– System Role",
lines=3,
interactive=True
)
max_tokens_input = gr.Slider(
minimum=1,
maximum=2048,
value=512,
step=1,
label="πŸ“Š Max Tokens"
)
temperature_input = gr.Slider(
minimum=0.1,
maximum=4.0,
value=0.7,
step=0.1,
label="🌑️ Temperature"
)
top_p_input = gr.Slider(
minimum=0.1,
maximum=1.0,
value=0.95,
step=0.05,
label="🎯 Top-p (nucleus sampling)",
)
gr.Markdown("""
<div class="sidebar-content">
<h3>πŸ’‘ Tips</h3>
<ul style="color: var(--text-secondary); font-size: 14px;">
<li>Higher temperature = more creative</li>
<li>Lower temperature = more focused</li>
<li>Adjust max tokens for response length</li>
<li>Login with Hugging Face token required</li>
</ul>
</div>
""")
with gr.Column(scale=4):
# Chat interface without examples to avoid caching issues
chatbot = gr.ChatInterface(
respond,
type="messages",
additional_inputs=[
system_input,
max_tokens_input,
temperature_input,
top_p_input
],
submit_btn="πŸš€ Send",
title=None, # We already have our own title
description=None # We already have our own description
)
# JavaScript to update login status
demo.load(
None,
None,
None,
js="""
() => {
// Check if user is logged in on page load
const checkLogin = () => {
const token = localStorage.getItem('oauth-token');
const statusEl = document.querySelector('.login-status');
if (token && statusEl) {
statusEl.innerHTML = '<div class="success-message">βœ… Successfully logged in! You can now chat with the AI.</div>';
}
};
// Check initially
checkLogin();
// Set up interval to check for login status changes
setInterval(checkLogin, 1000);
}
"""
)
if __name__ == "__main__":
demo.launch(
show_api=False,
share=False,
server_name="0.0.0.0",
server_port=7860
)