File size: 6,361 Bytes
9112884
 
7440293
9112884
 
 
7440293
 
 
 
9112884
1e03fe2
7440293
1e03fe2
 
 
7440293
029e04b
7440293
1e03fe2
7440293
59f6d1a
 
 
1e03fe2
 
 
029e04b
59f6d1a
d09c7ec
1e03fe2
 
 
 
 
 
59f6d1a
 
7440293
500c0f9
029e04b
1e03fe2
7440293
 
 
 
9112884
7440293
1e03fe2
b6db17e
1e03fe2
 
 
 
b6db17e
1e03fe2
 
 
59f6d1a
1e03fe2
 
 
 
b6db17e
1e03fe2
 
 
 
 
b6db17e
1e03fe2
59f6d1a
7440293
1e03fe2
 
 
 
7440293
 
 
 
9112884
1e03fe2
 
 
 
 
9112884
1e03fe2
 
 
 
 
 
 
 
1950ea9
9381d89
1950ea9
9112884
7440293
 
 
1e03fe2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
029e04b
1e03fe2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
029e04b
9112884
1e03fe2
59f6d1a
7440293
1e03fe2
b6db17e
7440293
1e03fe2
 
7440293
 
9112884
1e03fe2
 
9112884
1e03fe2
9112884
 
 
 
 
1e03fe2
 
9112884
 
 
 
1e03fe2
 
9112884
 
1e03fe2
9112884
 
 
 
 
 
 
 
 
b6db17e
 
1e03fe2
b6db17e
 
9112884
1e03fe2
59f6d1a
1e03fe2
59f6d1a
 
1e03fe2
 
59f6d1a
029e04b
9112884
 
1e03fe2
9112884
 
 
 
 
 
 
1e03fe2
 
 
9112884
 
 
 
1e03fe2
9112884
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
import gradio as gr
from peft import AutoPeftModelForCausalLM
from transformers import AutoTokenizer, GenerationConfig
import torch
import re
import json
import time
import logging
import os
import gc

# Configurações de otimização
os.environ["TOKENIZERS_PARALLELISM"] = "false"
os.environ["OMP_NUM_THREADS"] = "2"
os.environ["MKL_NUM_THREADS"] = "2"
torch.set_num_threads(2)
torch.set_num_interop_threads(1)

logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
log = logging.getLogger("news-filter-gradio")

device = "cpu"
torch.set_default_device(device)

# Carrega modelo e tokenizer
print("🚀 Carregando modelo e tokenizer...")
log.info("🚀 Carregando modelo e tokenizer...")

model = AutoPeftModelForCausalLM.from_pretrained(
    "habulaj/filterinstruct2",
    device_map=device,
    torch_dtype=torch.bfloat16,
    load_in_4bit=False,
    low_cpu_mem_usage=True,
    use_cache=True,
    trust_remote_code=True
)

tokenizer = AutoTokenizer.from_pretrained(
    "habulaj/filterinstruct2",
    use_fast=True,
    padding_side="left"
)

if tokenizer.pad_token is None:
    tokenizer.pad_token = tokenizer.eos_token

model.eval()
log.info("✅ Modelo carregado (eval mode).")

tokenizer.chat_template = """{% for message in messages %}
{%- if message['role'] == 'user' %}
{%- if loop.first %}
<|begin_of_text|><|start_header_id|>user<|end_header_id|>

{{ message['content'] }}<|eot_id|>
{%- else %}
<|start_header_id|>user<|end_header_id|>

{{ message['content'] }}<|eot_id|>
{%- endif %}
{%- elif message['role'] == 'assistant' %}
<|start_header_id|>assistant<|end_header_id|>

{{ message['content'] }}<|eot_id|>
{%- endif %}
{%- endfor %}
{%- if add_generation_prompt %}
<|start_header_id|>assistant<|end_header_id|>

{%- endif %}"""

