Spaces:
Running
Running
import gradio as gr | |
from huggingface_hub import InferenceClient | |
import random | |
class GemmaChatApp: | |
def __init__(self): | |
self.models = [ | |
"google/gemma-7b", | |
"google/gemma-7b-it", | |
"google/gemma-2b", | |
"google/gemma-2b-it" | |
] | |
self.clients = [ | |
InferenceClient(self.models[0]), | |
InferenceClient(self.models[1]), | |
InferenceClient(self.models[2]), | |
InferenceClient(self.models[3]), | |
] | |
self.rand_val = random.randint(1, 1111111111111111) | |
self.create_app() | |
def format_prompt(self, message, history): | |
prompt = "" | |
if history: | |
for user_prompt, bot_response in history: | |
prompt += f"<start_of_turn>usuário{user_prompt}<end_of_turn>" | |
prompt += f"<start_of_turn>modelo{bot_response}" | |
prompt += f"<start_of_turn>usuário{message}<end_of_turn><start_of_turn>modelo" | |
return prompt | |
def chat_inf(self, system_prompt, prompt, history, client_choice, seed, temp, tokens, top_p, rep_p, stream_output): | |
client = self.clients[int(client_choice) - 1] | |
if not history: | |
history = [] | |
generate_kwargs = dict( | |
temperature=temp, | |
max_new_tokens=tokens, | |
top_p=top_p, | |
repetition_penalty=rep_p, | |
do_sample=True, | |
seed=seed, | |
) | |
formatted_prompt = self.format_prompt(f"{system_prompt}, {prompt}", history) | |
stream = client.text_generation(formatted_prompt, **generate_kwargs, stream=stream_output, details=True, return_full_text=False) | |
output = "" | |
for response in stream: | |
output += response.token.text | |
yield [(prompt, output)] | |
history.append((prompt, output)) | |
yield history | |
def clear_fn(self): | |
return None, None, None | |
def create_app(self): | |
# Function to create a guide HTML for the user | |
def create_guide(): | |
return """ | |
<div style="max-width: 800px; margin: auto; padding: 20px; text-align: left; font-family: 'Arial', sans-serif; color: #333;"> | |
<h1 style='font-size: 28px; text-align: center; color: #007BFF;'>Gemma Google LLM</h1> | |
<p style='font-size: 16px; text-align: center; color: #555;'> | |
Um conjunto de modelos leves e avançados, | |
construídos a partir da mesma pesquisa e tecnologia utilizadas para criar os modelos Gemini. | |
</p> | |
<h3>Instruções:</h3> | |
<ol style='font-size: 16px;'> | |
<li>Insira seu prompt na caixa <strong>"Prompt"</strong>.</li> | |
<li> | |
Opcionalmente, adicione um prompt de sistema na caixa <strong>"Prompt do Sistema"</strong>. | |
</li> | |
<li> | |
Escolha um modelo na lista suspensa <strong>"Modelos"</strong>. | |
</li> | |
<li> | |
Ajuste os parâmetros conforme necessário: | |
<ul> | |
<li> | |
<strong>Temperatura:</strong> Controla a aleatoriedade da geração (valores mais baixos são mais determinísticos). | |
</li> | |
<li> | |
<strong>Top-P:</strong> Controla a diversidade da geração (valores mais baixos são mais restritos). | |
</li> | |
<li> | |
<strong>Penalidade de Repetição:</strong> Controla a penalidade para repetições na resposta gerada. | |
</li> | |
<li> | |
<strong>Máximo de Novos Tokens:</strong> Limita o número máximo de tokens gerados. | |
</li> | |
</ul> | |
</li> | |
<li> | |
Se desejar, marque <strong>"Semente Aleatória"</strong> para gerar uma semente aleatória. | |
</li> | |
<li> | |
Clique em <strong>"Enviar"</strong> para gerar uma resposta do modelo. | |
</li> | |
<li> | |
Clique em <strong>"Parar"</strong> a qualquer momento para interromper a conversa. | |
</li> | |
<li> | |
Clique em <strong>"Limpar"</strong> para reiniciar a conversa. | |
</li> | |
<li> | |
Marque <strong>"Saída em Tempo Real"</strong> para exibir a resposta do modelo em tempo real. | |
</li> | |
</ol> | |
</div> | |
""" | |
# With Gradio Blocks, create the app interface | |
with gr.Blocks() as app: | |
gr.HTML(create_guide()) # Display the guide | |
chat_b = gr.Chatbot(height=500) | |
with gr.Group(): | |
with gr.Row(): | |
with gr.Column(scale=3): | |
inp = gr.Textbox(label="Prompt", placeholder="Digite seu prompt aqui") | |
sys_inp = gr.TextArea(label="Prompt do Sistema (opcional)", placeholder="Opcional: Adicione um prompt de sistema aqui") | |
with gr.Row(): | |
with gr.Column(scale=2): | |
btn = gr.Button("Enviar") | |
with gr.Column(scale=1): | |
with gr.Group(): | |
stop_btn = gr.Button("Parar") | |
clear_btn = gr.Button("Limpar") | |
client_choice = gr.Dropdown(label="Modelos", type='index', choices={c: f"Model {i+1}" for i, c in enumerate(self.models)}, value=self.models[0], interactive=True) | |
with gr.Column(scale=1): | |
with gr.Group(): | |
rand = gr.Checkbox(label="Semente Aleatória", value=True) | |
seed = self.check_rand(rand, self.rand_val) | |
tokens = gr.Slider(label="Número Máximo de Tokens", value=6400, minimum=0, maximum=8000, step=64, interactive=True, visible=True, info="O número máximo de tokens") | |
temp = gr.Slider(label="Temperatura (Determinismo)", step=0.01, minimum=0.01, maximum=1.0, value=0.9) | |
top_p = gr.Slider(label="Top-P (Diversidade)", step=0.01, minimum=0.01, maximum=1.0, value=0.9) | |
rep_p = gr.Slider(label="Penalidade por Repetição", step=0.1, minimum=0.1, maximum=2.0, value=1.0) | |
stream_output = gr.Checkbox(label="Saída em Tempo Real", value=True) | |
go = btn.click(self.check_rand, [rand, seed], seed).then(self.chat_inf, [sys_inp, inp, chat_b, client_choice, seed, temp, tokens, top_p, rep_p, stream_output], chat_b) | |
stop_btn.click(None, None, None, cancels=go) | |
clear_btn.click(self.clear_fn, None, [inp, sys_inp, chat_b]) | |
app.queue(default_concurrency_limit=10).launch() | |
def check_rand(self, inp, val): | |
if inp: | |
return gr.Slider(label="Semente", minimum=1, maximum=1111111111111111, value=random.randint(1, 1111111111111111)) | |
else: | |
return gr.Slider(label="Semente", minimum=1, maximum=1111111111111111, value=int(val)) | |
# Create an instance of the GemmaChatApp and launch the app | |
gemma_chat_app = GemmaChatApp() | |