GeminiFan207's picture
Update app.py
f7d0ff2 verified
import gradio as gr
import requests
from datetime import datetime
import os
# GitHub image URL as chatbot icon
BOT_ICON = "https://raw.githubusercontent.com/GeminiFan207/Secialix_Chatbot/main/IMG_0528-removebg-preview.png"
# Load API token from Hugging Face Spaces secrets
API_TOKEN = os.getenv("HF_API_KEY") # Set this in Spaces Secrets
if not API_TOKEN:
raise ValueError("HF_API_KEY not set in Spaces Secrets. Please configure it in the Space settings.")
API_URL = "https://api-inference.huggingface.co/models/ZeppelinCorp/Charm_15"
headers = {"Authorization": f"Bearer {API_TOKEN}"}
def query_huggingface(payload):
response = requests.post(API_URL, headers=headers, json=payload)
if response.status_code == 200:
return response.json()[0]["generated_text"]
else:
return f"Error: API request failed with status {response.status_code}"
def chatbot_response(user_input):
timestamp = datetime.now().strftime("%H:%M:%S")
# Query the Charm_15 model via Hugging Face API
payload = {
"inputs": user_input,
"parameters": {"max_length": 100, "num_return_sequences": 1}
}
bot_response = query_huggingface(payload)
# Fallback if response is empty or an error
if not bot_response or "Error" in bot_response:
bot_response = f"Failed to generate response. Echo: '{user_input}' at {timestamp}"
else:
bot_response = f"{bot_response} (Generated at {timestamp})"
return [[user_input, bot_response]]
# Custom CSS for circular avatar
custom_css = """
.bot-avatar {
border-radius: 50% !important;
width: 32px !important;
height: 32px !important;
}
"""
# Gradio interface
with gr.Blocks(css=custom_css) as demo:
chatbot = gr.Chatbot(
label="Charm_15 Chatbot Playground",
avatar_images=[None, BOT_ICON], # None for user, GitHub image for bot
bubble_full_width=False
)
msg = gr.Textbox(placeholder="Type your message here...")
submit_btn = gr.Button("Send")
def submit_message(user_input, history=[]):
new_conversation = chatbot_response(user_input)
return history + new_conversation, ""
# Bind submission events
msg.submit(submit_message, [msg, chatbot], [chatbot, msg])
submit_btn.click(submit_message, [msg, chatbot], [chatbot, msg])
# Launch the app (Spaces handles this automatically)
demo.launch()