Nextspace commited on
Commit
2f54d3f
·
verified ·
1 Parent(s): 0ad8035

atualizar app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -120
app.py CHANGED
@@ -1,131 +1,59 @@
1
  from transformers import pipeline
2
- from huggingface_hub import login
3
  import gradio as gr
4
- 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 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",
130
- server_port=int(os.getenv("GRADIO_PORT", 7860))
131
- )
 
1
  from transformers import pipeline
 
2
  import gradio as gr
 
3
  import time
 
 
4
  from functools import lru_cache
5
+ import markdown
6
+
7
+ # --- Configurações do Modelo --- #
8
+ MODEL_NAME = "bigcode/starcoder2-7b" # Modelo principal
9
+ LANGUAGES = {
10
+ "python": {"ext": "py", "icon": "🐍"},
11
+ "javascript": {"ext": "js", "icon": "📜"},
12
+ "java": {"ext": "java", "icon": "☕"},
13
+ "cpp": {"ext": "cpp", "icon": "🖥️"},
14
+ "html": {"ext": "html", "icon": "🌐"},
15
+ "sql": {"ext": "sql", "icon": "🗃️"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  }
17
 
18
+ # --- Cache do Modelo --- #
19
  @lru_cache(maxsize=None)
20
  def load_model():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  try:
22
+ start_time = time.time()
23
+ model = pipeline(
24
+ "text-generation",
25
+ model=MODEL_NAME,
26
+ device_map="auto",
27
+ torch_dtype="auto"
28
+ )
29
+ print(f"✅ Modelo carregado em {time.time()-start_time:.2f}s")
30
+ return model
31
  except Exception as e:
32
+ raise RuntimeError(f"Falha ao carregar modelo: {str(e)}")
33
 
34
+ # --- Geração de Código --- #
35
+ def generate_response(prompt, language, chat_history):
36
+ try:
37
+ model = load_model()
38
+
39
+ # Prompt aprimorado com contexto de linguagem
40
+ system_prompt = f"""Você é um assistente de programação especializado em {language}.
41
+ Gere apenas código {language} funcional e bem documentado.
42
+ Requisitos: {prompt}"""
43
+
44
+ start_time = time.time()
45
+ output = model(
46
+ system_prompt,
47
+ max_length=1024,
48
+ temperature=0.3,
49
+ do_sample=True
50
+ )[0]["generated_text"]
51
+
52
+ # Pós-processamento
53
+ code = output.split("```")[1][len(language)+1:] if "```" in output else output
54
+ exec_time = time.time() - start_time
55
+
56
+ # Formatação Markdown
57
+ response = f"""
58
+ ```{language}
59
+ {code.strip()}