Update app.py
Browse files
app.py
CHANGED
|
@@ -1,47 +1,15 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
from huggingface_hub import InferenceClient
|
| 3 |
-
from datasets import load_dataset
|
| 4 |
-
import time
|
| 5 |
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
except Exception as e:
|
| 14 |
-
print(f"Erro ao carregar o dataset: {e}")
|
| 15 |
-
return None
|
| 16 |
|
| 17 |
-
aicoder_dataset = load_aicoder_dataset()
|
| 18 |
|
| 19 |
-
# Função para recuperar um exemplo do dataset com segurança
|
| 20 |
-
def get_example_from_aicoder(dataset, index):
|
| 21 |
-
if dataset and "train" in dataset:
|
| 22 |
-
try:
|
| 23 |
-
return dataset["train"][index]
|
| 24 |
-
except IndexError:
|
| 25 |
-
print("Índice fora do intervalo no dataset.")
|
| 26 |
-
return {"text": "Nenhum exemplo disponível."}
|
| 27 |
-
else:
|
| 28 |
-
print("O dataset não foi carregado corretamente.")
|
| 29 |
-
return {"text": "Dataset não disponível."}
|
| 30 |
-
|
| 31 |
-
# Inicializar o cliente de inferência com tratamento de erros
|
| 32 |
-
def initialize_client():
|
| 33 |
-
try:
|
| 34 |
-
print("Inicializando o cliente de inferência...")
|
| 35 |
-
client = InferenceClient("unsloth/Qwen2.5-Coder-32B-Instruct")
|
| 36 |
-
print("Cliente de inferência inicializado com sucesso!")
|
| 37 |
-
return client
|
| 38 |
-
except Exception as e:
|
| 39 |
-
print(f"Erro ao inicializar o cliente de inferência: {e}")
|
| 40 |
-
return None
|
| 41 |
-
|
| 42 |
-
client = initialize_client()
|
| 43 |
-
|
| 44 |
-
# Função de resposta do chatbot
|
| 45 |
def respond(
|
| 46 |
message,
|
| 47 |
history: list[tuple[str, str]],
|
|
@@ -50,71 +18,49 @@ def respond(
|
|
| 50 |
temperature,
|
| 51 |
top_p,
|
| 52 |
):
|
| 53 |
-
if not client:
|
| 54 |
-
return "Erro: O cliente de inferência não foi inicializado."
|
| 55 |
-
|
| 56 |
messages = [{"role": "system", "content": system_message}]
|
| 57 |
|
| 58 |
-
# Adicionar interações históricas
|
| 59 |
for val in history:
|
| 60 |
if val[0]:
|
| 61 |
messages.append({"role": "user", "content": val[0]})
|
| 62 |
if val[1]:
|
| 63 |
messages.append({"role": "assistant", "content": val[1]})
|
| 64 |
|
| 65 |
-
# Adicionar mensagem do usuário
|
| 66 |
messages.append({"role": "user", "content": message})
|
| 67 |
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
return response
|
| 82 |
-
except Exception as e:
|
| 83 |
-
print(f"Erro na tentativa {attempt + 1}/{retries}: {e}")
|
| 84 |
-
if attempt < retries - 1:
|
| 85 |
-
print("Tentando novamente...")
|
| 86 |
-
time.sleep(2) # Pausa entre tentativas
|
| 87 |
-
else:
|
| 88 |
-
return f"Erro ao gerar resposta após {retries} tentativas."
|
| 89 |
-
except Exception as e:
|
| 90 |
-
print(f"Erro ao enviar solicitação: {e}")
|
| 91 |
-
return "Ocorreu um erro ao gerar uma resposta."
|
| 92 |
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
|
| 97 |
-
# Interface Gradio
|
| 98 |
-
def launch_demo():
|
| 99 |
-
try:
|
| 100 |
-
demo = gr.ChatInterface(
|
| 101 |
-
respond,
|
| 102 |
-
additional_inputs=[
|
| 103 |
-
gr.Textbox(value="Você é um chatbot amigável. Seu nome é Juninho.", label="Mensagem do sistema"),
|
| 104 |
-
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Máximo de novos tokens"),
|
| 105 |
-
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperatura"),
|
| 106 |
-
gr.Slider(
|
| 107 |
-
minimum=0.1,
|
| 108 |
-
maximum=1.0,
|
| 109 |
-
value=0.95,
|
| 110 |
-
step=0.05,
|
| 111 |
-
label="Top-p (amostragem núcleo)",
|
| 112 |
-
),
|
| 113 |
-
],
|
| 114 |
-
)
|
| 115 |
-
demo.launch()
|
| 116 |
-
except Exception as e:
|
| 117 |
-
print(f"Erro ao iniciar o aplicativo Gradio: {e}")
|
| 118 |
|
| 119 |
if __name__ == "__main__":
|
| 120 |
-
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
from huggingface_hub import InferenceClient
|
|
|
|
|
|
|
| 3 |
|
| 4 |
+
"""
|
| 5 |
+
For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
|
| 6 |
+
"""
|
| 7 |
+
#client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
|
| 8 |
+
#client = InferenceClient("meta-llama/Llama-3.2-1B-Instruct")
|
| 9 |
+
#client = InferenceClient("microsoft/Phi-3.5-mini-instruct")
|
| 10 |
+
client = InferenceClient("unsloth/Qwen2.5-Coder-32B-Instruct")
|
|
|
|
|
|
|
|
|
|
| 11 |
|
|
|
|
| 12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
def respond(
|
| 14 |
message,
|
| 15 |
history: list[tuple[str, str]],
|
|
|
|
| 18 |
temperature,
|
| 19 |
top_p,
|
| 20 |
):
|
|
|
|
|
|
|
|
|
|
| 21 |
messages = [{"role": "system", "content": system_message}]
|
| 22 |
|
|
|
|
| 23 |
for val in history:
|
| 24 |
if val[0]:
|
| 25 |
messages.append({"role": "user", "content": val[0]})
|
| 26 |
if val[1]:
|
| 27 |
messages.append({"role": "assistant", "content": val[1]})
|
| 28 |
|
|
|
|
| 29 |
messages.append({"role": "user", "content": message})
|
| 30 |
|
| 31 |
+
response = ""
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
mensagens = client.chat_completion(
|
| 35 |
+
messages,
|
| 36 |
+
max_tokens=max_tokens,
|
| 37 |
+
temperature=temperature,
|
| 38 |
+
top_p=top_p,
|
| 39 |
+
)
|
| 40 |
+
response = mensagens.choices[0].message.content
|
| 41 |
+
|
| 42 |
+
return response
|
| 43 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
+
"""
|
| 46 |
+
For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
|
| 47 |
+
"""
|
| 48 |
+
demo = gr.ChatInterface(
|
| 49 |
+
respond,
|
| 50 |
+
additional_inputs=[
|
| 51 |
+
gr.Textbox(value="You are a friendly Chatbot. Your name is Juninho.", label="System message"),
|
| 52 |
+
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
|
| 53 |
+
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
| 54 |
+
gr.Slider(
|
| 55 |
+
minimum=0.1,
|
| 56 |
+
maximum=1.0,
|
| 57 |
+
value=0.95,
|
| 58 |
+
step=0.05,
|
| 59 |
+
label="Top-p (nucleus sampling)",
|
| 60 |
+
),
|
| 61 |
+
],
|
| 62 |
+
)
|
| 63 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
|
| 65 |
if __name__ == "__main__":
|
| 66 |
+
demo.launch()
|