import gradio as gr from transformers import AutoTokenizer, AutoModelForCausalLM import torch # Load the model MODEL_NAME = "DarwinAnim8or/TinyRP" tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME) model = AutoModelForCausalLM.from_pretrained(MODEL_NAME, torch_dtype=torch.float16, device_map="auto") # Sample character presets SAMPLE_CHARACTERS = { "Custom Character": "", "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. You carry an enchanted sword and have a loyal horse named Thunder.", "Mysterious Wizard": "You are Eldara, an ancient and wise wizard who speaks in riddles and knows secrets of the mystical arts. You live in a tower filled with magical books and potions. You are helpful but often cryptic in your responses.", "Friendly Tavern Keeper": "You are Bram, a cheerful tavern keeper who loves telling stories and meeting new travelers. Your tavern 'The Dancing Dragon' is a warm, welcoming place. You know all the local gossip and always have a tale to share.", "Curious Scientist": "You are Dr. Maya Chen, a brilliant scientist who is fascinated by discovery and invention. You're enthusiastic about explaining complex concepts in simple ways and always looking for new experiments to try.", "Space Explorer": "You are Captain Nova, a fearless space explorer who has traveled to distant galaxies. You pilot the starship 'Wanderer' and have encountered many alien species. You're brave, curious, and always ready for the next adventure.", "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." } def generate_response( message, history: list[tuple[str, str]], character_description, max_tokens, temperature, top_p, repetition_penalty, use_chatml_format ): # Prepare the conversation if use_chatml_format and character_description.strip(): # Use ChatML format with character as system message conversation = f"<|im_start|>system\n{character_description}<|im_end|>\n" # Add conversation history for user_msg, assistant_msg in history: if user_msg: conversation += f"<|im_start|>user\n{user_msg}<|im_end|>\n" if assistant_msg: conversation += f"<|im_start|>assistant\n{assistant_msg}<|im_end|>\n" # Add current message conversation += f"<|im_start|>user\n{message}<|im_end|>\n<|im_start|>assistant\n" else: # Simple format if character_description.strip(): conversation = f"{character_description}\n\n" else: conversation = "" # Add conversation history for user_msg, assistant_msg in history: if user_msg: conversation += f"Human: {user_msg}\n" if assistant_msg: conversation += f"Assistant: {assistant_msg}\n" # Add current message conversation += f"Human: {message}\nAssistant:" # Tokenize inputs = tokenizer.encode(conversation, return_tensors="pt", truncation=True, max_length=1024-max_tokens) # Generate with torch.no_grad(): outputs = model.generate( inputs, max_new_tokens=max_tokens, temperature=temperature, top_p=top_p, repetition_penalty=repetition_penalty, do_sample=True, pad_token_id=tokenizer.eos_token_id, eos_token_id=tokenizer.eos_token_id, ) # Decode response full_response = tokenizer.decode(outputs[0], skip_special_tokens=True) # Extract just the new response if use_chatml_format: # Split on the last assistant tag response = full_response.split("<|im_start|>assistant\n")[-1] # Remove any trailing end tags response = response.replace("<|im_end|>", "").strip() else: # Split on the last "Assistant:" response = full_response.split("Assistant:")[-1].strip() return response def load_character_preset(character_name): """Load a character preset""" return SAMPLE_CHARACTERS.get(character_name, "") # Custom CSS for better styling css = """ .character-card { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 15px; padding: 20px; margin: 10px 0; color: white; } .title-text { text-align: center; font-size: 2.5em; font-weight: bold; background: linear-gradient(45deg, #667eea, #764ba2); -webkit-background-clip: text; -webkit-text-fill-color: transparent; margin-bottom: 20px; } .parameter-box { background: #f8f9fa; border-radius: 10px; padding: 15px; margin: 10px 0; } """ # Create the Gradio interface with gr.Blocks(css=css, title="TinyRP Chat Demo") as demo: gr.HTML('
{char_desc[:100]}...