File size: 3,761 Bytes
ad41991
ac67b86
1427492
0ecb04d
01b185c
2f54d3f
 
01b185c
 
a6c28a4
2f54d3f
1427492
a6c28a4
29631c9
01b185c
2f54d3f
 
 
 
39a542c
01b185c
 
2f54d3f
39a542c
2f54d3f
29631c9
39a542c
 
ad41991
01b185c
39a542c
2f54d3f
 
01b185c
 
 
 
 
 
 
2f54d3f
39a542c
386665d
39a542c
01b185c
 
 
 
2f54d3f
 
01b185c
 
0ecb04d
01b185c
 
 
 
70f9a89
 
01b185c
70f9a89
01b185c
70f9a89
 
01b185c
70f9a89
 
01b185c
 
70f9a89
 
 
01b185c
70f9a89
 
 
39a542c
01b185c
 
39a542c
70f9a89
 
01b185c
 
 
 
70f9a89
01b185c
 
 
 
70f9a89
 
01b185c
70f9a89
01b185c
 
 
 
 
 
39a542c
70f9a89
01b185c
 
 
 
 
 
 
 
 
 
470d112
386665d
 
0ecb04d
39a542c
01b185c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
from transformers import pipeline
import gradio as gr
from functools import lru_cache
import time
import os

# --- Configurações do Modelo --- #
MODEL_NAME = "codellama/CodeLlama-7b-hf"  # Modelo mais rápido que starcoder
MAX_TOKENS = 512  # Reduzido para respostas mais rápidas

# --- Cache do Modelo --- #
@lru_cache(maxsize=None)
def load_model():
    try:
        print("⚡ Carregando modelo otimizado...")
        start_time = time.time()
        model = pipeline(
            "text-generation",
            model=MODEL_NAME,
            device_map="auto",
            torch_dtype="auto",
            model_kwargs={"load_in_8bit": True}  # Otimização de memória
        )
        print(f"✅ Modelo carregado em {time.time()-start_time:.2f}s")
        return model
    except Exception as e:
        print(f"❌ Erro ao carregar modelo: {str(e)}")
        raise

# --- Função de Geração Otimizada --- #
def generate_response(message, history, selected_language):
    try:
        model = load_model()
        
        # Prompt eficiente
        prompt = f"""Gere SOMENTE o código {selected_language} para: {message}
Instruções:
1. Apenas o código necessário
2. Sem explicações
3. Máximo {MAX_TOKENS} tokens"""
        
        start_time = time.time()
        response = model(
            prompt,
            max_new_tokens=MAX_TOKENS,
            temperature=0.2,  # Menos criativo = mais rápido
            do_sample=True,
            top_k=30
        )[0]["generated_text"]
        
        # Extração eficiente do código
        code = response.split("```")[1][len(selected_language)+1:].strip() if "```" in response else response.strip()
        
        return f"""```{selected_language}
{code}

⏱️ Processado em {time.time()-start_time:.2f}s"""
        
    except Exception as e:
        return f"❌ Erro: {str(e)}"

# --- Interface Leve --- #
with gr.Blocks(
    theme=gr.themes.Soft(
        primary_hue="blue"
    ),
    css="""
    .chatbot { min-height: 400px; }
    .code { max-height: 300px; overflow-y: auto !important; font-size: 0.9em !important; }
    """
) as app:
    
    gr.Markdown("# <center>🧑💻 Assistente Rápido de Programação</center>")
    
    with gr.Row():
        with gr.Column(scale=3):
            language = gr.Dropdown(
                label="🔤 Linguagem",
                choices=["python", "javascript", "java", "cpp", "html", "sql"],
                value="python"
            )
            
            chatbot = gr.Chatbot(height=400)
            msg = gr.Textbox(
                placeholder="Ex: Função para calcular IMC em Python",
                lines=2
            )
            
            with gr.Row():
                submit_btn = gr.Button("🚀 Gerar (Enter)", variant="primary")
                clear_btn = gr.Button("🧹 Limpar")
        
        with gr.Column(scale=2):
            gr.Markdown("### ⚡ Dicas para Respostas Rápidas")
            gr.Markdown("""
- Seja específico nos requisitos
- Evite descrições muito longas
- Exemplos eficientes:
  - "Função Python para fatorial"
  - "Componente React simples"
  - "Consulta SQL para filtrar dados"
""")

    # Eventos Otimizados
    def respond(message, chat_history, lang):
        bot_message = generate_response(message, chat_history, lang)
        chat_history.append((message, bot_message))
        return "", chat_history
    
    msg.submit(respond, [msg, chatbot, language], [msg, chatbot])
    submit_btn.click(respond, [msg, chatbot, language], [msg, chatbot])
    clear_btn.click(lambda: None, None, chatbot, queue=False)

if __name__ == "__main__":
    app.launch(
        server_name="0.0.0.0",
        server_port=int(os.getenv("GRADIO_PORT", 7860)),
        share=False
    )