bgustscraper 0.2.0

Advanced semantic scraping engine with AI-driven compliance checks and legal terms validation
Documentation
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
mod search;
mod worker;
mod extractor;
mod legal;
mod cache;
mod clustering;
mod semantic_extractor;
mod api;
mod auth;
mod schedule_config;
mod scheduler;
mod benchmark;

use anyhow::{Result, anyhow};
use clap::Parser;
use dialoguer::{theme::ColorfulTheme, Input, Select, MultiSelect};
use url::Url;
use crate::worker::{PlaywrightWorker, ScrapingEngine, ScrapeOptions, ScrapeResponse};
use indicatif::{ProgressBar, ProgressStyle, MultiProgress};
use std::time::Duration;
use std::fs;

#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct Args {
    /// URL o Prompt de búsqueda inicial (Posicional)
    input: Option<String>,

    /// Ejecutar en modo daemon (programado) y arrancar Servidor API seguro
    #[arg(short, long)]
    daemon: bool,

    /// Modo visual/interactivo (abre el navegador para resolver CAPTCHAs)
    #[arg(short = 'v', long)]
    interactive: bool,

    /// Prompt de extracción semántica estructurada (Formato JSON)
    #[arg(short = 'e', long)]
    extract: Option<String>,

    /// Ejecutar suite de pruebas de rendimiento (Benchmark completo)
    #[arg(short, long)]
    benchmark: bool,
}

fn print_banner() {
    let banner = r#"
    __                              __                                     
   / /_   ____ _ __  __ _____ / /_ _____ _____  _____ ____ _ ____   ___   _____
  / __ \ / __ `// / / // ___// __// ___// ___// __ `// __ `// __ \ / _ \ / ___/
 / /_/ // /_/ // /_/ /(__  )/ /_ / /   / /__ / /_/ // /_/ // /_/ //  __// /    
/_.___/ \__, / \__,_//____/ \__/ /_/    \___/ \__,_/ \__,_// .___/ \___//_/     
       /____/                                             /_/                   
    "#;
    println!("{}", banner);
    println!("--- Ingesta Robusta, Legal y Semántica (v0.1.0) ---\n");
}

#[tokio::main]
async fn main() -> Result<()> {
    let args = Args::parse();

    // 1. Escenario de Ejecución: Benchmark completo
    if args.benchmark {
        print_banner();
        benchmark::run_benchmark()?;
        return Ok(());
    }

    // 2. Escenario de Ejecución: Daemon de Agenda + Servidor Web API Seguro
    if args.daemon {
        print_banner();
        println!("⚙️  Iniciando bgustscraper en modo Daemon + Servidor API...");
        
        // Arrancar el planificador asíncrono en segundo plano
        tokio::spawn(async {
            if let Err(e) = scheduler::run_scheduler_daemon().await {
                eprintln!("⚠️ Error crítico en el planificador daemon: {}", e);
            }
        });

        // Levantar el servidor web seguro Axum (Bloqueante en la tarea principal)
        api::start_api_server(8080).await?;
        return Ok(());
    }

    print_banner();
    let mut interactive_args = args;

    loop {
        let input_val = match interactive_args.input.take() {
            Some(i) => i,
            None => {
                Input::<String>::with_theme(&ColorfulTheme::default())
                    .with_prompt("🔍 Introduce una URL o un Prompt de búsqueda")
                    .interact_text()?
            }
        };

        match process_input(&input_val, interactive_args.interactive, interactive_args.extract.as_deref()).await {
            Ok(_) => {
                let retry = dialoguer::Confirm::with_theme(&ColorfulTheme::default())
                    .with_prompt("¿Deseas realizar otra búsqueda?")
                    .default(false)
                    .interact()?;
                
                if !retry { break; }
            }
            Err(e) => {
                println!("\n❌ Lo siento, no he podido conseguir el documento. {}", e);
                let retry = dialoguer::Confirm::with_theme(&ColorfulTheme::default())
                    .with_prompt("¿Quieres intentarlo de nuevo con alguna otra búsqueda?")
                    .default(true)
                    .interact()?;
                
                if !retry { break; }
            }
        }
    }

    Ok(())
}

