Update app.py
Browse files
app.py
CHANGED
|
@@ -1,64 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
from huggingface_hub import InferenceClient
|
| 3 |
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
def respond(
|
| 11 |
-
message,
|
| 12 |
history: list[tuple[str, str]],
|
| 13 |
-
system_message,
|
| 14 |
-
max_tokens,
|
| 15 |
-
temperature,
|
| 16 |
-
top_p,
|
| 17 |
):
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
|
|
|
| 25 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
messages.append({"role": "user", "content": message})
|
| 27 |
|
|
|
|
| 28 |
response = ""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
top_p=top_p,
|
| 36 |
-
):
|
| 37 |
-
token = message.choices[0].delta.content
|
| 38 |
-
|
| 39 |
-
response += token
|
| 40 |
-
yield response
|
| 41 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
demo = gr.ChatInterface(
|
| 47 |
-
respond,
|
| 48 |
-
additional_inputs=[
|
| 49 |
-
gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
|
| 50 |
-
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
|
| 51 |
-
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
| 52 |
-
gr.Slider(
|
| 53 |
-
minimum=0.1,
|
| 54 |
-
maximum=1.0,
|
| 55 |
-
value=0.95,
|
| 56 |
-
step=0.05,
|
| 57 |
-
label="Top-p (nucleus sampling)",
|
| 58 |
-
),
|
| 59 |
-
],
|
| 60 |
-
)
|
| 61 |
|
|
|
|
| 62 |
|
| 63 |
if __name__ == "__main__":
|
| 64 |
-
demo
|
|
|
|
|
|
| 1 |
+
# app.py
|
| 2 |
+
# suppress warnings
|
| 3 |
+
import warnings
|
| 4 |
+
warnings.filterwarnings("ignore")
|
| 5 |
+
|
| 6 |
+
# import libraries
|
| 7 |
+
from dotenv import load_dotenv
|
| 8 |
+
import os
|
| 9 |
import gradio as gr
|
| 10 |
from huggingface_hub import InferenceClient
|
| 11 |
|
| 12 |
+
# Load environment variables
|
| 13 |
+
load_dotenv() # Load from environment or Spaces secrets
|
| 14 |
+
|
| 15 |
+
# Get the Hugging Face API key
|
| 16 |
+
HUGGINGFACE_API_KEY = os.getenv("HUGGINGFACE_API_KEY")
|
| 17 |
+
if not HUGGINGFACE_API_KEY:
|
| 18 |
+
raise ValueError("HUGGINGFACE_API_KEY is not set in environment variables or Spaces secrets")
|
| 19 |
+
|
| 20 |
+
# Initialize the Hugging Face Inference Client
|
| 21 |
+
client = InferenceClient(model="HuggingFaceH4/zephyr-7b-beta", token=HUGGINGFACE_API_KEY)
|
| 22 |
|
| 23 |
+
# Load personality context for RAG
|
| 24 |
+
PERSONALITY_FILE = "personality.txt" # Relative path for Spaces
|
| 25 |
+
try:
|
| 26 |
+
with open(PERSONALITY_FILE, "r") as f:
|
| 27 |
+
personality_context = f.read()
|
| 28 |
+
except FileNotFoundError:
|
| 29 |
+
personality_context = "Default personality: A friendly and witty chatbot with a passion for horror and gaming."
|
| 30 |
+
warnings.warn(f"Personality file not found at {PERSONALITY_FILE}. Using default personality.")
|
| 31 |
|
| 32 |
def respond(
|
| 33 |
+
message: str,
|
| 34 |
history: list[tuple[str, str]],
|
| 35 |
+
system_message: str,
|
| 36 |
+
max_tokens: int,
|
| 37 |
+
temperature: float,
|
| 38 |
+
top_p: float,
|
| 39 |
):
|
| 40 |
+
"""
|
| 41 |
+
Generate a response using the Hugging Face Inference API with RAG to enforce
|
| 42 |
+
the ZombieSlayerBot personality defined in personality.txt.
|
| 43 |
+
"""
|
| 44 |
+
if not message.strip():
|
| 45 |
+
return "Please say something, survivor! The zombies are waiting!"
|
| 46 |
|
| 47 |
+
# Handle greetings explicitly
|
| 48 |
+
message_lower = message.lower().strip()
|
| 49 |
+
greetings = ["hi", "hello", "hey", "good morning", "good afternoon"]
|
| 50 |
+
if any(greeting in message_lower for greeting in greetings):
|
| 51 |
+
yield "Yo, survivor! Ready to dive into the zombie-infested chaos of Raccoon City? What's up?"
|
| 52 |
+
return
|
| 53 |
|
| 54 |
+
# Combine system message with personality context
|
| 55 |
+
full_system_message = (
|
| 56 |
+
f"{system_message}\n\n"
|
| 57 |
+
"Follow this personality profile in all responses:\n"
|
| 58 |
+
f"{personality_context}\n\n"
|
| 59 |
+
"Use the conversation history and the user's message to generate a response that aligns with the personality."
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
# Build the conversation history
|
| 63 |
+
messages = [{"role": "system", "content": full_system_message}]
|
| 64 |
+
for user_msg, bot_msg in history:
|
| 65 |
+
if user_msg:
|
| 66 |
+
messages.append({"role": "user", "content": user_msg})
|
| 67 |
+
if bot_msg:
|
| 68 |
+
messages.append({"role": "assistant", "content": bot_msg})
|
| 69 |
messages.append({"role": "user", "content": message})
|
| 70 |
|
| 71 |
+
# Stream response from Hugging Face Inference API
|
| 72 |
response = ""
|
| 73 |
+
try:
|
| 74 |
+
for message_chunk in client.chat_completion(
|
| 75 |
+
messages,
|
| 76 |
+
max_tokens=max_tokens,
|
| 77 |
+
stream=True,
|
| 78 |
+
temperature=temperature,
|
| 79 |
+
top_p=top_p,
|
| 80 |
+
):
|
| 81 |
+
token = message_chunk.choices[0].delta.content or ""
|
| 82 |
+
response += token
|
| 83 |
+
yield response
|
| 84 |
+
except Exception as e:
|
| 85 |
+
yield f"Error in the apocalypse: {str(e)}. Try again, survivor!"
|
| 86 |
|
| 87 |
+
# Create the Gradio interface
|
| 88 |
+
def create_chatbot():
|
| 89 |
+
with gr.Blocks(title="ZombieSlayerBot") as demo:
|
| 90 |
+
gr.Markdown("# 🧟♂️ ZombieSlayerBot")
|
| 91 |
+
gr.Markdown("Welcome, survivor! I'm ZombieSlayerBot, your guide through the zombie-infested world of Resident Evil. Powered by Hugging Face's Zephyr-7B-Beta. Let’s lock and load—chat with me!")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
|
| 93 |
+
# Chat interface
|
| 94 |
+
chat_interface = gr.ChatInterface(
|
| 95 |
+
fn=respond,
|
| 96 |
+
chatbot=gr.Chatbot(height=400, show_label=False, container=True),
|
| 97 |
+
textbox=gr.Textbox(placeholder="Type your message here, survivor...", container=False, scale=4),
|
| 98 |
+
additional_inputs=[
|
| 99 |
+
gr.Textbox(value="You are ZombieSlayerBot, a witty and bold chatbot obsessed with Resident Evil.", label="System message"),
|
| 100 |
+
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
|
| 101 |
+
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
| 102 |
+
gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)"),
|
| 103 |
+
],
|
| 104 |
+
submit_btn=gr.Button("Send", variant="primary"),
|
| 105 |
+
)
|
| 106 |
|
| 107 |
+
# Separate clear button
|
| 108 |
+
clear_btn = gr.Button("Clear Chat", variant="secondary")
|
| 109 |
+
clear_btn.click(lambda: None, None, chat_interface.chatbot, queue=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
|
| 111 |
+
return demo
|
| 112 |
|
| 113 |
if __name__ == "__main__":
|
| 114 |
+
demo = create_chatbot()
|
| 115 |
+
demo.launch(debug=False) # Compatible with Spaces
|