Spaces:
Sleeping
Sleeping
atualizar app.py
Browse files
app.py
CHANGED
|
@@ -2,27 +2,24 @@ from transformers import pipeline
|
|
| 2 |
import gradio as gr
|
| 3 |
from functools import lru_cache
|
| 4 |
import time
|
| 5 |
-
import os
|
| 6 |
|
| 7 |
# --- Configurações do Modelo --- #
|
| 8 |
-
MODEL_NAME = "
|
| 9 |
-
|
| 10 |
-
"python", "javascript", "typescript",
|
| 11 |
-
"java", "c++", "c#", "go", "rust",
|
| 12 |
-
"html", "css", "sql", "php"
|
| 13 |
-
]
|
| 14 |
|
| 15 |
# --- Cache do Modelo --- #
|
| 16 |
@lru_cache(maxsize=None)
|
| 17 |
def load_model():
|
| 18 |
try:
|
| 19 |
-
print("⚡ Carregando modelo...")
|
| 20 |
start_time = time.time()
|
| 21 |
model = pipeline(
|
| 22 |
"text-generation",
|
| 23 |
model=MODEL_NAME,
|
| 24 |
device_map="auto",
|
| 25 |
-
torch_dtype="auto"
|
|
|
|
| 26 |
)
|
| 27 |
print(f"✅ Modelo carregado em {time.time()-start_time:.2f}s")
|
| 28 |
return model
|
|
@@ -30,90 +27,93 @@ def load_model():
|
|
| 30 |
print(f"❌ Erro ao carregar modelo: {str(e)}")
|
| 31 |
raise
|
| 32 |
|
| 33 |
-
# --- Função de Geração
|
| 34 |
def generate_response(message, history, selected_language):
|
| 35 |
try:
|
| 36 |
model = load_model()
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
start_time = time.time()
|
| 42 |
response = model(
|
| 43 |
prompt,
|
| 44 |
-
|
| 45 |
-
temperature=0.
|
|
|
|
|
|
|
| 46 |
)[0]["generated_text"]
|
| 47 |
|
| 48 |
-
#
|
| 49 |
-
if "```" in response
|
| 50 |
-
code = response.split("```")[1][len(selected_language)+1:].strip()
|
| 51 |
-
else:
|
| 52 |
-
code = response.strip()
|
| 53 |
|
| 54 |
-
return {
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
|
| 59 |
except Exception as e:
|
| 60 |
-
return {
|
| 61 |
-
"role": "assistant",
|
| 62 |
-
"content": f"❌ Erro: {str(e)}\n\nPor favor, tente reformular sua solicitação."
|
| 63 |
-
}
|
| 64 |
|
| 65 |
-
# --- Interface
|
| 66 |
with gr.Blocks(
|
| 67 |
theme=gr.themes.Soft(
|
| 68 |
-
primary_hue="blue"
|
| 69 |
-
font=[gr.themes.GoogleFont("Inter")]
|
| 70 |
),
|
| 71 |
css="""
|
| 72 |
-
.chatbot { min-height:
|
| 73 |
-
.code { max-height:
|
| 74 |
"""
|
| 75 |
) as app:
|
| 76 |
|
| 77 |
-
gr.Markdown("# <center>🧑💻 Assistente de Programação
|
| 78 |
|
| 79 |
with gr.Row():
|
| 80 |
with gr.Column(scale=3):
|
| 81 |
language = gr.Dropdown(
|
| 82 |
-
label="🔤 Linguagem
|
| 83 |
-
choices=
|
| 84 |
value="python"
|
| 85 |
)
|
| 86 |
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
placeholder="Descreva o código que precisa...",
|
| 92 |
-
lines=3
|
| 93 |
-
),
|
| 94 |
-
examples=[
|
| 95 |
-
["Função Python para calcular fatorial"],
|
| 96 |
-
["Componente React em TypeScript"],
|
| 97 |
-
["Classe Java para conexão JDBC"]
|
| 98 |
-
]
|
| 99 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
|
| 101 |
with gr.Column(scale=2):
|
| 102 |
-
gr.Markdown("###
|
| 103 |
gr.Markdown("""
|
| 104 |
-
-
|
| 105 |
-
-
|
| 106 |
-
-
|
| 107 |
-
-
|
| 108 |
-
-
|
| 109 |
-
-
|
| 110 |
-
- Banco de Dados 🗃️ (SQL)
|
| 111 |
""")
|
| 112 |
|
| 113 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
if __name__ == "__main__":
|
| 115 |
app.launch(
|
| 116 |
server_name="0.0.0.0",
|
| 117 |
server_port=int(os.getenv("GRADIO_PORT", 7860)),
|
| 118 |
share=False
|
| 119 |
-
)
|
|
|
|
| 2 |
import gradio as gr
|
| 3 |
from functools import lru_cache
|
| 4 |
import time
|
| 5 |
+
import os
|
| 6 |
|
| 7 |
# --- Configurações do Modelo --- #
|
| 8 |
+
MODEL_NAME = "codellama/CodeLlama-7b-hf" # Modelo mais rápido que starcoder
|
| 9 |
+
MAX_TOKENS = 512 # Reduzido para respostas mais rápidas
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
# --- Cache do Modelo --- #
|
| 12 |
@lru_cache(maxsize=None)
|
| 13 |
def load_model():
|
| 14 |
try:
|
| 15 |
+
print("⚡ Carregando modelo otimizado...")
|
| 16 |
start_time = time.time()
|
| 17 |
model = pipeline(
|
| 18 |
"text-generation",
|
| 19 |
model=MODEL_NAME,
|
| 20 |
device_map="auto",
|
| 21 |
+
torch_dtype="auto",
|
| 22 |
+
model_kwargs={"load_in_8bit": True} # Otimização de memória
|
| 23 |
)
|
| 24 |
print(f"✅ Modelo carregado em {time.time()-start_time:.2f}s")
|
| 25 |
return model
|
|
|
|
| 27 |
print(f"❌ Erro ao carregar modelo: {str(e)}")
|
| 28 |
raise
|
| 29 |
|
| 30 |
+
# --- Função de Geração Otimizada --- #
|
| 31 |
def generate_response(message, history, selected_language):
|
| 32 |
try:
|
| 33 |
model = load_model()
|
| 34 |
+
|
| 35 |
+
# Prompt eficiente
|
| 36 |
+
prompt = f"""Gere SOMENTE o código {selected_language} para: {message}
|
| 37 |
+
Instruções:
|
| 38 |
+
1. Apenas o código necessário
|
| 39 |
+
2. Sem explicações
|
| 40 |
+
3. Máximo {MAX_TOKENS} tokens"""
|
| 41 |
|
| 42 |
start_time = time.time()
|
| 43 |
response = model(
|
| 44 |
prompt,
|
| 45 |
+
max_new_tokens=MAX_TOKENS,
|
| 46 |
+
temperature=0.2, # Menos criativo = mais rápido
|
| 47 |
+
do_sample=True,
|
| 48 |
+
top_k=30
|
| 49 |
)[0]["generated_text"]
|
| 50 |
|
| 51 |
+
# Extração eficiente do código
|
| 52 |
+
code = response.split("```")[1][len(selected_language)+1:].strip() if "```" in response else response.strip()
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
+
return f"""```{selected_language}
|
| 55 |
+
{code}
|
| 56 |
+
|
| 57 |
+
⏱️ Processado em {time.time()-start_time:.2f}s"""
|
| 58 |
|
| 59 |
except Exception as e:
|
| 60 |
+
return f"❌ Erro: {str(e)}"
|
|
|
|
|
|
|
|
|
|
| 61 |
|
| 62 |
+
# --- Interface Leve --- #
|
| 63 |
with gr.Blocks(
|
| 64 |
theme=gr.themes.Soft(
|
| 65 |
+
primary_hue="blue"
|
|
|
|
| 66 |
),
|
| 67 |
css="""
|
| 68 |
+
.chatbot { min-height: 400px; }
|
| 69 |
+
.code { max-height: 300px; overflow-y: auto !important; font-size: 0.9em !important; }
|
| 70 |
"""
|
| 71 |
) as app:
|
| 72 |
|
| 73 |
+
gr.Markdown("# <center>🧑💻 Assistente Rápido de Programação</center>")
|
| 74 |
|
| 75 |
with gr.Row():
|
| 76 |
with gr.Column(scale=3):
|
| 77 |
language = gr.Dropdown(
|
| 78 |
+
label="🔤 Linguagem",
|
| 79 |
+
choices=["python", "javascript", "java", "cpp", "html", "sql"],
|
| 80 |
value="python"
|
| 81 |
)
|
| 82 |
|
| 83 |
+
chatbot = gr.Chatbot(height=400)
|
| 84 |
+
msg = gr.Textbox(
|
| 85 |
+
placeholder="Ex: Função para calcular IMC em Python",
|
| 86 |
+
lines=2
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
)
|
| 88 |
+
|
| 89 |
+
with gr.Row():
|
| 90 |
+
submit_btn = gr.Button("🚀 Gerar (Enter)", variant="primary")
|
| 91 |
+
clear_btn = gr.Button("🧹 Limpar")
|
| 92 |
|
| 93 |
with gr.Column(scale=2):
|
| 94 |
+
gr.Markdown("### ⚡ Dicas para Respostas Rápidas")
|
| 95 |
gr.Markdown("""
|
| 96 |
+
- Seja específico nos requisitos
|
| 97 |
+
- Evite descrições muito longas
|
| 98 |
+
- Exemplos eficientes:
|
| 99 |
+
- "Função Python para fatorial"
|
| 100 |
+
- "Componente React simples"
|
| 101 |
+
- "Consulta SQL para filtrar dados"
|
|
|
|
| 102 |
""")
|
| 103 |
|
| 104 |
+
# Eventos Otimizados
|
| 105 |
+
def respond(message, chat_history, lang):
|
| 106 |
+
bot_message = generate_response(message, chat_history, lang)
|
| 107 |
+
chat_history.append((message, bot_message))
|
| 108 |
+
return "", chat_history
|
| 109 |
+
|
| 110 |
+
msg.submit(respond, [msg, chatbot, language], [msg, chatbot])
|
| 111 |
+
submit_btn.click(respond, [msg, chatbot, language], [msg, chatbot])
|
| 112 |
+
clear_btn.click(lambda: None, None, chatbot, queue=False)
|
| 113 |
+
|
| 114 |
if __name__ == "__main__":
|
| 115 |
app.launch(
|
| 116 |
server_name="0.0.0.0",
|
| 117 |
server_port=int(os.getenv("GRADIO_PORT", 7860)),
|
| 118 |
share=False
|
| 119 |
+
)
|