Spaces:
Sleeping
Sleeping
atualiza app.py
Browse files
app.py
CHANGED
|
@@ -2,112 +2,203 @@ from transformers import pipeline
|
|
| 2 |
from huggingface_hub import login
|
| 3 |
import gradio as gr
|
| 4 |
import os
|
|
|
|
|
|
|
| 5 |
import warnings
|
| 6 |
|
| 7 |
-
#
|
| 8 |
-
|
| 9 |
-
HF_TOKEN = os.getenv("HUGGINGFACE_TOKEN") # Leia de uma variável de ambiente
|
| 10 |
|
| 11 |
-
# Lista de modelos prioritários
|
| 12 |
-
|
| 13 |
-
"bigcode/starcoderbase"
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
-
#
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
-
# Tentar modelos
|
| 35 |
-
for
|
| 36 |
try:
|
| 37 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
"text-generation",
|
| 39 |
-
model=
|
| 40 |
-
device_map="auto"
|
|
|
|
| 41 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
except Exception as e:
|
| 43 |
-
warnings.warn(f"
|
| 44 |
|
| 45 |
-
# Fallback
|
| 46 |
-
warnings.warn("Usando
|
| 47 |
-
return pipeline("text-generation", model="gpt2")
|
| 48 |
|
| 49 |
-
#
|
| 50 |
-
gerador_codigo =
|
| 51 |
|
| 52 |
-
# Função
|
| 53 |
-
def
|
| 54 |
try:
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
)
|
| 63 |
-
return resposta[0]["generated_text"]
|
| 64 |
except Exception as e:
|
| 65 |
-
|
|
|
|
| 66 |
|
| 67 |
-
# Interface
|
| 68 |
-
with gr.Blocks(
|
| 69 |
-
gr.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
|
| 71 |
with gr.Row():
|
| 72 |
-
with gr.Column():
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
)
|
| 78 |
-
|
|
|
|
|
|
|
| 79 |
|
| 80 |
-
with gr.Column():
|
| 81 |
-
|
| 82 |
-
label="Código Gerado",
|
| 83 |
language="python",
|
|
|
|
|
|
|
| 84 |
interactive=True
|
| 85 |
)
|
| 86 |
|
| 87 |
-
#
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
)
|
| 100 |
|
| 101 |
-
#
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
)
|
| 107 |
|
| 108 |
-
#
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
|
|
|
|
|
|
|
|
| 2 |
from huggingface_hub import login
|
| 3 |
import gradio as gr
|
| 4 |
import os
|
| 5 |
+
import time
|
| 6 |
+
from typing import Dict
|
| 7 |
import warnings
|
| 8 |
|
| 9 |
+
# --- Configurações Globais --- #
|
| 10 |
+
HF_TOKEN = os.getenv("HUGGINGFACE_TOKEN") # Lê do ambiente ou .env
|
|
|
|
| 11 |
|
| 12 |
+
# Lista de modelos prioritários com configurações
|
| 13 |
+
MODEL_CONFIGS = {
|
| 14 |
+
"bigcode/starcoderbase": {
|
| 15 |
+
"requires_token": True,
|
| 16 |
+
"params": {"temperature": 0.7, "max_length": 256}
|
| 17 |
+
},
|
| 18 |
+
"bigcode/starcoder2-7b": {
|
| 19 |
+
"requires_token": False,
|
| 20 |
+
"params": {"temperature": 0.6, "max_length": 512}
|
| 21 |
+
},
|
| 22 |
+
"codellama/CodeLlama-7b-hf": {
|
| 23 |
+
"requires_token": False,
|
| 24 |
+
"params": {"temperature": 0.5, "max_length": 384}
|
| 25 |
+
}
|
| 26 |
+
}
|
| 27 |
|
| 28 |
+
# --- Sistema de Idiomas --- #
|
| 29 |
+
TRANSLATIONS: Dict[str, Dict[str, str]] = {
|
| 30 |
+
"pt_BR": {
|
| 31 |
+
"title": "🧑💻 Assistente de Programação IA",
|
| 32 |
+
"description": "Descreva o código que precisa e eu gerarei automaticamente!",
|
| 33 |
+
"input_placeholder": "Ex: Função Python para calcular IMC",
|
| 34 |
+
"generate_btn": "Gerar Código",
|
| 35 |
+
"loading": "Gerando...",
|
| 36 |
+
"error": "Erro ao processar",
|
| 37 |
+
"model_status": "Modelo: {}"
|
| 38 |
+
},
|
| 39 |
+
"en": {
|
| 40 |
+
"title": "🧑💻 AI Programming Assistant",
|
| 41 |
+
"description": "Describe the code you need and I'll generate it automatically!",
|
| 42 |
+
"input_placeholder": "Ex: Python function to calculate BMI",
|
| 43 |
+
"generate_btn": "Generate Code",
|
| 44 |
+
"loading": "Generating...",
|
| 45 |
+
"error": "Processing error",
|
| 46 |
+
"model_status": "Model: {}"
|
| 47 |
+
}
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
# --- Inicialização Otimizada do Modelo --- #
|
| 51 |
+
@gr.cache_resource()
|
| 52 |
+
def load_model():
|
| 53 |
+
current_model = None
|
| 54 |
|
| 55 |
+
# Tentar modelos prioritários
|
| 56 |
+
for model_name, config in MODEL_CONFIGS.items():
|
| 57 |
try:
|
| 58 |
+
if config["requires_token"] and not HF_TOKEN:
|
| 59 |
+
continue
|
| 60 |
+
|
| 61 |
+
if config["requires_token"]:
|
| 62 |
+
login(token=HF_TOKEN)
|
| 63 |
+
|
| 64 |
+
print(f"⚡ Tentando carregar: {model_name}")
|
| 65 |
+
start_time = time.time()
|
| 66 |
+
|
| 67 |
+
current_model = pipeline(
|
| 68 |
"text-generation",
|
| 69 |
+
model=model_name,
|
| 70 |
+
device_map="auto",
|
| 71 |
+
**config["params"]
|
| 72 |
)
|
| 73 |
+
|
| 74 |
+
print(f"✅ {model_name} carregado em {time.time()-start_time:.2f}s")
|
| 75 |
+
return current_model, model_name
|
| 76 |
+
|
| 77 |
except Exception as e:
|
| 78 |
+
warnings.warn(f"❌ Falha no {model_name}: {str(e)}")
|
| 79 |
|
| 80 |
+
# Fallback
|
| 81 |
+
warnings.warn("Usando GPT-2 como fallback")
|
| 82 |
+
return pipeline("text-generation", model="gpt2"), "gpt2"
|
| 83 |
|
| 84 |
+
# Carrega o modelo e pega seu nome
|
| 85 |
+
gerador_codigo, modelo_atual = load_model()
|
| 86 |
|
| 87 |
+
# --- Função Principal com Monitoramento --- #
|
| 88 |
+
def generate_code(prompt: str, lang: str) -> str:
|
| 89 |
try:
|
| 90 |
+
start_time = time.time()
|
| 91 |
+
output = gerador_codigo(prompt)[0]["generated_text"]
|
| 92 |
+
gen_time = time.time() - start_time
|
| 93 |
+
|
| 94 |
+
print(f"📊 Estatísticas | Tempo: {gen_time:.2f}s | Chars: {len(output)}")
|
| 95 |
+
return output
|
| 96 |
+
|
|
|
|
|
|
|
| 97 |
except Exception as e:
|
| 98 |
+
print(f"🔥 Erro crítico: {str(e)}")
|
| 99 |
+
return f"{TRANSLATIONS[lang]['error']}: {str(e)}"
|
| 100 |
|
| 101 |
+
# --- Interface Premium --- #
|
| 102 |
+
with gr.Blocks(
|
| 103 |
+
theme=gr.themes.Soft(
|
| 104 |
+
primary_hue="blue",
|
| 105 |
+
secondary_hue="gray",
|
| 106 |
+
font=[gr.themes.GoogleFont("Poppins")]
|
| 107 |
+
),
|
| 108 |
+
title="Assistente de IA Multilíngue"
|
| 109 |
+
) as app:
|
| 110 |
+
|
| 111 |
+
# Estado para rastrear o idioma
|
| 112 |
+
current_lang = gr.State("pt_BR")
|
| 113 |
+
|
| 114 |
+
# Componentes dinâmicos
|
| 115 |
+
title = gr.Markdown()
|
| 116 |
+
description = gr.Markdown()
|
| 117 |
+
model_status = gr.Markdown()
|
| 118 |
|
| 119 |
with gr.Row():
|
| 120 |
+
with gr.Column(scale=1):
|
| 121 |
+
lang_radio = gr.Radio(
|
| 122 |
+
choices=["pt_BR", "en"],
|
| 123 |
+
value="pt_BR",
|
| 124 |
+
label="🌐 Idioma/Language",
|
| 125 |
+
interactive=True
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
input_box = gr.Textbox(
|
| 129 |
+
lines=5,
|
| 130 |
+
placeholder="",
|
| 131 |
+
label="",
|
| 132 |
+
interactive=True
|
| 133 |
)
|
| 134 |
+
|
| 135 |
+
btn = gr.Button(value="", variant="primary")
|
| 136 |
+
loading_label = gr.Label(visible=False)
|
| 137 |
|
| 138 |
+
with gr.Column(scale=2):
|
| 139 |
+
output_code = gr.Code(
|
|
|
|
| 140 |
language="python",
|
| 141 |
+
label="",
|
| 142 |
+
lines=28,
|
| 143 |
interactive=True
|
| 144 |
)
|
| 145 |
|
| 146 |
+
# Atualização de idioma
|
| 147 |
+
def update_language(lang):
|
| 148 |
+
trans = TRANSLATIONS[lang]
|
| 149 |
+
return [
|
| 150 |
+
gr.Markdown(value=f"## {trans['title']}"),
|
| 151 |
+
gr.Markdown(value=trans['description']),
|
| 152 |
+
gr.Textbox(placeholder=trans['input_placeholder']),
|
| 153 |
+
gr.Button(value=trans['generate_btn']),
|
| 154 |
+
gr.Code(label=trans['title']),
|
| 155 |
+
gr.Markdown(value=trans['model_status'].format(modelo_atual)),
|
| 156 |
+
lang
|
| 157 |
+
]
|
| 158 |
|
| 159 |
+
# Geração do código
|
| 160 |
+
def wrapper_generate(prompt, lang):
|
| 161 |
+
loading_label.value = TRANSLATIONS[lang]["loading"]
|
| 162 |
+
yield {loading_label: gr.Label(visible=True)}
|
| 163 |
+
|
| 164 |
+
result = generate_code(prompt, lang)
|
| 165 |
+
|
| 166 |
+
yield {
|
| 167 |
+
output_code: result,
|
| 168 |
+
loading_label: gr.Label(visible=False)
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
# Eventos
|
| 172 |
+
lang_radio.change(
|
| 173 |
+
fn=update_language,
|
| 174 |
+
inputs=lang_radio,
|
| 175 |
+
outputs=[title, description, input_box, btn, output_code, model_status, current_lang]
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
btn.click(
|
| 179 |
+
fn=wrapper_generate,
|
| 180 |
+
inputs=[input_box, current_lang],
|
| 181 |
+
outputs=[output_code, loading_label],
|
| 182 |
+
api_name="generate"
|
| 183 |
)
|
| 184 |
|
| 185 |
+
# Exemplos
|
| 186 |
+
examples = gr.Examples(
|
| 187 |
+
examples=[
|
| 188 |
+
["Função Python para calcular fatorial", "pt_BR"],
|
| 189 |
+
["Classe JavaScript para um carro com marca e modelo", "pt_BR"],
|
| 190 |
+
["Python function to connect to MySQL database", "en"],
|
| 191 |
+
["React component for a shopping cart", "en"]
|
| 192 |
+
],
|
| 193 |
+
inputs=[input_box, current_lang],
|
| 194 |
+
label="💡 Exemplos/Examples"
|
| 195 |
)
|
| 196 |
|
| 197 |
+
# --- Otimizações Finais --- #
|
| 198 |
+
app.queue(concurrency_count=2) # Processa 2 requisições em paralelo
|
| 199 |
+
|
| 200 |
+
if __name__ == "__main__":
|
| 201 |
+
app.launch(
|
| 202 |
+
server_name="0.0.0.0",
|
| 203 |
+
server_port=int(os.getenv("GRADIO_PORT", 7860))
|
| 204 |
+
)
|