generation_config = GenerationConfig(
    max_new_tokens=200,
    temperature=1.0,
    min_p=0.1,
    do_sample=True,
    use_cache=True,
    eos_token_id=tokenizer.eos_token_id,
    pad_token_id=tokenizer.eos_token_id,
)

def extract_json(text):
    match = re.search(r'\{.*\}', text, flags=re.DOTALL)
    if match:
        return match.group(0)
    return text

def analyze_news(title, content):
    try:
        log.info(f"🧠 Inferência iniciada para: {title}")
        start_time = time.time()
        
        messages = [
            {
                "role": "user",
                "content": f"""Analyze the news title and content, and return the filters in JSON format with the defined fields.
                
Please respond ONLY with the JSON filter, do NOT add any explanations, system messages, or extra text.

Title: "{title}"
Content: "{content}"
"""
            }
        ]
        
        inputs = tokenizer.apply_chat_template(
            messages,
            tokenize=True,
            add_generation_prompt=True,
            return_tensors="pt",
        )
        
        with torch.no_grad(), torch.inference_mode():
            outputs = model.generate(
                input_ids=inputs,
                generation_config=generation_config,
                num_return_sequences=1,
                output_scores=False,
                return_dict_in_generate=False
            )
        
        prompt_text = tokenizer.decode(inputs[0], skip_special_tokens=False)
        decoded_text = tokenizer.decode(outputs[0], skip_special_tokens=False)
        generated_only = decoded_text[len(prompt_text):].strip()
        json_result = extract_json(generated_only)
        
        duration = time.time() - start_time
        log.info(f"✅ JSON extraído em {duration:.2f}s")
        
        del outputs, inputs
        gc.collect()
        
        try:
            parsed_json = json.loads(json_result)
            return json.dumps(parsed_json, indent=2, ensure_ascii=False)
        except json.JSONDecodeError:
            return json_result
            
    except Exception as e:
        log.exception("❌ Erro inesperado:")
        return f"Erro durante a análise: {str(e)}"

def warmup_model():
    log.info("🔥 Executando warmup...")
    try:
        analyze_news("Test title", "Test content")
        log.info("✅ Warmup concluído.")
    except Exception as e:
        log.warning(f"⚠️ Warmup falhou: {e}")

def create_interface():
    with gr.Blocks(title="Analisador de Notícias", theme=gr.themes.Soft()) as demo:
        
        gr.Markdown("# 📰 Analisador de Notícias")
        
        with gr.Row():
            with gr.Column(scale=1):
                title_input = gr.Textbox(
                    label="Título da Notícia",
                    placeholder="Digite o título da notícia...",
                    lines=2
                )
                
                content_input = gr.Textbox(
                    label="Conteúdo da Notícia",
                    placeholder="Digite o conteúdo da notícia...",
                    lines=6
                )
                
                analyze_btn = gr.Button("🔍 Analisar Notícia", variant="primary")
            
            with gr.Column(scale=1):
                output = gr.Textbox(
                    label="Resultado JSON",
                    lines=15,
                    max_lines=20,
                    show_copy_button=True
                )
                
                status = gr.Textbox(
                    label="Status",
                    value="Aguardando entrada...",
                    interactive=False
                )
        
        def update_status_and_analyze(title, content):
            if not title.strip() or not content.strip():
                return "❌ Preencha título e conteúdo.", "Erro: Campos obrigatórios."
            
            try:
                result = analyze_news(title, content)
                return f"✅ Análise concluída!", result
            except Exception as e:
                return f"❌ Erro: {str(e)}", f"Erro: {str(e)}"
        
        analyze_btn.click(
            fn=update_status_and_analyze,
            inputs=[title_input, content_input],
            outputs=[status, output]
        )
    
    return demo

if __name__ == "__main__":
    warmup_model()
    print("🚀 Iniciando interface Gradio...")
    demo = create_interface()
    demo.launch(
        share=False,
        server_name="0.0.0.0",
        server_port=7860,
        show_error=True
    )