Nextspace commited on
Commit
39a542c
·
verified ·
1 Parent(s): 0ecb04d

atualizar app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -84
app.py CHANGED
@@ -2,9 +2,10 @@ from transformers import pipeline
2
  import gradio as gr
3
  from functools import lru_cache
4
  import time
 
5
 
6
  # --- Configurações do Modelo --- #
7
- MODEL_NAME = "bigcode/starcoder2-7b" # Modelo otimizado para geração de código
8
  SUPPORTED_LANGUAGES = [
9
  "python", "javascript", "typescript",
10
  "java", "c++", "c#", "go", "rust",
@@ -14,72 +15,54 @@ SUPPORTED_LANGUAGES = [
14
  # --- Cache do Modelo --- #
15
  @lru_cache(maxsize=None)
16
  def load_model():
17
- """Carrega o modelo com configurações otimizadas"""
18
  try:
19
- print("⚡ Iniciando carregamento do modelo...")
20
  start_time = time.time()
21
-
22
  model = pipeline(
23
  "text-generation",
24
  model=MODEL_NAME,
25
- device_map="auto", # Usa GPU se disponível
26
- torch_dtype="auto", # Otimiza para o hardware
27
- max_length=1024
28
  )
29
-
30
- load_time = time.time() - start_time
31
- print(f"✅ Modelo carregado em {load_time:.2f} segundos")
32
  return model
33
-
34
  except Exception as e:
35
- print(f"❌ Falha crítica ao carregar modelo: {str(e)}")
36
- raise RuntimeError("Não foi possível carregar o modelo")
37
 
38
- # --- Função de Geração de Código --- #
39
- def generate_code_response(message, history, selected_language):
40
- """Gera código com tratamento de erros robusto"""
41
  try:
42
  model = load_model()
43
- start_time = time.time()
44
-
45
- # Prompt otimizado para geração de código
46
- system_prompt = f"""Você é um assistente especializado em {selected_language}.
47
- Gere SOMENTE código {selected_language} funcional e bem documentado para:
48
  {message}"""
49
 
 
50
  response = model(
51
- system_prompt,
52
- temperature=0.3, # Balanceia criatividade e precisão
53
- do_sample=True,
54
- top_k=50,
55
- max_new_tokens=512
56
  )[0]["generated_text"]
57
 
58
- # Pós-processamento da resposta
59
  if "```" in response:
60
  code = response.split("```")[1][len(selected_language)+1:].strip()
61
  else:
62
  code = response.strip()
63
 
64
- exec_time = time.time() - start_time
65
- formatted_response = f"""```{selected_language}
66
- {code}
67
-
68
- ⏱️ Gerado em {exec_time:.2f}s | 🛠 {selected_language.upper()}"""
69
-
70
- return {"role": "assistant", "content": formatted_response}
71
 
72
  except Exception as e:
73
- error_msg = f"""❌ Erro na geração:
74
- {str(e)}
75
-
76
- Por favor:
77
- 1. Verifique a linguagem selecionada
78
- 2. Simplifique sua solicitação
79
- 3. Tente novamente"""
80
- return {"role": "assistant", "content": error_msg}
81
 
82
- # --- Interface do Usuário --- #
83
  with gr.Blocks(
84
  theme=gr.themes.Soft(
85
  primary_hue="blue",
@@ -88,69 +71,49 @@ with gr.Blocks(
88
  css="""
89
  .chatbot { min-height: 500px; }
90
  .code { max-height: 400px; overflow-y: auto !important; }
91
- .dark .code { background-color: #1e1e1e !important; }
92
  """
93
  ) as app:
94
 
95
- # Layout Principal
96
- gr.Markdown("""
97
- # <center>🧑💻 Assistente de Programação Avançado</center>
98
- <center>Gera código em múltiplas linguagens com precisão</center>
99
- """)
100
 
101
  with gr.Row():
102
  with gr.Column(scale=3):
103
- # Seletor de Linguagem
104
- language_dropdown = gr.Dropdown(
105
  label="🔤 Linguagem de Programação",
106
  choices=SUPPORTED_LANGUAGES,
107
- value="python",
108
- interactive=True
109
  )
110
 
111
- # Chat Interface
112
- chat_interface = gr.ChatInterface(
113
- fn=lambda msg, history: generate_code_response(msg, history, language_dropdown.value),
114
  textbox=gr.Textbox(
115
- placeholder="Descreva o código que precisa (ex: 'função Python para calcular IMC')",
116
- lines=3,
117
- max_lines=5
118
  ),
119
  examples=[
120
- ["Classe Python para representar um carro", "python"],
121
- ["Função JavaScript para validar email", "javascript"],
122
- ["Componente React para botão animado", "typescript"],
123
- ["Consulta SQL para relatório de vendas", "sql"]
124
- ],
125
- cache_examples=True
126
  )
127
 
128
  with gr.Column(scale=2):
129
- # Painel de Informações
130
  gr.Markdown("### 📋 Linguagens Suportadas")
131
  gr.Markdown("""
132
- - **Python** 🐍 (incluindo Pandas, Flask)
133
- - **JavaScript/TypeScript** 📜 (React, Node.js)
134
- - **Java** ☕ (Spring, Android)
135
- - **C++/C#** 🖥️
136
- - **Go/Rust** 🦀
137
- - **Web** 🌐 (HTML, CSS, PHP)
138
- - **Banco de Dados** 🗃️ (SQL)
139
- """)
140
-
141
- gr.Markdown("### 💡 Dicas de Uso")
142
- gr.Markdown("""
143
- 1. Seja específico nos requisitos
144
- 2. Mencione bibliotecas/frameworks
145
- 3. Use os exemplos para começar
146
- 4. Para código complexo, divida em partes
147
- """)
148
 
149
  # --- Configuração de Deploy --- #
150
  if __name__ == "__main__":
151
  app.launch(
152
  server_name="0.0.0.0",
153
  server_port=int(os.getenv("GRADIO_PORT", 7860)),
154
- share=False,
155
- show_error=True
156
  )
 
2
  import gradio as gr
3
  from functools import lru_cache
4
  import time
5
+ import os # Importação adicionada para resolver o NameError
6
 
7
  # --- Configurações do Modelo --- #
8
+ MODEL_NAME = "bigcode/starcoder2-7b"
9
  SUPPORTED_LANGUAGES = [
10
  "python", "javascript", "typescript",
11
  "java", "c++", "c#", "go", "rust",
 
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
 
29
  except Exception as e:
30
+ print(f"❌ Erro ao carregar modelo: {str(e)}")
31
+ raise
32
 
33
+ # --- Função de Geração no Formato OpenAI --- #
34
+ def generate_response(message, history, selected_language):
 
35
  try:
36
  model = load_model()
37
+ prompt = f"""Você é um especialista em {selected_language}.
38
+ Gere SOMENTE código {selected_language} funcional para:
 
 
 
39
  {message}"""
40
 
41
+ start_time = time.time()
42
  response = model(
43
+ prompt,
44
+ max_length=1024,
45
+ temperature=0.3
 
 
46
  )[0]["generated_text"]
47
 
48
+ # Extrai o código da resposta
49
  if "```" in response:
50
  code = response.split("```")[1][len(selected_language)+1:].strip()
51
  else:
52
  code = response.strip()
53
 
54
+ return {
55
+ "role": "assistant",
56
+ "content": f"```{selected_language}\n{code}\n```"
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 Moderna --- #
66
  with gr.Blocks(
67
  theme=gr.themes.Soft(
68
  primary_hue="blue",
 
71
  css="""
72
  .chatbot { min-height: 500px; }
73
  .code { max-height: 400px; overflow-y: auto !important; }
 
74
  """
75
  ) as app:
76
 
77
+ gr.Markdown("# <center>🧑💻 Assistente de Programação Avançado</center>")
 
 
 
 
78
 
79
  with gr.Row():
80
  with gr.Column(scale=3):
81
+ language = gr.Dropdown(
 
82
  label="🔤 Linguagem de Programação",
83
  choices=SUPPORTED_LANGUAGES,
84
+ value="python"
 
85
  )
86
 
87
+ # ChatInterface no formato OpenAI
88
+ chat = gr.ChatInterface(
89
+ lambda msg, history: generate_response(msg, history, language.value),
90
  textbox=gr.Textbox(
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("### 📋 Linguagens Suportadas")
103
  gr.Markdown("""
104
+ - Python 🐍 (incluindo Flask, Django)
105
+ - JavaScript/TypeScript 📜 (React, Node)
106
+ - Java ☕ (Spring, Android)
107
+ - C++/C# 🖥️
108
+ - Go/Rust 🦀
109
+ - Web 🌐 (HTML, CSS, PHP)
110
+ - Banco de Dados 🗃️ (SQL)
111
+ """)
 
 
 
 
 
 
 
 
112
 
113
  # --- Configuração de Deploy --- #
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
  )