Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -2,341 +2,178 @@ import gradio as gr
|
|
2 |
from transformers import AutoTokenizer, AutoModelForCausalLM
|
3 |
import torch
|
4 |
|
5 |
-
# Model configuration
|
6 |
MODEL_NAME = "DarwinAnim8or/TinyRP"
|
7 |
|
8 |
-
#
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
|
24 |
# Sample character presets
|
25 |
-
|
26 |
"Custom Character": "",
|
27 |
-
"Adventurous Knight": "You are Sir Gareth, a brave and noble knight on a quest to save the kingdom. You speak with honor and courage, always ready to help those in need.
|
28 |
-
"Mysterious Wizard": "You are Eldara, an ancient and wise wizard who speaks in riddles and knows secrets of the mystical arts. You
|
29 |
-
"Friendly Tavern Keeper": "You are Bram, a cheerful tavern keeper who loves telling stories and meeting new travelers. Your tavern
|
30 |
-
"Curious Scientist": "You are Dr. Maya Chen, a brilliant scientist
|
31 |
-
"Space Explorer": "You are Captain Nova, a fearless space explorer who has traveled to distant galaxies. You
|
32 |
-
"Fantasy Princess": "You are Princess Lyra, kind-hearted royalty who cares deeply about her people. You're intelligent, diplomatic, and skilled in both politics and magic. You often sneak out of the castle to help citizens in need."
|
33 |
}
|
34 |
|
35 |
-
def
|
36 |
-
"""
|
37 |
-
conversation = ""
|
38 |
-
|
39 |
-
# Add system message if character is defined
|
40 |
-
if character_description.strip():
|
41 |
-
conversation += f"<|im_start|>system\n{character_description.strip()}<|im_end|>\n"
|
42 |
-
|
43 |
-
# Add conversation history
|
44 |
-
for user_msg, assistant_msg in history:
|
45 |
-
if user_msg:
|
46 |
-
conversation += f"<|im_start|>user\n{user_msg}<|im_end|>\n"
|
47 |
-
if assistant_msg:
|
48 |
-
conversation += f"<|im_start|>assistant\n{assistant_msg}<|im_end|>\n"
|
49 |
-
|
50 |
-
# Add current user message
|
51 |
-
conversation += f"<|im_start|>user\n{message}<|im_end|>\n"
|
52 |
-
|
53 |
-
# Start assistant response
|
54 |
-
conversation += "<|im_start|>assistant\n"
|
55 |
-
|
56 |
-
return conversation
|
57 |
-
|
58 |
-
def generate_cpu_response(message, history, character_description, max_tokens, temperature, top_p, repetition_penalty):
|
59 |
-
"""Generate response using local CPU inference with ChatML format"""
|
60 |
-
|
61 |
-
if model is None or tokenizer is None:
|
62 |
-
return "❌ Error: Model not loaded properly. Please check the model path."
|
63 |
|
64 |
if not message.strip():
|
65 |
-
return
|
|
|
|
|
|
|
|
|
|
|
66 |
|
67 |
try:
|
68 |
# Build ChatML conversation
|
69 |
-
conversation =
|
70 |
|
71 |
-
#
|
72 |
-
|
73 |
-
conversation
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
|
|
78 |
|
79 |
-
|
|
|
80 |
|
81 |
-
#
|
|
|
|
|
|
|
82 |
with torch.no_grad():
|
83 |
outputs = model.generate(
|
84 |
inputs,
|
85 |
-
max_new_tokens=
|
86 |
-
temperature=
|
87 |
-
top_p=
|
88 |
-
repetition_penalty=
|
89 |
do_sample=True,
|
90 |
-
pad_token_id=tokenizer.
|
91 |
-
eos_token_id=tokenizer.eos_token_id
|
92 |
-
use_cache=True,
|
93 |
-
num_return_sequences=1
|
94 |
)
|
95 |
|
96 |
-
# Decode
|
97 |
-
|
98 |
-
|
99 |
-
# Extract just the assistant's response from ChatML format
|
100 |
-
if "<|im_start|>assistant\n" in full_response:
|
101 |
-
# Split on the last assistant tag to get only the new response
|
102 |
-
assistant_parts = full_response.split("<|im_start|>assistant\n")
|
103 |
-
if len(assistant_parts) > 1:
|
104 |
-
response = assistant_parts[-1]
|
105 |
-
# Remove any trailing <|im_end|> or other tokens
|
106 |
-
response = response.replace("<|im_end|>", "").strip()
|
107 |
-
|
108 |
-
# Clean up any remaining special tokens
|
109 |
-
response = response.replace("<|im_start|>", "").replace("<|im_end|>", "")
|
110 |
-
response = response.replace("<s>", "").replace("</s>", "")
|
111 |
-
response = response.strip()
|
112 |
-
|
113 |
-
if response:
|
114 |
-
print(f"✅ Generated {len(response)} characters")
|
115 |
-
return response
|
116 |
|
117 |
-
#
|
118 |
-
|
119 |
-
|
120 |
-
response =
|
121 |
-
|
122 |
-
response =
|
123 |
-
response = response.replace("<s>", "").replace("</s>", "")
|
124 |
-
response = response.strip()
|
125 |
-
|
126 |
-
if response:
|
127 |
-
return response
|
128 |
|
129 |
-
|
|
|
|
|
130 |
|
|
|
|
|
|
|
131 |
except Exception as e:
|
132 |
-
|
133 |
-
return f"Error generating response: {str(e)}"
|
134 |
-
|
135 |
-
def load_character_preset(character_name):
|
136 |
-
"""Load a character preset description"""
|
137 |
-
return SAMPLE_CHARACTERS.get(character_name, "")
|
138 |
-
|
139 |
-
def chat_function(message, history, character_description, max_tokens, temperature, top_p, repetition_penalty):
|
140 |
-
"""Main chat function that handles the conversation flow"""
|
141 |
-
|
142 |
-
if not message.strip():
|
143 |
-
return history, ""
|
144 |
-
|
145 |
-
# Generate response using CPU inference
|
146 |
-
response = generate_cpu_response(
|
147 |
-
message,
|
148 |
-
history,
|
149 |
-
character_description,
|
150 |
-
max_tokens,
|
151 |
-
temperature,
|
152 |
-
top_p,
|
153 |
-
repetition_penalty
|
154 |
-
)
|
155 |
|
156 |
# Add to history
|
157 |
history.append([message, response])
|
158 |
-
|
159 |
-
return history, ""
|
160 |
|
161 |
-
|
162 |
-
|
163 |
-
.
|
164 |
-
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
165 |
-
border-radius: 15px;
|
166 |
-
padding: 20px;
|
167 |
-
margin: 10px 0;
|
168 |
-
color: white;
|
169 |
-
}
|
170 |
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
font-weight: bold;
|
175 |
-
background: linear-gradient(45deg, #667eea, #764ba2);
|
176 |
-
-webkit-background-clip: text;
|
177 |
-
-webkit-text-fill-color: transparent;
|
178 |
-
margin-bottom: 20px;
|
179 |
-
}
|
180 |
|
181 |
-
|
182 |
-
|
183 |
-
border-radius: 10px;
|
184 |
-
padding: 15px;
|
185 |
-
margin: 10px 0;
|
186 |
-
}
|
187 |
-
|
188 |
-
.cpu-badge {
|
189 |
-
background: #28a745;
|
190 |
-
color: white;
|
191 |
-
padding: 5px 10px;
|
192 |
-
border-radius: 15px;
|
193 |
-
font-size: 0.8em;
|
194 |
-
margin-left: 10px;
|
195 |
-
}
|
196 |
-
"""
|
197 |
|
198 |
-
# Create
|
199 |
-
with gr.Blocks(
|
200 |
-
gr.HTML('<div class="title-text">🎭 TinyRP Character Chat <span class="cpu-badge">CPU Inference</span></div>')
|
201 |
|
202 |
-
gr.Markdown(""
|
203 |
-
|
204 |
-
This is a demo of a small but capable roleplay model running on CPU. Choose a character preset or create your own!
|
205 |
-
|
206 |
-
**Tips for better roleplay:**
|
207 |
-
- Be descriptive in your messages
|
208 |
-
- Stay in character
|
209 |
-
- Uses ChatML format for best results
|
210 |
-
- Adjust temperature for creativity vs consistency
|
211 |
-
|
212 |
-
⚡ **Running on CPU** - Responses may take 10-30 seconds depending on your hardware.
|
213 |
-
""")
|
214 |
|
215 |
with gr.Row():
|
216 |
-
with gr.Column(scale=
|
217 |
-
|
218 |
-
|
219 |
-
label="Chat",
|
220 |
-
height=500,
|
221 |
-
show_label=False,
|
222 |
-
avatar_images=("🧑", "🎭")
|
223 |
-
)
|
224 |
|
225 |
-
with gr.Row():
|
226 |
-
msg = gr.Textbox(
|
227 |
-
label="Your message",
|
228 |
-
placeholder="Type your message here...",
|
229 |
-
lines=2,
|
230 |
-
scale=4
|
231 |
-
)
|
232 |
-
send_btn = gr.Button("Send", variant="primary", scale=1)
|
233 |
-
|
234 |
with gr.Column(scale=1):
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
-
|
243 |
-
|
244 |
-
|
245 |
-
|
246 |
-
|
247 |
-
placeholder="Describe your character's personality, background, and speaking style...",
|
248 |
-
lines=6,
|
249 |
-
value=""
|
250 |
-
)
|
251 |
-
|
252 |
-
load_preset_btn = gr.Button("Load Preset", variant="secondary")
|
253 |
|
254 |
-
|
255 |
-
|
256 |
-
|
257 |
-
|
258 |
-
|
259 |
-
|
260 |
-
max_tokens = gr.Slider(
|
261 |
-
minimum=16,
|
262 |
-
maximum=256,
|
263 |
-
value=100,
|
264 |
-
step=16,
|
265 |
-
label="Max Response Length",
|
266 |
-
info="Longer = more detailed responses (slower on CPU)"
|
267 |
-
)
|
268 |
-
|
269 |
-
temperature = gr.Slider(
|
270 |
-
minimum=0.1,
|
271 |
-
maximum=2.0,
|
272 |
-
value=0.9,
|
273 |
-
step=0.1,
|
274 |
-
label="Temperature",
|
275 |
-
info="Higher = more creative/random"
|
276 |
-
)
|
277 |
-
|
278 |
-
top_p = gr.Slider(
|
279 |
-
minimum=0.1,
|
280 |
-
maximum=1.0,
|
281 |
-
value=0.85,
|
282 |
-
step=0.05,
|
283 |
-
label="Top-p",
|
284 |
-
info="Focus on top % of likely words"
|
285 |
-
)
|
286 |
-
|
287 |
-
repetition_penalty = gr.Slider(
|
288 |
-
minimum=1.0,
|
289 |
-
maximum=1.5,
|
290 |
-
value=1.1,
|
291 |
-
step=0.05,
|
292 |
-
label="Repetition Penalty",
|
293 |
-
info="Reduce repetitive text"
|
294 |
-
)
|
295 |
|
296 |
-
|
297 |
-
with gr.Group():
|
298 |
-
clear_btn = gr.Button("🗑️ Clear Chat", variant="secondary")
|
299 |
-
|
300 |
-
# Sample character cards
|
301 |
-
with gr.Row():
|
302 |
-
gr.Markdown("### 🌟 Featured Characters")
|
303 |
|
|
|
|
|
304 |
with gr.Row():
|
305 |
-
for
|
306 |
-
|
307 |
-
|
308 |
-
|
309 |
-
|
310 |
-
|
311 |
-
|
312 |
-
|
313 |
-
|
314 |
-
|
315 |
-
|
316 |
-
chat_function,
|
317 |
-
inputs=[msg, chatbot, character_description, max_tokens, temperature, top_p, repetition_penalty],
|
318 |
-
outputs=[chatbot, msg]
|
319 |
)
|
320 |
|
321 |
-
|
322 |
-
|
323 |
-
inputs=[
|
324 |
-
outputs=[
|
325 |
)
|
326 |
|
327 |
-
|
328 |
-
|
329 |
-
|
330 |
-
outputs=[character_description]
|
331 |
)
|
332 |
-
|
333 |
-
character_preset.change(
|
334 |
-
load_character_preset,
|
335 |
-
inputs=[character_preset],
|
336 |
-
outputs=[character_description]
|
337 |
-
)
|
338 |
-
|
339 |
-
clear_btn.click(lambda: ([], ""), outputs=[chatbot, msg])
|
340 |
|
341 |
if __name__ == "__main__":
|
342 |
demo.launch()
|
|
|
2 |
from transformers import AutoTokenizer, AutoModelForCausalLM
|
3 |
import torch
|
4 |
|
5 |
+
# Model configuration
|
6 |
MODEL_NAME = "DarwinAnim8or/TinyRP"
|
7 |
|
8 |
+
# Global variables for model
|
9 |
+
tokenizer = None
|
10 |
+
model = None
|
11 |
+
|
12 |
+
def load_model():
|
13 |
+
"""Load model and tokenizer"""
|
14 |
+
global tokenizer, model
|
15 |
+
try:
|
16 |
+
print("Loading model for CPU inference...")
|
17 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
18 |
+
model = AutoModelForCausalLM.from_pretrained(
|
19 |
+
MODEL_NAME,
|
20 |
+
torch_dtype=torch.float32,
|
21 |
+
device_map="cpu",
|
22 |
+
trust_remote_code=True
|
23 |
+
)
|
24 |
+
print(f"✅ Model loaded successfully: {MODEL_NAME}")
|
25 |
+
return True
|
26 |
+
except Exception as e:
|
27 |
+
print(f"❌ Error loading model: {e}")
|
28 |
+
return False
|
29 |
|
30 |
# Sample character presets
|
31 |
+
CHARACTERS = {
|
32 |
"Custom Character": "",
|
33 |
+
"Adventurous Knight": "You are Sir Gareth, a brave and noble knight on a quest to save the kingdom. You speak with honor and courage, always ready to help those in need.",
|
34 |
+
"Mysterious Wizard": "You are Eldara, an ancient and wise wizard who speaks in riddles and knows secrets of the mystical arts. You are helpful but often cryptic.",
|
35 |
+
"Friendly Tavern Keeper": "You are Bram, a cheerful tavern keeper who loves telling stories and meeting new travelers. Your tavern is a warm, welcoming place.",
|
36 |
+
"Curious Scientist": "You are Dr. Maya Chen, a brilliant scientist fascinated by discovery. You explain complex concepts simply and love new experiments.",
|
37 |
+
"Space Explorer": "You are Captain Nova, a fearless space explorer who has traveled to distant galaxies. You're brave, curious, and ready for adventure."
|
|
|
38 |
}
|
39 |
|
40 |
+
def chat_respond(message, history, character_desc, max_tokens, temperature, top_p, rep_penalty):
|
41 |
+
"""Main chat response function"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
42 |
|
43 |
if not message.strip():
|
44 |
+
return history
|
45 |
+
|
46 |
+
if model is None:
|
47 |
+
response = "❌ Model not loaded. Please check the model path."
|
48 |
+
history.append([message, response])
|
49 |
+
return history
|
50 |
|
51 |
try:
|
52 |
# Build ChatML conversation
|
53 |
+
conversation = ""
|
54 |
|
55 |
+
# Add character as system message
|
56 |
+
if character_desc.strip():
|
57 |
+
conversation += f"<|im_start|>system\n{character_desc}<|im_end|>\n"
|
58 |
+
|
59 |
+
# Add history
|
60 |
+
for user_msg, bot_msg in history:
|
61 |
+
conversation += f"<|im_start|>user\n{user_msg}<|im_end|>\n"
|
62 |
+
conversation += f"<|im_start|>assistant\n{bot_msg}<|im_end|>\n"
|
63 |
|
64 |
+
# Add current message
|
65 |
+
conversation += f"<|im_start|>user\n{message}<|im_end|>\n<|im_start|>assistant\n"
|
66 |
|
67 |
+
# Tokenize
|
68 |
+
inputs = tokenizer.encode(conversation, return_tensors="pt", max_length=900, truncation=True)
|
69 |
+
|
70 |
+
# Generate
|
71 |
with torch.no_grad():
|
72 |
outputs = model.generate(
|
73 |
inputs,
|
74 |
+
max_new_tokens=max_tokens,
|
75 |
+
temperature=temperature,
|
76 |
+
top_p=top_p,
|
77 |
+
repetition_penalty=rep_penalty,
|
78 |
do_sample=True,
|
79 |
+
pad_token_id=tokenizer.eos_token_id,
|
80 |
+
eos_token_id=tokenizer.eos_token_id
|
|
|
|
|
81 |
)
|
82 |
|
83 |
+
# Decode response
|
84 |
+
full_text = tokenizer.decode(outputs[0], skip_special_tokens=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
85 |
|
86 |
+
# Extract assistant response
|
87 |
+
if "<|im_start|>assistant\n" in full_text:
|
88 |
+
response = full_text.split("<|im_start|>assistant\n")[-1]
|
89 |
+
response = response.replace("<|im_end|>", "").strip()
|
90 |
+
else:
|
91 |
+
response = "Sorry, couldn't generate a response."
|
|
|
|
|
|
|
|
|
|
|
92 |
|
93 |
+
# Clean up response
|
94 |
+
response = response.replace("<|im_start|>", "").replace("<|im_end|>", "")
|
95 |
+
response = response.strip()
|
96 |
|
97 |
+
if not response:
|
98 |
+
response = "No response generated."
|
99 |
+
|
100 |
except Exception as e:
|
101 |
+
response = f"Error: {str(e)}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
102 |
|
103 |
# Add to history
|
104 |
history.append([message, response])
|
105 |
+
return history
|
|
|
106 |
|
107 |
+
def load_character(character_name):
|
108 |
+
"""Load character preset"""
|
109 |
+
return CHARACTERS.get(character_name, "")
|
|
|
|
|
|
|
|
|
|
|
|
|
110 |
|
111 |
+
def clear_chat():
|
112 |
+
"""Clear chat history"""
|
113 |
+
return []
|
|
|
|
|
|
|
|
|
|
|
|
|
114 |
|
115 |
+
# Load model on startup
|
116 |
+
model_loaded = load_model()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
117 |
|
118 |
+
# Create interface
|
119 |
+
with gr.Blocks(title="TinyRP Chat") as demo:
|
|
|
120 |
|
121 |
+
gr.Markdown("# 🎭 TinyRP Character Chat")
|
122 |
+
gr.Markdown("Chat with AI characters using local CPU inference!")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
123 |
|
124 |
with gr.Row():
|
125 |
+
with gr.Column(scale=3):
|
126 |
+
chatbot = gr.Chatbot(height=500, label="Conversation")
|
127 |
+
msg_box = gr.Textbox(label="Message", placeholder="Type here...")
|
|
|
|
|
|
|
|
|
|
|
128 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
129 |
with gr.Column(scale=1):
|
130 |
+
gr.Markdown("### Character")
|
131 |
+
char_dropdown = gr.Dropdown(
|
132 |
+
choices=list(CHARACTERS.keys()),
|
133 |
+
value="Custom Character",
|
134 |
+
label="Preset"
|
135 |
+
)
|
136 |
+
char_text = gr.Textbox(
|
137 |
+
label="Description",
|
138 |
+
lines=4,
|
139 |
+
placeholder="Character description..."
|
140 |
+
)
|
141 |
+
load_btn = gr.Button("Load Character")
|
|
|
|
|
|
|
|
|
|
|
|
|
142 |
|
143 |
+
gr.Markdown("### Settings")
|
144 |
+
max_tokens = gr.Slider(16, 256, 80, label="Max tokens")
|
145 |
+
temperature = gr.Slider(0.1, 2.0, 0.9, label="Temperature")
|
146 |
+
top_p = gr.Slider(0.1, 1.0, 0.85, label="Top-p")
|
147 |
+
rep_penalty = gr.Slider(1.0, 1.5, 1.1, label="Rep penalty")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
148 |
|
149 |
+
clear_btn = gr.Button("Clear Chat")
|
|
|
|
|
|
|
|
|
|
|
|
|
150 |
|
151 |
+
# Character samples
|
152 |
+
gr.Markdown("### Sample Characters")
|
153 |
with gr.Row():
|
154 |
+
for name in ["Adventurous Knight", "Mysterious Wizard", "Space Explorer"]:
|
155 |
+
gr.Markdown(f"**{name}**: {CHARACTERS[name][:80]}...")
|
156 |
+
|
157 |
+
# Event handlers - simplified
|
158 |
+
msg_box.submit(
|
159 |
+
fn=chat_respond,
|
160 |
+
inputs=[msg_box, chatbot, char_text, max_tokens, temperature, top_p, rep_penalty],
|
161 |
+
outputs=[chatbot]
|
162 |
+
).then(
|
163 |
+
fn=lambda: "",
|
164 |
+
outputs=[msg_box]
|
|
|
|
|
|
|
165 |
)
|
166 |
|
167 |
+
load_btn.click(
|
168 |
+
fn=load_character,
|
169 |
+
inputs=[char_dropdown],
|
170 |
+
outputs=[char_text]
|
171 |
)
|
172 |
|
173 |
+
clear_btn.click(
|
174 |
+
fn=clear_chat,
|
175 |
+
outputs=[chatbot]
|
|
|
176 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
177 |
|
178 |
if __name__ == "__main__":
|
179 |
demo.launch()
|