Nextspace commited on
Commit
0ecb04d
·
verified ·
1 Parent(s): 7cbfed3

atualizar app.py

Browse files
Files changed (1) hide show
  1. app.py +98 -50
app.py CHANGED
@@ -1,108 +1,156 @@
1
  from transformers import pipeline
2
  import gradio as gr
3
- import time
4
  from functools import lru_cache
 
5
 
6
  # --- Configurações do Modelo --- #
7
- MODEL_NAME = "bigcode/starcoder2-7b" # Modelo principal otimizado
8
- LANGUAGES = ["python", "javascript", "java", "cpp", "html", "sql"]
 
 
 
 
9
 
10
  # --- Cache do Modelo --- #
11
  @lru_cache(maxsize=None)
12
  def load_model():
 
13
  try:
14
- print("⚡ Carregando modelo...")
15
  start_time = time.time()
 
16
  model = pipeline(
17
  "text-generation",
18
  model=MODEL_NAME,
19
- device_map="auto",
20
- torch_dtype="auto"
 
21
  )
22
- print(f"✅ Modelo carregado em {time.time()-start_time:.2f}s")
 
 
23
  return model
 
24
  except Exception as e:
25
- raise RuntimeError(f"❌ Falha ao carregar modelo: {str(e)}")
 
26
 
27
- # --- Função de Geração no Formato OpenAI --- #
28
- def generate_response(message, history, language):
 
29
  try:
30
  model = load_model()
31
- prompt = f"""Você é um especialista em {language}. Gere código {language} funcional para:
 
 
 
 
32
  {message}"""
33
 
34
- start_time = time.time()
35
  response = model(
36
- prompt,
37
- max_length=1024,
38
- temperature=0.3
 
 
39
  )[0]["generated_text"]
40
 
41
- # Extrai o código da resposta
42
- code = response.split("```")[1][len(language)+1:] if "```" in response else response
43
- return {"role": "assistant", "content": f"```{language}\n{code.strip()}\n```"}
 
 
 
 
 
 
 
 
 
 
44
 
45
  except Exception as e:
46
- return {"role": "assistant", "content": f"❌ Erro: {str(e)}"}
 
 
 
 
 
 
 
47
 
48
- # --- Interface Moderna --- #
49
  with gr.Blocks(
50
  theme=gr.themes.Soft(
51
  primary_hue="blue",
52
  font=[gr.themes.GoogleFont("Inter")]
53
  ),
54
  css="""
55
- .chatbot {height: 500px;}
56
- .code {max-height: 400px; overflow-y: auto;}
 
57
  """
58
  ) as app:
59
 
60
- gr.Markdown("# <center>🧑💻 Assistente de Programação Avançado</center>")
 
 
 
 
61
 
62
  with gr.Row():
63
  with gr.Column(scale=3):
64
- language = gr.Dropdown(
65
- label="Selecione a Linguagem",
66
- choices=LANGUAGES,
67
- value="python"
 
 
68
  )
69
 
70
- # ChatInterface moderno
71
  chat_interface = gr.ChatInterface(
72
- lambda msg, history: generate_response(msg, history, language.value),
73
  textbox=gr.Textbox(
74
- placeholder="Descreva o código que precisa...",
75
- lines=3
 
76
  ),
77
  examples=[
78
- ["Função Python para calcular Fibonacci"],
79
- ["Componente React em JavaScript"],
80
- ["Classe Java para conexão MySQL"]
81
- ]
 
 
82
  )
83
 
84
  with gr.Column(scale=2):
 
85
  gr.Markdown("### 📋 Linguagens Suportadas")
86
  gr.Markdown("""
87
- - Python 🐍
88
- - JavaScript 📜
89
- - Java ☕
90
- - C++ 🖥️
91
- - HTML 🌐
92
- - SQL 🗃️
93
- """)
 
94
 
95
- gr.Markdown("### ⚡ Dicas")
96
  gr.Markdown("""
97
- 1. Seja específico nos requisitos
98
- 2. Mencione bibliotecas se necessário
99
- 3. Use os exemplos para começar
100
- """)
 
101
 
102
- # --- Configurações de Deploy --- #
103
  if __name__ == "__main__":
104
  app.launch(
105
  server_name="0.0.0.0",
106
- server_port=7860,
107
- share=False
 
108
  )
 
1
  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",
11
+ "html", "css", "sql", "php"
12
+ ]
13
 
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",
86
  font=[gr.themes.GoogleFont("Inter")]
87
  ),
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
  )