Spaces:
Sleeping
Sleeping
atualizar app.py
Browse files
app.py
CHANGED
|
@@ -5,27 +5,28 @@ 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ê
|
| 11 |
|
| 12 |
-
#
|
| 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.
|
| 21 |
},
|
| 22 |
"codellama/CodeLlama-7b-hf": {
|
| 23 |
"requires_token": False,
|
| 24 |
-
"params": {"temperature": 0.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
}
|
| 26 |
}
|
| 27 |
|
| 28 |
-
# --- Sistema de
|
| 29 |
TRANSLATIONS: Dict[str, Dict[str, str]] = {
|
| 30 |
"pt_BR": {
|
| 31 |
"title": "🧑💻 Assistente de Programação IA",
|
|
@@ -34,7 +35,8 @@ TRANSLATIONS: Dict[str, Dict[str, str]] = {
|
|
| 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",
|
|
@@ -43,24 +45,21 @@ TRANSLATIONS: Dict[str, Dict[str, str]] = {
|
|
| 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 |
-
@
|
| 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 |
|
|
@@ -77,7 +76,7 @@ def load_model():
|
|
| 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 |
|
|
@@ -105,7 +104,7 @@ with gr.Blocks(
|
|
| 105 |
secondary_hue="gray",
|
| 106 |
font=[gr.themes.GoogleFont("Poppins")]
|
| 107 |
),
|
| 108 |
-
title="
|
| 109 |
) as app:
|
| 110 |
|
| 111 |
# Estado para rastrear o idioma
|
|
@@ -118,6 +117,7 @@ with gr.Blocks(
|
|
| 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",
|
|
@@ -125,6 +125,7 @@ with gr.Blocks(
|
|
| 125 |
interactive=True
|
| 126 |
)
|
| 127 |
|
|
|
|
| 128 |
input_box = gr.Textbox(
|
| 129 |
lines=5,
|
| 130 |
placeholder="",
|
|
@@ -132,10 +133,12 @@ with gr.Blocks(
|
|
| 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="",
|
|
@@ -143,32 +146,32 @@ with gr.Blocks(
|
|
| 143 |
interactive=True
|
| 144 |
)
|
| 145 |
|
| 146 |
-
#
|
| 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
|
| 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,
|
|
@@ -182,7 +185,7 @@ with gr.Blocks(
|
|
| 182 |
api_name="generate"
|
| 183 |
)
|
| 184 |
|
| 185 |
-
# Exemplos
|
| 186 |
examples = gr.Examples(
|
| 187 |
examples=[
|
| 188 |
["Função Python para calcular fatorial", "pt_BR"],
|
|
@@ -191,7 +194,7 @@ with gr.Blocks(
|
|
| 191 |
["React component for a shopping cart", "en"]
|
| 192 |
],
|
| 193 |
inputs=[input_box, current_lang],
|
| 194 |
-
label="
|
| 195 |
)
|
| 196 |
|
| 197 |
# --- Otimizações Finais --- #
|
|
|
|
| 5 |
import time
|
| 6 |
from typing import Dict
|
| 7 |
import warnings
|
| 8 |
+
from functools import lru_cache # Substitui o cache_resource para compatibilidade
|
| 9 |
|
| 10 |
# --- Configurações Globais --- #
|
| 11 |
+
HF_TOKEN = os.getenv("HUGGINGFACE_TOKEN") # Lê de variáveis de ambiente
|
| 12 |
|
| 13 |
+
# Modelos prioritários com configurações otimizadas
|
| 14 |
MODEL_CONFIGS = {
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
"bigcode/starcoder2-7b": {
|
| 16 |
+
"requires_token": False,
|
| 17 |
+
"params": {"temperature": 0.7, "max_length": 512}
|
| 18 |
},
|
| 19 |
"codellama/CodeLlama-7b-hf": {
|
| 20 |
"requires_token": False,
|
| 21 |
+
"params": {"temperature": 0.6, "max_length": 384}
|
| 22 |
+
},
|
| 23 |
+
"Salesforce/codegen-2B-mono": {
|
| 24 |
+
"requires_token": False,
|
| 25 |
+
"params": {"temperature": 0.5, "max_length": 256}
|
| 26 |
}
|
| 27 |
}
|
| 28 |
|
| 29 |
+
# --- Sistema de Tradução (pt-BR/en) --- #
|
| 30 |
TRANSLATIONS: Dict[str, Dict[str, str]] = {
|
| 31 |
"pt_BR": {
|
| 32 |
"title": "🧑💻 Assistente de Programação IA",
|
|
|
|
| 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",
|
|
|
|
| 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 Otimizada do Modelo --- #
|
| 54 |
+
@lru_cache(maxsize=None) # Cache compatível com todas versões do Gradio
|
| 55 |
def load_model():
|
| 56 |
current_model = None
|
| 57 |
|
|
|
|
| 58 |
for model_name, config in MODEL_CONFIGS.items():
|
| 59 |
try:
|
| 60 |
if config["requires_token"] and not HF_TOKEN:
|
| 61 |
continue
|
| 62 |
|
|
|
|
|
|
|
|
|
|
| 63 |
print(f"⚡ Tentando carregar: {model_name}")
|
| 64 |
start_time = time.time()
|
| 65 |
|
|
|
|
| 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"), "gpt2"
|
| 82 |
|
|
|
|
| 104 |
secondary_hue="gray",
|
| 105 |
font=[gr.themes.GoogleFont("Poppins")]
|
| 106 |
),
|
| 107 |
+
title="AI Code Assistant"
|
| 108 |
) as app:
|
| 109 |
|
| 110 |
# Estado para rastrear o idioma
|
|
|
|
| 117 |
|
| 118 |
with gr.Row():
|
| 119 |
with gr.Column(scale=1):
|
| 120 |
+
# Seletor de idioma
|
| 121 |
lang_radio = gr.Radio(
|
| 122 |
choices=["pt_BR", "en"],
|
| 123 |
value="pt_BR",
|
|
|
|
| 125 |
interactive=True
|
| 126 |
)
|
| 127 |
|
| 128 |
+
# Entrada do usuário
|
| 129 |
input_box = gr.Textbox(
|
| 130 |
lines=5,
|
| 131 |
placeholder="",
|
|
|
|
| 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="",
|
|
|
|
| 146 |
interactive=True
|
| 147 |
)
|
| 148 |
|
| 149 |
+
# --- Lógica de Atualização --- #
|
| 150 |
def update_language(lang):
|
| 151 |
trans = TRANSLATIONS[lang]
|
| 152 |
return [
|
| 153 |
+
gr.Markdown(value=f"## {trans['title']}"), # Título
|
| 154 |
+
gr.Markdown(value=trans['description']), # Descrição
|
| 155 |
+
gr.Textbox(placeholder=trans['input_placeholder']), # Placeholder
|
| 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 |
+
# --- Geração com Feedback Visual --- #
|
| 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=lang_radio,
|
|
|
|
| 185 |
api_name="generate"
|
| 186 |
)
|
| 187 |
|
| 188 |
+
# --- Exemplos Multilíngue --- #
|
| 189 |
examples = gr.Examples(
|
| 190 |
examples=[
|
| 191 |
["Função Python para calcular fatorial", "pt_BR"],
|
|
|
|
| 194 |
["React component for a shopping cart", "en"]
|
| 195 |
],
|
| 196 |
inputs=[input_box, current_lang],
|
| 197 |
+
label=TRANSLATIONS["pt_BR"]["examples_label"] # Atualiza dinamicamente
|
| 198 |
)
|
| 199 |
|
| 200 |
# --- Otimizações Finais --- #
|