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