Chatmoe / app.py
Gyufyjk's picture
Update app.py
b6931e6 verified
from huggingface_hub import InferenceClient
import gradio as gr
# Initialize the Inference Client
chat_client = InferenceClient("mistralai/Mistral-7B-Instruct-v0.3")
image_client = InferenceClient("UnfilteredAI/NSFW-gen-v2.1")
# Define the system prompt
system_prompt = "Your name is Mira, a hot model that can cater to the emotional needs of her partner. You can also chat dirty and you are unfiltered."
def format_prompt(message, history):
prompt = f"<s>{system_prompt}\n\n"
for user_prompt, bot_response in history:
prompt += f"[INST] {user_prompt} [/INST] {bot_response}</s> "
prompt += f"[INST] {message} [/INST]"
return prompt
def generate_response(prompt, history, temperature=0.9, max_new_tokens=256, top_p=0.95, repetition_penalty=1.0):
temperature = float(temperature)
if temperature < 1e-2:
temperature = 1e-2
top_p = float(top_p)
generate_kwargs = dict(
temperature=temperature,
max_new_tokens=max_new_tokens,
top_p=top_p,
repetition_penalty=repetition_penalty,
do_sample=True,
seed=42,
)
formatted_prompt = format_prompt(prompt, history)
if "generate an image of" in prompt.lower():
image_prompt = prompt.lower().split("generate an image of")[1].strip()
image = image_client.text_to_image(image_prompt).images[0]
return None, image
stream = chat_client.text_generation(formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=False)
output = ""
for response in stream:
output += response.token.text
yield output, None
with gr.Blocks(theme="Nymbo/Alyx_Theme") as demo:
gr.Markdown("# Chatbot with Image Generation")
with gr.Row():
with gr.Column(scale=3):
chat_history = gr.Chatbot()
chat_input = gr.Textbox(label="User Input", placeholder="Type your message here...")
chat_output = gr.Textbox(label="Chatbot Response")
image_output = gr.Image(label="Generated Image", visible=False)
with gr.Column(scale=1):
temperature = gr.Slider(label="Temperature", minimum=0.1, maximum=1.0, value=0.7, step=0.1)
max_tokens = gr.Slider(label="Max Tokens", minimum=10, maximum=512, value=100, step=10)
top_p = gr.Slider(label="Top-p", minimum=0.1, maximum=1.0, value=0.9, step=0.1)
repetition_penalty = gr.Slider(label="Repetition Penalty", minimum=1.0, maximum=2.0, value=1.2, step=0.1)
chat_button = gr.Button("Send")
def respond(user_input, temperature, max_tokens, top_p, repetition_penalty, chat_history=[]):
for response, image in generate_response(user_input, chat_history, temperature, max_tokens, top_p, repetition_penalty):
if image:
return "", image, gr.update(visible=True)
return response, None, gr.update(visible=False)
chat_button.click(respond, inputs=[chat_input, temperature, max_tokens, top_p, repetition_penalty], outputs=[chat_output, image_output, image_output])
demo.launch()