Nextspace commited on
Commit
1427492
·
verified ·
1 Parent(s): be0f697

atualizar app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -136
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 # 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",
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 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
 
66
- current_model = pipeline(
67
  "text-generation",
68
  model=model_name,
69
- device_map="auto",
70
  **config["params"]
71
  )
72
 
73
- print(f"✅ {model_name} carregado em {time.time()-start_time:.2f}s")
74
- return current_model, model_name
 
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"), "gpt2"
82
 
83
- # Carrega o modelo e pega seu nome
84
- gerador_codigo, modelo_atual = load_model()
85
 
86
- # --- Função Principal com Monitoramento --- #
87
- def generate_code(prompt: str, lang: str) -> str:
88
  try:
89
- start_time = time.time()
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
- print(f"🔥 Erro crítico: {str(e)}")
98
- return f"{TRANSLATIONS[lang]['error']}: {str(e)}"
99
 
100
- # --- Interface Premium --- #
101
- with gr.Blocks(
102
- theme=gr.themes.Soft(
103
- primary_hue="blue",
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
111
- current_lang = gr.State("pt_BR")
112
 
113
  # Componentes dinâmicos
114
  title = gr.Markdown()
115
- description = gr.Markdown()
116
- model_status = gr.Markdown()
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",
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
- # --- 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,
178
- outputs=[title, description, input_box, btn, output_code, model_status, current_lang]
179
  )
180
 
 
181
  btn.click(
182
- fn=wrapper_generate,
183
- inputs=[input_box, current_lang],
184
- outputs=[output_code, loading_label],
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"],
192
- ["Classe JavaScript para um carro com marca e modelo", "pt_BR"],
193
- ["Python function to connect to MySQL database", "en"],
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 --- #
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",