Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,156 +1,152 @@
|
|
1 |
import gradio as gr
|
2 |
-
import
|
3 |
import os
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
#
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
"
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
"options": ["Swan Lake", "The Nutcracker", "Sleeping Beauty", "Giselle"],
|
37 |
-
"answer": "The Nutcracker"
|
38 |
-
},
|
39 |
-
{
|
40 |
-
"question": "Which company was the first to use Santa Claus in advertising?",
|
41 |
-
"options": ["Pepsi", "Coca-Cola", "McDonald's", "Walmart"],
|
42 |
-
"answer": "Coca-Cola"
|
43 |
-
},
|
44 |
-
{
|
45 |
-
"question": "What is the most popular Christmas dinner in Japan?",
|
46 |
-
"options": ["Turkey", "Ham", "KFC Chicken", "Roast Beef"],
|
47 |
-
"answer": "KFC Chicken"
|
48 |
-
}
|
49 |
-
]
|
50 |
-
|
51 |
-
# Initialize the Stable Diffusion pipeline if available
|
52 |
-
if STABLE_DIFFUSION_AVAILABLE:
|
53 |
-
model_id = "runwayml/stable-diffusion-v1-5"
|
54 |
-
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float32)
|
55 |
-
|
56 |
-
def generate_image(prompt):
|
57 |
-
if not STABLE_DIFFUSION_AVAILABLE:
|
58 |
return None
|
59 |
-
with torch.no_grad():
|
60 |
-
image = pipe(prompt, num_inference_steps=50).images[0]
|
61 |
-
return image
|
62 |
-
|
63 |
-
def get_gpt_response(prompt, history):
|
64 |
-
if not USE_GPT:
|
65 |
-
return "I'm sorry, but I'm currently operating with limited capabilities. I can still help with the Christmas quiz and card generation!"
|
66 |
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
|
|
|
|
74 |
|
75 |
-
|
76 |
-
response
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
return
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
return "I'm sorry,
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
|
|
|
|
141 |
return "", history + [[user_message, None]]
|
142 |
-
|
143 |
-
def
|
144 |
-
bot_message =
|
145 |
-
history[-1][1] = bot_message
|
146 |
if isinstance(bot_message, tuple):
|
|
|
147 |
return history, bot_message[1]
|
|
|
148 |
return history, None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
149 |
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
)
|
154 |
-
clear.click(lambda: None, None, chatbot, queue=False)
|
155 |
-
|
156 |
-
demo.launch()
|
|
|
1 |
import gradio as gr
|
2 |
+
from typing import List, Tuple, Optional, Union
|
3 |
import os
|
4 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
5 |
+
import torch
|
6 |
+
|
7 |
+
class ChristmasBot:
|
8 |
+
def __init__(self, model_name: str = "TheBloke/Mistral-7B-v0.1-GGUF"):
|
9 |
+
"""
|
10 |
+
Initialize the Christmas chatbot with a Hugging Face model.
|
11 |
+
Default model is Mistral-7B, but you can change it to any other model.
|
12 |
+
"""
|
13 |
+
self.stable_diffusion_available = False
|
14 |
+
|
15 |
+
# Initialize the model and tokenizer
|
16 |
+
print("Loading model and tokenizer...")
|
17 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
|
18 |
+
self.model = AutoModelForCausalLM.from_pretrained(
|
19 |
+
model_name,
|
20 |
+
torch_dtype=torch.float16,
|
21 |
+
device_map="auto",
|
22 |
+
load_in_8bit=True # Enable 8-bit quantization for memory efficiency
|
23 |
+
)
|
24 |
+
print("Model loaded successfully!")
|
25 |
+
|
26 |
+
# System prompt to give the model Christmas context
|
27 |
+
self.system_prompt = """You are Holly, a cheerful Christmas helper chatbot.
|
28 |
+
You love everything about Christmas and respond in a warm, festive manner.
|
29 |
+
Keep your responses concise but friendly.
|
30 |
+
If users ask about sensitive topics, guide the conversation back to Christmas-related subjects."""
|
31 |
+
|
32 |
+
def _generate_image(self, prompt: str) -> Optional[str]:
|
33 |
+
"""Placeholder for image generation functionality."""
|
34 |
+
if not self.stable_diffusion_available:
|
35 |
+
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
36 |
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
37 |
|
38 |
+
def _format_chat_history(self, history: List[List[str]]) -> str:
|
39 |
+
"""Format the chat history into a single string for the model."""
|
40 |
+
formatted_history = self.system_prompt + "\n\n"
|
41 |
+
for user_msg, bot_msg in history:
|
42 |
+
if user_msg:
|
43 |
+
formatted_history += f"User: {user_msg}\n"
|
44 |
+
if bot_msg:
|
45 |
+
formatted_history += f"Assistant: {bot_msg}\n"
|
46 |
+
return formatted_history
|
47 |
|
48 |
+
def _get_llm_response(self, message: str, history: List[List[str]]) -> str:
|
49 |
+
"""Generate response using the Hugging Face model."""
|
50 |
+
try:
|
51 |
+
# Format the conversation history with the new message
|
52 |
+
chat_history = self._format_chat_history(history)
|
53 |
+
prompt = f"{chat_history}User: {message}\nAssistant:"
|
54 |
+
|
55 |
+
# Tokenize input
|
56 |
+
inputs = self.tokenizer(prompt, return_tensors="pt", truncation=True, max_length=1024)
|
57 |
+
inputs = inputs.to(self.model.device)
|
58 |
+
|
59 |
+
# Generate response
|
60 |
+
outputs = self.model.generate(
|
61 |
+
inputs["input_ids"],
|
62 |
+
max_length=2048,
|
63 |
+
temperature=0.7,
|
64 |
+
top_p=0.9,
|
65 |
+
repetition_penalty=1.2,
|
66 |
+
do_sample=True,
|
67 |
+
num_return_sequences=1,
|
68 |
+
pad_token_id=self.tokenizer.eos_token_id
|
69 |
+
)
|
70 |
+
|
71 |
+
# Decode and clean up the response
|
72 |
+
response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
73 |
+
response = response.split("Assistant:")[-1].strip()
|
74 |
+
|
75 |
+
return response
|
76 |
+
|
77 |
+
except Exception as e:
|
78 |
+
print(f"Error generating response: {e}")
|
79 |
+
return "Ho ho ho! I seem to be having trouble with my Christmas magic. Could you try asking me something else?"
|
80 |
+
|
81 |
+
def process_message(self, message: str, history: List[List[str]]) -> Union[str, Tuple[str, str]]:
|
82 |
+
"""Process user message and return appropriate response."""
|
83 |
+
# Initial greeting
|
84 |
+
if not history:
|
85 |
+
return "Ho ho ho! Merry Christmas! I'm Holly, your Christmas helper. Would you like to create a Christmas card or chat about the holidays?"
|
86 |
+
|
87 |
+
message = message.lower()
|
88 |
+
last_response = history[-1][1].lower() if history else ""
|
89 |
+
|
90 |
+
# Handle card creation request
|
91 |
+
if "card" in message:
|
92 |
+
if self.stable_diffusion_available:
|
93 |
+
return "Wonderful! Let's create a Christmas card. Please describe the scene you'd like on your card, and I'll generate it for you using AI."
|
94 |
+
return "I'm sorry, but the card generation feature is currently unavailable. Let's chat about Christmas instead!"
|
95 |
+
|
96 |
+
# Handle card generation
|
97 |
+
if "card" in last_response and self.stable_diffusion_available:
|
98 |
+
image = self._generate_image(f"Christmas card scene: {message}")
|
99 |
+
if image:
|
100 |
+
return (
|
101 |
+
f"I've created a Christmas card based on your description: '{message}'. "
|
102 |
+
f"Would you like to create another card or chat about something else?",
|
103 |
+
image
|
104 |
+
)
|
105 |
+
return "I'm sorry, I couldn't generate the image. Would you like to try again or chat about something else?"
|
106 |
+
|
107 |
+
# Default to LLM response for all other messages
|
108 |
+
return self._get_llm_response(message, history)
|
109 |
+
|
110 |
+
def create_gradio_interface() -> gr.Blocks:
|
111 |
+
"""Create and configure the Gradio interface."""
|
112 |
+
# You can change the model here
|
113 |
+
bot = ChristmasBot(model_name="TheBloke/Mistral-7B-v0.1-GGUF")
|
114 |
+
|
115 |
+
def user(user_message: str, history: List[List[str]]) -> Tuple[str, List[List[str]]]:
|
116 |
return "", history + [[user_message, None]]
|
117 |
+
|
118 |
+
def bot_response(history: List[List[str]]) -> Tuple[List[List[str]], Optional[str]]:
|
119 |
+
bot_message = bot.process_message(history[-1][0], history[:-1])
|
|
|
120 |
if isinstance(bot_message, tuple):
|
121 |
+
history[-1][1] = bot_message[0]
|
122 |
return history, bot_message[1]
|
123 |
+
history[-1][1] = bot_message
|
124 |
return history, None
|
125 |
+
|
126 |
+
with gr.Blocks() as demo:
|
127 |
+
gr.Markdown("# π Christmas Chatbot & Card Generator π
")
|
128 |
+
gr.Markdown("""
|
129 |
+
Welcome to the Christmas Chatbot!
|
130 |
+
- Chat about anything Christmas-related
|
131 |
+
- Type 'card' to create a custom Christmas card
|
132 |
+
""")
|
133 |
+
|
134 |
+
chatbot = gr.Chatbot()
|
135 |
+
msg = gr.Textbox(
|
136 |
+
label="Type your message here",
|
137 |
+
placeholder="Ask me anything about Christmas or request a card!",
|
138 |
+
show_label=True
|
139 |
+
)
|
140 |
+
clear = gr.Button("Clear Chat")
|
141 |
+
image_output = gr.Image(label="Generated Card")
|
142 |
+
|
143 |
+
msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
|
144 |
+
bot_response, chatbot, [chatbot, image_output]
|
145 |
+
)
|
146 |
+
clear.click(lambda: None, None, chatbot, queue=False)
|
147 |
+
|
148 |
+
return demo
|
149 |
|
150 |
+
if __name__ == "__main__":
|
151 |
+
demo = create_gradio_interface()
|
152 |
+
demo.launch()
|
|
|
|
|
|
|
|