async fn process_input(input: &str, interactive: bool, extract_prompt: Option<&str>) -> Result<()> {
    let multi = MultiProgress::new();
    let pb = multi.add(ProgressBar::new_spinner());
    
    pb.set_style(ProgressStyle::default_spinner()
        .tick_chars("⠁⠂⠄⡀⢀⠠⠐⠈ ")
        .template("{spinner:.green} {msg}")?);
    
    if interactive {
        pb.println("🖥️  [MODO VISUAL] Preparando ventana de Chromium...");
    }

    pb.set_message("Iniciando motores...");
    pb.enable_steady_tick(Duration::from_millis(100));

    let mut worker = match PlaywrightWorker::new(!interactive, ScrapingEngine::Playwright) {
        Ok(w) => w,
        Err(e) => {
            pb.finish_with_message("❌ Error al iniciar Playwright.");
            return Err(e);
        }
    };

    let cache = cache::LocalCache::new()?;

    let target_urls = if is_url(input) {
        pb.set_message(format!("Analizando URL directa: {}", input));
        vec![input.to_string()]
    } else {
        pb.set_message(format!("Buscando fuentes para: '{}'...", input));
        let urls = search::search_duckduckgo(input).await?;
        
        if urls.is_empty() {
            pb.finish_with_message("⚠️ No se encontraron resultados para el prompt.");
            worker.exit()?;
            return Err(anyhow!("No se encontraron fuentes para el prompt."));
        }

        pb.set_message(format!("Se encontraron {} fuentes potenciales.", urls.len()));
        pb.suspend(|| {
            let mut items = vec!["Todas las fuentes".to_string()];
            items.extend(urls.clone());
            let selection = Select::with_theme(&ColorfulTheme::default())
                .with_prompt("Selecciona una fuente")
                .items(&items)
                .default(0)
                .interact()?;
            
            if selection == 0 { 
                Ok::<Vec<String>, anyhow::Error>(urls) 
            } else { 
                Ok(vec![urls[selection - 1].clone()]) 
            }
        })?
    };

    let mut found_any = false;
    for url in target_urls {
        pb.set_message(format!("🚀 Navegando a: {}", url));
        let cache_key = format!("scrape:{}", url);

        let response = match cache.get(&cache_key) {
            Ok(Some(cached_json)) => {
                pb.set_message("⚡ Recuperando datos de caché persistente (redb)...");
                serde_json::from_str::<ScrapeResponse>(&cached_json)?
            }
            _ => {
                pb.set_message(format!("📡 Conectando con {}...", url));
                tokio::time::sleep(Duration::from_millis(500)).await;
                let scrape_opts = ScrapeOptions {
                    deep_scan: false,
                    semantic_embeddings: Some(true),
                    text: None,
                    prompt: None,
                };
                
                let mut resp = worker.scrape(&url, Some(scrape_opts))?;
                
                if resp.status == "error" || resp.html.as_ref().map_or(true, |h| h.contains("cf-challenge") || h.contains("Checking your browser")) {
                    pb.set_message("🔄 Playwright bloqueado. Intentando Motor 2 (Cloudscraper)...");
                    worker.exit()?;
                    worker = PlaywrightWorker::new(true, ScrapingEngine::Cloudscraper)?;
                    resp = worker.scrape(&url, None)?;
                }
                
                if resp.status == "success" {
                    if let Ok(resp_json) = serde_json::to_string(&resp) {
                        let _ = cache.set(&cache_key, &resp_json);
                    }
                }
                resp
            }
        };

        if response.status == "success" {
            let mut html = response.html.clone().unwrap_or_default();
            let markdown = response.markdown.clone().unwrap_or_default();
            
            pb.set_message("🧩 Analizando estructura del sitio...");
            tokio::time::sleep(Duration::from_millis(800)).await;

            pb.set_message("⚖️ Consultando cumplimiento legal...");
            let legal_links = legal::find_legal_links(&html, &url);
            let mut is_allowed = true;
            
            if !legal_links.is_empty() {
                pb.set_message(format!("📖 Leyendo términos en: {}", legal_links[0]));
                let legal_resp = worker.scrape(&legal_links[0], None)?;
                if let Some(legal_html) = legal_resp.html {
                    let status = legal::analyze_legal_text(&legal_html).await?;
                    pb.set_message(format!("✅ Análisis Legal: {}", status.reasoning));
                    is_allowed = status.allowed;
                }
            }

            if !is_allowed {
                pb.set_message("🚫 Abortando por restricciones legales.");
                continue;
            }

            // 1. Compresión semántica mediante clustering de oraciones (K-Means)
            let compressed_text = if let (Some(sentences), Some(embeddings)) = (&response.sentences, &response.embeddings) {
                pb.set_message("🧠 Comprimiendo contenido semánticamente (K-Means)...");
                let summary_sentences = clustering::compress_text_by_clustering(sentences, embeddings, 12);
                pb.set_message("✅ Contenido comprimido semánticamente.");
                summary_sentences.join("\n")
            } else {
                // Fallback si no hay oraciones vectorizadas: usar parte del markdown crudo
                markdown.chars().take(2000).collect()
            };

            // 2. Comprobar si estamos en Modo Extracción Estructurada Genérica (--extract)
            if let Some(prompt) = extract_prompt {
                pb.set_message("🔮 Ejecutando consulta de extracción semántica estructurada...");
                let extract_opts = ScrapeOptions {
                    deep_scan: false,
                    semantic_embeddings: None,
                    text: Some(compressed_text.clone()),
                    prompt: Some(prompt.to_string()),
                };
                
                let extract_resp = worker.scrape("extract", Some(extract_opts))?;
                if extract_resp.status == "success" {
                    if let Some(data) = extract_resp.data {
                        pb.finish_with_message("✨ ¡Extracción semántica exitosa!");
                        println!("\n📊 Datos extraídos en formato estructurado JSON:");
                        println!("{}", serde_json::to_string_pretty(&data)?);
                        
                        // Guardar en la carpeta downloads
                        fs::create_dir_all("downloads")?;
                        let timestamp = std::time::SystemTime::now()
                            .duration_since(std::time::UNIX_EPOCH)
                            .unwrap()
                            .as_secs();
                        let filename = format!("downloads/extraction_{}.json", timestamp);
                        fs::write(&filename, serde_json::to_string_pretty(&data)?)?;
                        println!("\n💾 Archivo guardado con éxito en: {}", filename);
                        found_any = true;
                        break;
                    }
                } else {
                    pb.finish_with_message("❌ Error en extracción.");
                    return Err(anyhow!("La extracción falló: {}", extract_resp.message.unwrap_or_default()));
                }
            }

            // 3. Modo Ingestor/Descargador de Documentos por Defecto
            pb.set_message("🔎 Escaneando en busca de documentos...");
            
            // 3.1 Detección Sintáctica (HTML tags)
            let mut docs = extractor::find_documents(&html, &url);

            // 3.2 Deep Scan si es necesario
            if docs.is_empty() && matches!(worker.engine, ScrapingEngine::Playwright) {
                pb.set_message("🕵️ No se hallaron documentos directos. Activando Deep Scan...");
                let deep_resp = worker.scrape(&url, Some(ScrapeOptions { 
                    deep_scan: true,
                    semantic_embeddings: None,
                    text: None,
                    prompt: None
                }))?;
                if deep_resp.status == "success" {
                    html = deep_resp.html.unwrap();
                    docs = extractor::find_documents(&html, &url);
                }
            }

            // 3.3 Detección Semántica con Qwen (Hugging Face local)
            pb.set_message("🧠 Analizando texto semánticamente para detectar más documentos...");
            if let Ok(semantic_docs) = semantic_extractor::extract_semantic_documents(&mut worker, &compressed_text, &url) {
                if !semantic_docs.is_empty() {
                    pb.set_message(format!("✨ Encontrados {} documentos por vía semántica.", semantic_docs.len()));
                    // Combinar ambos listados, evitando duplicar URLs
                    for sem_doc in semantic_docs {
                        if !docs.iter().any(|d| d.url == sem_doc.url) {
                            docs.push(extractor::ExtractedDocument {
                                url: sem_doc.url,
                                extension: sem_doc.extension,
                                name: format!("{} [Categoría: {}] - Resumen: {}", sem_doc.name, sem_doc.category, sem_doc.summary),
                            });
                        }
                    }
                }
            }
            
            if docs.is_empty() {
                if html.contains("cf-challenge") || html.contains("Checking your browser") || html.contains("captcha") {
                    pb.set_message("⚠️ Bloqueo de seguridad detectado.");
                } else {
                    pb.set_message("📭 No se hallaron documentos.");
                }
                tokio::time::sleep(Duration::from_millis(2000)).await;
            } else {
                found_any = true;
                pb.set_message(format!("✨ ¡Éxito! {} documentos encontrados.", docs.len()));
                let selections = pb.suspend(|| {
                    println!("\n📂 Documentos disponibles en {}:", url);
                    let mut choices = Vec::new();
                    for (i, doc) in docs.iter().enumerate() {
                        choices.push(format!("{}. {}", i + 1, doc.name));
                    }

                    MultiSelect::with_theme(&ColorfulTheme::default())
                        .with_prompt("Marca los archivos que deseas descargar")
                        .items(&choices)
                        .interact()
                })?;

                if !selections.is_empty() {
                    fs::create_dir_all("downloads")?;
                    for index in selections {
                        let doc = &docs[index];
                        let clean_filename = doc.url.split('/').last()
                            .unwrap_or("descarga.bin")
                            .split('?').next()
                            .unwrap_or("descarga.bin");
                        let dl_pb = multi.add(ProgressBar::new(0));
                        dl_pb.set_style(ProgressStyle::default_bar()
                            .template("{msg}\n{spinner:.green} [{elapsed_precise}] [{wide_bar:.cyan/blue}] {bytes}/{total_bytes}")?
                            .progress_chars("#>-"));
                        dl_pb.set_message(format!("📥 Descargando: {}", clean_filename));

                        if let Err(e) = download_file_with_progress(&doc.url, clean_filename, &dl_pb).await {
                            dl_pb.finish_with_message(format!("❌ Error: {}", e));
                        } else {
                            dl_pb.finish_with_message(format!("✅ Descargado: {}", clean_filename));
                        }
                    }
                }
            }
        } else {
            pb.set_message(format!("❌ Error: {}", response.message.unwrap_or_default()));
        }
    }

    pb.set_message("Finalizando sesión...");
    worker.exit()?;
    
    if !found_any {
        pb.finish_and_clear();
        return Err(anyhow!("No se encontraron documentos en las fuentes analizadas."));
    }

    pb.finish_with_message("🏁 ¡Todo listo! Revisa la carpeta 'downloads'.");
    Ok(())
}

fn is_url(input: &str) -> bool {
    Url::parse(input).is_ok()
}

async fn download_file_with_progress(url: &str, filename: &str, pb: &ProgressBar) -> Result<()> {
    let mut fixed_url = url.to_string();
    if fixed_url.contains(".tsj.gov.ve") {
        fixed_url = fixed_url.replace(".tsj.gov.ve", ".tsj.gob.ve");
    }

    let client = reqwest::Client::builder()
        .danger_accept_invalid_certs(true)
        .user_agent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
        .build()?;

    let res = client.get(&fixed_url).send().await?;
    
    if !res.status().is_success() {
        return Err(anyhow!("Error del servidor: {}", res.status()));
    }

    let total_size = res.content_length().unwrap_or(0);
    pb.set_length(total_size);

    let path = format!("downloads/{}", filename);
    let mut file = std::fs::File::create(path)?;
    let mut stream = res.bytes_stream();
    use futures_util::StreamExt;

    while let Some(item) = stream.next().await {
        let chunk = item?;
        use std::io::Write;
        file.write_all(&chunk)?;
        pb.inc(chunk.len() as u64);
    }

    Ok(())
}