caarleexx commited on
Commit
1147bf9
·
verified ·
1 Parent(s): 27a8bd8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -481
app.py CHANGED
@@ -1,3 +1,4 @@
 
1
  import os
2
  import sys
3
  import json
@@ -257,8 +258,16 @@ PAYLOAD_MINIMO = {
257
  "track_total_hits": True
258
  }
259
 
260
- # Payload para busca por ID
261
- PAYLOAD_POR_ID = {
 
 
 
 
 
 
 
 
262
  "query": {"ids": {"values": []}},
263
  "_source": PAYLOAD_COMPLETO["_source"],
264
  "size": 1
@@ -278,484 +287,10 @@ HEADERS = {
278
  token_cache = {"token": None, "expires_at": 0}
279
 
280
  # ============================================
281
- # HTML TEMPLATE COMPLETO
282
  # ============================================
283
  HTML_TEMPLATE = """
284
- <!DOCTYPE html>
285
- <html>
286
- <head>
287
- <title>⚖️ STF Jurisprudência - Visualizador Completo</title>
288
- <meta charset="utf-8">
289
- <meta name="viewport" content="width=device-width, initial-scale=1">
290
- <style>
291
- body { font-family: 'Segoe UI', Roboto, system-ui, sans-serif; max-width: 1600px; margin: 0 auto; padding: 20px; background: #f0f2f5; }
292
- .container { background: white; border-radius: 12px; padding: 30px; box-shadow: 0 8px 20px rgba(0,0,0,0.1); }
293
- h1 { color: #1a1a2e; border-bottom: 3px solid #4CAF50; padding-bottom: 15px; display: flex; align-items: center; gap: 10px; }
294
- h1:before { content: "⚖️"; font-size: 1.2em; }
295
- h2 { color: #2c3e50; margin-top: 25px; margin-bottom: 15px; font-size: 1.5em; border-left: 5px solid #4CAF50; padding-left: 15px; }
296
- h3 { color: #34495e; margin-top: 20px; margin-bottom: 10px; font-size: 1.2em; border-bottom: 1px solid #e0e0e0; padding-bottom: 8px; }
297
- .info-box { background: #e8f0fe; border-left: 5px solid #2196F3; padding: 15px 20px; margin: 20px 0; border-radius: 8px; }
298
- .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin: 25px 0; }
299
- .stat-card { background: white; border: 1px solid #e0e0e0; border-radius: 10px; padding: 20px; text-align: center; box-shadow: 0 2px 8px rgba(0,0,0,0.05); }
300
- .stat-value { font-size: 32px; font-weight: bold; color: #1a73e8; }
301
- .stat-label { color: #5f6368; font-size: 14px; margin-top: 8px; text-transform: uppercase; letter-spacing: 0.5px; }
302
- .button-group { display: flex; gap: 15px; flex-wrap: wrap; margin: 25px 0; }
303
- button { background: #1a73e8; color: white; border: none; padding: 14px 28px; font-size: 16px; font-weight: 500; border-radius: 8px; cursor: pointer; transition: all 0.3s; display: inline-flex; align-items: center; gap: 10px; box-shadow: 0 2px 8px rgba(26,115,232,0.3); }
304
- button:hover { background: #1557b0; transform: translateY(-2px); box-shadow: 0 4px 12px rgba(26,115,232,0.4); }
305
- button:disabled { background: #a0a0a0; cursor: not-allowed; transform: none; box-shadow: none; }
306
- button.secondary { background: #34a853; }
307
- button.secondary:hover { background: #2d8745; }
308
- button.download { background: #f9ab00; color: #1a1a2e; }
309
- button.download:hover { background: #e69c00; }
310
- .loading { display: inline-block; width: 20px; height: 20px; border: 3px solid rgba(255,255,255,0.3); border-top: 3px solid white; border-radius: 50%; animation: spin 1s linear infinite; margin-right: 10px; vertical-align: middle; }
311
- @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
312
- pre { background: #f8f9fa; border: 1px solid #e0e0e0; border-radius: 10px; padding: 20px; overflow: auto; max-height: 800px; font-size: 13px; font-family: 'Consolas', 'Monaco', monospace; box-shadow: inset 0 2px 4px rgba(0,0,0,0.05); }
313
- .success { color: #0f9d58; background: #e6f4ea; border-left: 5px solid #34a853; padding: 15px 20px; margin: 15px 0; border-radius: 8px; font-weight: 500; }
314
- .error { color: #d93025; background: #fce8e6; border-left: 5px solid #ea4335; padding: 15px 20px; margin: 15px 0; border-radius: 8px; font-weight: 500; }
315
- .warning { color: #e37400; background: #fef7e0; border-left: 5px solid #f9ab00; padding: 15px 20px; margin: 15px 0; border-radius: 8px; font-weight: 500; }
316
- .token-box { background: #1a1a2e; color: #e0e0e0; padding: 15px; border-radius: 8px; font-family: 'Consolas', monospace; word-break: break-all; margin: 15px 0; border: 1px solid #2a2a3e; }
317
- .token-label { color: #f9ab00; font-weight: bold; margin-bottom: 8px; display: block; }
318
- .filters { background: #f8f9fa; border-radius: 8px; padding: 20px; margin: 20px 0; border: 1px solid #e0e0e0; }
319
- .filter-group { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; align-items: end; }
320
- .filter-item { min-width: 200px; }
321
- .filter-item label { display: block; margin-bottom: 8px; color: #5f6368; font-size: 14px; font-weight: 500; }
322
- .filter-item input, .filter-item select { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; font-size: 14px; }
323
- .filter-item input:focus, .filter-item select:focus { outline: none; border-color: #1a73e8; box-shadow: 0 0 0 2px rgba(26,115,232,0.2); }
324
- .badge { display: inline-block; background: #e8f0fe; color: #1a73e8; padding: 4px 12px; border-radius: 20px; font-size: 13px; font-weight: 500; margin: 2px; }
325
- .campo-lista { background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 15px; margin: 10px 0; }
326
- .campo-nome { font-weight: bold; color: #2c3e50; font-size: 14px; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 5px; }
327
- .campo-valor { color: #1a1a2e; font-size: 14px; word-break: break-word; font-family: 'Consolas', monospace; background: white; padding: 8px; border-radius: 4px; border: 1px solid #e0e0e0; }
328
- .campo-vazio { color: #999; font-style: italic; }
329
- .texto-completo { max-height: 400px; overflow-y: auto; background: #f1f8fe; padding: 15px; border-radius: 8px; border: 1px solid #b8daf5; margin: 10px 0; white-space: pre-wrap; font-family: inherit; line-height: 1.5; }
330
- .nav-tabs { display: flex; gap: 5px; margin: 20px 0; flex-wrap: wrap; border-bottom: 2px solid #e0e0e0; padding-bottom: 10px; }
331
- .nav-tab { padding: 10px 20px; cursor: pointer; background: white; border: 1px solid #e0e0e0; border-radius: 8px 8px 0 0; margin-bottom: -2px; font-weight: 500; transition: all 0.2s; }
332
- .nav-tab:hover { background: #f0f0f0; }
333
- .nav-tab.active { background: #1a73e8; color: white; border-color: #1a73e8; }
334
- .tab-content { display: none; padding: 20px; background: white; border: 1px solid #e0e0e0; border-top: none; border-radius: 0 0 8px 8px; }
335
- .tab-content.active { display: block; }
336
- .campo-card { background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 15px; margin: 10px 0; transition: all 0.2s; }
337
- .campo-card:hover { box-shadow: 0 4px 12px rgba(0,0,0,0.1); border-color: #1a73e8; }
338
- .flag-true { color: #0f9d58; font-weight: bold; }
339
- .flag-false { color: #d93025; }
340
- .url-link { color: #1a73e8; text-decoration: none; word-break: break-all; }
341
- .url-link:hover { text-decoration: underline; }
342
- .highlight { background-color: #f9ab00; color: #1a1a2e; font-weight: bold; padding: 2px 4px; border-radius: 4px; }
343
- .highlight-box { background: #fef7e0; border: 1px solid #f9ab00; padding: 10px; border-radius: 8px; margin: 10px 0; }
344
- .highlight-title { font-weight: bold; color: #e37400; margin-bottom: 5px; }
345
- </style>
346
- </head>
347
- <body>
348
- <div class="container">
349
- <h1>STF Jurisprudência - Visualizador Completo</h1>
350
-
351
- <div class="info-box">
352
- <strong>📌 API de Jurisprudência do STF - Todos os Campos com Highlight</strong><br>
353
- • Total de campos disponíveis: <span id="totalCampos">102</span><br>
354
- • Campos com highlight: 22 campos configurados<br>
355
- • Documentos disponíveis: <span id="totalDocs">carregando...</span>
356
- </div>
357
-
358
- <div class="stats-grid">
359
- <div class="stat-card"><div class="stat-value" id="requestsCount">0</div><div class="stat-label">Requisições</div></div>
360
- <div class="stat-card"><div class="stat-value" id="successCount">0</div><div class="stat-label">Sucessos</div></div>
361
- <div class="stat-card"><div class="stat-value" id="failCount">0</div><div class="stat-label">Falhas</div></div>
362
- <div class="stat-card"><div class="stat-value" id="docsCount">0</div><div class="stat-label">Docs Obtidos</div></div>
363
- </div>
364
-
365
- <div class="filters">
366
- <h3 style="margin-top: 0;">🔍 Filtros de Busca</h3>
367
- <div class="filter-group">
368
- <div class="filter-item">
369
- <label>Quantidade</label>
370
- <select id="pageSize">
371
- <option value="5">5 resultados</option>
372
- <option value="10">10 resultados</option>
373
- <option value="25">25 resultados</option>
374
- <option value="50">50 resultados</option>
375
- <option value="100" selected>100 resultados</option>
376
- </select>
377
- </div>
378
- <div class="filter-item">
379
- <label>Ordenar por</label>
380
- <select id="sortOrder">
381
- <option value="desc">Mais recentes</option>
382
- <option value="asc">Mais antigos</option>
383
- </select>
384
- </div>
385
- <div class="filter-item">
386
- <label>Base</label>
387
- <select id="base">
388
- <option value="acordaos">Acórdãos</option>
389
- <option value="decisoes">Decisões</option>
390
- <option value="sumulas">Súmulas</option>
391
- <option value="informativos">Informativos</option>
392
- <option value="">Todas</option>
393
- </select>
394
- </div>
395
- <div class="filter-item">
396
- <label>Busca por ID</label>
397
- <input type="text" id="docId" placeholder="Ex: sjur505215">
398
- </div>
399
- </div>
400
- </div>
401
-
402
- <div class="button-group">
403
- <button id="testBtn" onclick="runSearch()">
404
- <span class="loading" id="loading" style="display: none;"></span>
405
- <span>🔍 Buscar Documentos</span>
406
- </button>
407
- <button id="getByIdBtn" class="secondary" onclick="getDocumentById()">
408
- <span>📄 Buscar por ID</span>
409
- </button>
410
- <button id="downloadBtn" class="download" onclick="downloadJSON()" disabled>
411
- 📥 Download JSON
412
- </button>
413
- <button id="copyBtn" class="secondary" onclick="copyToken()">
414
- 🔑 Copiar Token
415
- </button>
416
- </div>
417
-
418
- <div id="tokenDisplay" style="display: none;" class="token-box">
419
- <span class="token-label">🔐 Token AWS WAF</span>
420
- <span id="tokenValue"></span>
421
- </div>
422
-
423
- <div id="result" style="margin-top: 25px;"></div>
424
- </div>
425
-
426
- <script>
427
- let lastResult = null;
428
- let lastToken = null;
429
- let requestsCount = 0, successCount = 0, failCount = 0, docsCount = 0;
430
-
431
- function renderCampo(nome, valor, tipo = 'normal') {
432
- if (valor === null || valor === undefined || valor === '') {
433
- return `<div class="campo-card"><div class="campo-nome">${nome}</div><div class="campo-vazio">(vazio)</div></div>`;
434
- }
435
- if (tipo === 'url' && valor) {
436
- return `<div class="campo-card"><div class="campo-nome">${nome}</div><div class="campo-valor"><a href="${valor}" target="_blank" class="url-link">${valor}</a></div></div>`;
437
- }
438
- if (tipo === 'flag') {
439
- const flagClass = valor ? 'flag-true' : 'flag-false';
440
- return `<div class="campo-card"><div class="campo-nome">${nome}</div><div class="campo-valor ${flagClass}">${valor ? '✓ Sim' : '✗ Não'}</div></div>`;
441
- }
442
- if (tipo === 'texto' && valor && valor.length > 200) {
443
- return `<div class="campo-card"><div class="campo-nome">${nome}</div><div class="texto-completo">${valor.replace(/\\n/g, '<br>').replace(/<em>/g, '<span class="highlight">').replace(/<\\/em>/g, '</span>')}</div></div>`;
444
- }
445
- if (Array.isArray(valor)) {
446
- return `<div class="campo-card"><div class="campo-nome">${nome}</div><div class="campo-valor">${valor.join('<br>')}</div></div>`;
447
- }
448
- return `<div class="campo-card"><div class="campo-nome">${nome}</div><div class="campo-valor">${String(valor).replace(/\\n/g, '<br>').replace(/<em>/g, '<span class="highlight">').replace(/<\\/em>/g, '</span>')}</div></div>`;
449
- }
450
-
451
- function renderHighlight(highlight) {
452
- if (!highlight) return '';
453
- let html = '<div class="highlight-box"><div class="highlight-title">🔆 Termos destacados (highlight):</div>';
454
- for (const [campo, valores] of Object.entries(highlight)) {
455
- if (valores && valores.length > 0) {
456
- html += `<div><strong>${campo}:</strong> `;
457
- valores.forEach(valor => {
458
- html += `<div style="margin-left: 20px; margin-top: 5px;">${valor.replace(/<em>/g, '<span class="highlight">').replace(/<\\/em>/g, '</span>')}</div>`;
459
- });
460
- html += '</div>';
461
- }
462
- }
463
- html += '</div>';
464
- return html;
465
- }
466
-
467
- function displayResult(data) {
468
- if (!data || !data.result || !data.result.hits || !data.result.hits.hits || data.result.hits.hits.length === 0) {
469
- document.getElementById('result').innerHTML = '<div class="warning">⚠️ Nenhum documento encontrado</div>';
470
- return;
471
- }
472
-
473
- const hits = data.result.hits.hits;
474
- const total = data.result.hits.total?.value || 0;
475
-
476
- let html = `<div class="success">✅ Encontrados ${total.toLocaleString()} documentos. Exibindo ${hits.length} resultados.</div>`;
477
-
478
- hits.forEach((hit, index) => {
479
- const source = hit._source || {};
480
- const highlight = hit.highlight || {};
481
- const docId = source.id || hit._id || `doc_${index}`;
482
-
483
- html += `<div class="campo-lista" style="margin-top: 30px;">`;
484
- html += `<h3 style="display: flex; justify-content: space-between; align-items: center;">
485
- <span>📄 Documento ${index + 1}: ${source.titulo || source.processo_codigo_completo || docId}</span>
486
- <span class="badge">ID: ${docId}</span>
487
- </h3>`;
488
-
489
- // Abas internas para cada documento
490
- html += `<div style="display: flex; gap: 5px; margin: 15px 0; flex-wrap: wrap;">`;
491
- html += `<button class="badge" style="cursor: pointer;" onclick="showDocTab('geral-${index}')">📋 Geral</button>`;
492
- html += `<button class="badge" style="cursor: pointer;" onclick="showDocTab('ementa-${index}')">📝 Ementa</button>`;
493
- html += `<button class="badge" style="cursor: pointer;" onclick="showDocTab('acordao-${index}')">⚖️ Acórdão</button>`;
494
- html += `<button class="badge" style="cursor: pointer;" onclick="showDocTab('legislacao-${index}')">📚 Legislação</button>`;
495
- html += `<button class="badge" style="cursor: pointer;" onclick="showDocTab('highlight-${index}')">🔆 Highlight</button>`;
496
- html += `<button class="badge" style="cursor: pointer;" onclick="showDocTab('completo-${index}')">📋 Todos Campos</button>`;
497
- html += `</div>`;
498
-
499
- // Aba: Geral
500
- html += `<div id="doc-tab-geral-${index}" class="doc-tab" style="display: block;">`;
501
- html += renderCampo('Processo', source.processo_codigo_completo);
502
- html += renderCampo('Classe', source.processo_classe_processual_unificada_extenso);
503
- html += renderCampo('Órgão Julgador', source.orgao_julgador);
504
- html += renderCampo('Relator', source.relator_processo_nome);
505
- html += renderCampo('Relator Acórdão', source.relator_acordao_nome);
506
- html += renderCampo('Ministros', source.ministro_facet);
507
- html += renderCampo('Data Julgamento', source.julgamento_data);
508
- html += renderCampo('Data Publicação', source.publicacao_data);
509
- html += renderCampo('Procedência', source.procedencia_geografica_completo);
510
- html += renderCampo('UF', source.procedencia_geografica_uf_sigla);
511
- html += `</div>`;
512
-
513
- // Aba: Ementa
514
- html += `<div id="doc-tab-ementa-${index}" class="doc-tab" style="display: none;">`;
515
- html += renderCampo('Ementa', source.ementa_texto, 'texto');
516
- html += renderCampo('Tese', source.documental_tese_texto, 'texto');
517
- html += renderCampo('Tema', source.documental_tese_tema_texto);
518
- html += `</div>`;
519
-
520
- // Aba: Acórdão
521
- html += `<div id="doc-tab-acordao-${index}" class="doc-tab" style="display: none;">`;
522
- html += renderCampo('Acórdão/Ata', source.acordao_ata, 'texto');
523
- html += renderCampo('Decisão', source.decisao_texto, 'texto');
524
- html += renderCampo('Súmula', source.sumula_texto, 'texto');
525
- html += renderCampo('Indexação', source.documental_indexacao_texto, 'texto');
526
- html += renderCampo('Observações', source.documental_observacao_texto, 'texto');
527
- html += `</div>`;
528
-
529
- // Aba: Legislação
530
- html += `<div id="doc-tab-legislacao-${index}" class="doc-tab" style="display: none;">`;
531
- html += renderCampo('Legislação Citada', source.documental_legislacao_citada_texto, 'texto');
532
- html += renderCampo('Jurisprudência Citada', source.documental_jurisprudencia_citada_texto, 'texto');
533
- html += renderCampo('Doutrina', source.documental_doutrina_texto, 'texto');
534
- html += renderCampo('Precedentes', source.processo_precedente_texto, 'texto');
535
- html += `</div>`;
536
-
537
- // Aba: Highlight
538
- html += `<div id="doc-tab-highlight-${index}" class="doc-tab" style="display: none;">`;
539
- if (Object.keys(highlight).length > 0) {
540
- for (const [campo, valores] of Object.entries(highlight)) {
541
- if (valores && valores.length > 0) {
542
- html += `<div class="campo-card">`;
543
- html += `<div class="campo-nome">${campo}</div>`;
544
- valores.forEach(valor => {
545
- html += `<div class="highlight-box" style="margin-top: 5px;">${valor.replace(/<em>/g, '<span class="highlight">').replace(/<\\/em>/g, '</span>')}</div>`;
546
- });
547
- html += `</div>`;
548
- }
549
- }
550
- } else {
551
- html += `<div class="campo-vazio">Nenhum termo destacado</div>`;
552
- }
553
- html += `</div>`;
554
-
555
- // Aba: Todos Campos
556
- html += `<div id="doc-tab-completo-${index}" class="doc-tab" style="display: none;">`;
557
- html += `<pre>${JSON.stringify(source, null, 2).replace(/<em>/g, '<span class="highlight">').replace(/<\\/em>/g, '</span>')}</pre>`;
558
- html += `</div>`;
559
-
560
- // URLs importantes
561
- if (source.inteiro_teor_url) {
562
- html += `<div style="margin-top: 15px; padding: 10px; background: #e8f0fe; border-radius: 8px;">`;
563
- html += `<strong>🔗 Links:</strong><br>`;
564
- html += `<a href="${source.inteiro_teor_url}" target="_blank" class="url-link">📄 Inteiro Teor</a><br>`;
565
- if (source.acompanhamento_processual_url) {
566
- html += `<a href="${source.acompanhamento_processual_url}" target="_blank" class="url-link">📊 Acompanhamento Processual</a><br>`;
567
- }
568
- if (source.dje_url) {
569
- html += `<a href="${source.dje_url}" target="_blank" class="url-link">📰 DJE</a>`;
570
- }
571
- html += `</div>`;
572
- }
573
-
574
- html += `</div>`; // Fecha campo-lista
575
- });
576
-
577
- document.getElementById('result').innerHTML = html;
578
- }
579
-
580
- function showDocTab(tabId) {
581
- const docIndex = tabId.split('-')[2];
582
- document.querySelectorAll(`[id^="doc-tab-"]`).forEach(el => {
583
- if (el.id.includes(`-${docIndex}`)) {
584
- el.style.display = 'none';
585
- }
586
- });
587
- const selectedTab = document.getElementById(`doc-tab-${tabId}`);
588
- if (selectedTab) {
589
- selectedTab.style.display = 'block';
590
- }
591
- }
592
-
593
- async function runSearch() {
594
- const btn = document.getElementById('testBtn');
595
- const loading = document.getElementById('loading');
596
- const resultDiv = document.getElementById('result');
597
- const pageSize = document.getElementById('pageSize').value;
598
- const sortOrder = document.getElementById('sortOrder').value;
599
- const base = document.getElementById('base').value;
600
-
601
- btn.disabled = true;
602
- loading.style.display = 'inline-block';
603
- resultDiv.innerHTML = '<div class="info-box">⏳ Executando busca no STF...</div>';
604
-
605
- try {
606
- const response = await fetch('/api/search-advanced', {
607
- method: 'POST',
608
- headers: { 'Content-Type': 'application/json' },
609
- body: JSON.stringify({
610
- pageSize: parseInt(pageSize),
611
- sortOrder,
612
- base: base || undefined
613
- })
614
- });
615
-
616
- const data = await response.json();
617
- requestsCount++;
618
- document.getElementById('requestsCount').textContent = requestsCount;
619
-
620
- if (data.success) {
621
- successCount++;
622
- document.getElementById('successCount').textContent = successCount;
623
-
624
- if (data.data && data.data.result && data.data.result.hits) {
625
- docsCount = data.data.result.hits.hits.length;
626
- document.getElementById('docsCount').textContent = docsCount;
627
-
628
- if (data.data.result.hits.total && data.data.result.hits.total.value) {
629
- document.getElementById('totalDocs').textContent = data.data.result.hits.total.value.toLocaleString();
630
- }
631
- }
632
-
633
- lastResult = data.data;
634
- lastToken = data.token;
635
-
636
- if (lastToken) {
637
- document.getElementById('tokenValue').textContent = lastToken;
638
- document.getElementById('tokenDisplay').style.display = 'block';
639
- document.getElementById('downloadBtn').disabled = false;
640
- }
641
-
642
- displayResult(data.data);
643
-
644
- } else {
645
- failCount++;
646
- document.getElementById('failCount').textContent = failCount;
647
-
648
- let errorHtml = '<div class="error">❌ Falha na busca</div>';
649
- if (data.attempts) {
650
- data.attempts.forEach(attempt => {
651
- errorHtml += `<div class="warning"><strong>${attempt.method}:</strong> ${attempt.error || 'Erro'}</div>`;
652
- });
653
- }
654
- errorHtml += '<pre>' + JSON.stringify(data, null, 2) + '</pre>';
655
- resultDiv.innerHTML = errorHtml;
656
- }
657
- } catch (error) {
658
- failCount++;
659
- document.getElementById('failCount').textContent = failCount;
660
- resultDiv.innerHTML = '<div class="error">❌ Erro: ' + error.message + '</div>';
661
- } finally {
662
- btn.disabled = false;
663
- loading.style.display = 'none';
664
- }
665
- }
666
-
667
- async function getDocumentById() {
668
- const docId = document.getElementById('docId').value.trim();
669
- if (!docId) {
670
- alert('Digite um ID');
671
- return;
672
- }
673
-
674
- const btn = document.getElementById('getByIdBtn');
675
- const loading = document.getElementById('loading');
676
- const resultDiv = document.getElementById('result');
677
-
678
- btn.disabled = true;
679
- loading.style.display = 'inline-block';
680
- resultDiv.innerHTML = '<div class="info-box">⏳ Buscando documento...</div>';
681
-
682
- try {
683
- const response = await fetch(`/api/document/${docId}`);
684
- const data = await response.json();
685
-
686
- requestsCount++;
687
- document.getElementById('requestsCount').textContent = requestsCount;
688
-
689
- if (data.success && data.document) {
690
- successCount++;
691
- document.getElementById('successCount').textContent = successCount;
692
- docsCount++;
693
- document.getElementById('docsCount').textContent = docsCount;
694
-
695
- lastResult = { result: { hits: { hits: [data.document] } } };
696
-
697
- displayResult(lastResult);
698
- } else {
699
- failCount++;
700
- document.getElementById('failCount').textContent = failCount;
701
- resultDiv.innerHTML = '<div class="error">❌ Documento não encontrado</div>';
702
- }
703
- } catch (error) {
704
- failCount++;
705
- document.getElementById('failCount').textContent = failCount;
706
- resultDiv.innerHTML = '<div class="error">❌ Erro: ' + error.message + '</div>';
707
- } finally {
708
- btn.disabled = false;
709
- loading.style.display = 'none';
710
- }
711
- }
712
-
713
- function downloadJSON() {
714
- if (!lastResult) {
715
- alert('Nenhum resultado para download');
716
- return;
717
- }
718
-
719
- const dataStr = JSON.stringify(lastResult, null, 2);
720
- const blob = new Blob([dataStr], { type: 'application/json' });
721
- const url = URL.createObjectURL(blob);
722
- const a = document.createElement('a');
723
- a.href = url;
724
- a.download = `stf_jurisprudencia_${new Date().toISOString().slice(0,10)}.json`;
725
- document.body.appendChild(a);
726
- a.click();
727
- document.body.removeChild(a);
728
- URL.revokeObjectURL(url);
729
- }
730
-
731
- function copyToken() {
732
- if (!lastToken) {
733
- alert('Nenhum token disponível. Execute uma busca primeiro.');
734
- return;
735
- }
736
-
737
- navigator.clipboard.writeText(lastToken).then(() => {
738
- alert('✅ Token copiado para área de transferência!');
739
- }).catch(() => {
740
- alert('❌ Erro ao copiar token');
741
- });
742
- }
743
-
744
- window.onload = async () => {
745
- try {
746
- const response = await fetch('/api/health');
747
- const data = await response.json();
748
- if (data.total_docs) {
749
- document.getElementById('totalDocs').textContent = data.total_docs.toLocaleString();
750
- }
751
- document.getElementById('totalCampos').textContent = "102";
752
- } catch (e) {
753
- document.getElementById('totalDocs').textContent = 'indisponível';
754
- }
755
- };
756
- </script>
757
- </body>
758
- </html>
759
  """
760
 
761
  # ============================================
@@ -857,9 +392,41 @@ def search_with_token(token, payload):
857
  return {"success": False, "error": str(e)}
858
 
859
  def get_document_by_id(token, doc_id):
860
- payload = PAYLOAD_POR_ID.copy()
861
- payload["query"]["ids"]["values"] = [doc_id]
862
- return search_with_token(token, payload)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
863
 
864
  def test_with_playwright_full(payload):
865
  logger.info("Tentando acesso com Playwright...")
@@ -963,7 +530,9 @@ def get_document(doc_id):
963
  token = get_fresh_token()
964
  if not token:
965
  return jsonify({"error": "Não foi possível obter token"}), 500
 
966
  result = get_document_by_id(token, doc_id)
 
967
  if result.get("success") and result["data"].get("hits", {}).get("hits"):
968
  doc = result["data"]["hits"]["hits"][0] if result["data"]["hits"]["hits"] else None
969
  return jsonify({"success": True, "document": doc})
 
1
+
2
  import os
3
  import sys
4
  import json
 
258
  "track_total_hits": True
259
  }
260
 
261
+ # Payload para busca por ID (versão completa com highlight)
262
+ PAYLOAD_POR_ID_COMPLETO = {
263
+ "query": {"ids": {"values": []}},
264
+ "_source": PAYLOAD_COMPLETO["_source"],
265
+ "highlight": PAYLOAD_COMPLETO["highlight"],
266
+ "size": 1
267
+ }
268
+
269
+ # Payload para busca por ID (versão sem highlight)
270
+ PAYLOAD_POR_ID_SIMPLES = {
271
  "query": {"ids": {"values": []}},
272
  "_source": PAYLOAD_COMPLETO["_source"],
273
  "size": 1
 
287
  token_cache = {"token": None, "expires_at": 0}
288
 
289
  # ============================================
290
+ # HTML TEMPLATE COMPLETO (inserir o mesmo da resposta anterior)
291
  # ============================================
292
  HTML_TEMPLATE = """
293
+ ... (cole aqui o HTML completo da resposta anterior) ...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
294
  """
295
 
296
  # ============================================
 
392
  return {"success": False, "error": str(e)}
393
 
394
  def get_document_by_id(token, doc_id):
395
+ """
396
+ Busca um documento por ID, tentando diferentes payloads (completo, simples, etc.)
397
+ """
398
+ # Tentar payload completo com highlight
399
+ payload_completo = PAYLOAD_POR_ID_COMPLETO.copy()
400
+ payload_completo["query"]["ids"]["values"] = [doc_id]
401
+ res = search_with_token(token, payload_completo)
402
+ if res.get("success") and res["data"].get("hits", {}).get("hits"):
403
+ return res
404
+
405
+ # Se falhou, tentar payload sem highlight
406
+ logger.info("Payload completo por ID falhou. Tentando payload simples...")
407
+ payload_simples = PAYLOAD_POR_ID_SIMPLES.copy()
408
+ payload_simples["query"]["ids"]["values"] = [doc_id]
409
+ res2 = search_with_token(token, payload_simples)
410
+ if res2.get("success") and res2["data"].get("hits", {}).get("hits"):
411
+ return res2
412
+
413
+ # Último recurso: buscar por termo no campo id (alguns documentos podem ter id em _id)
414
+ logger.info("Payloads por ID falharam. Tentando busca por termo...")
415
+ payload_termo = {
416
+ "query": {
417
+ "bool": {
418
+ "should": [
419
+ {"term": {"_id": doc_id}},
420
+ {"term": {"id": doc_id}},
421
+ {"term": {"dg_unique": doc_id}}
422
+ ]
423
+ }
424
+ },
425
+ "_source": PAYLOAD_COMPLETO["_source"],
426
+ "size": 1
427
+ }
428
+ res3 = search_with_token(token, payload_termo)
429
+ return res3
430
 
431
  def test_with_playwright_full(payload):
432
  logger.info("Tentando acesso com Playwright...")
 
530
  token = get_fresh_token()
531
  if not token:
532
  return jsonify({"error": "Não foi possível obter token"}), 500
533
+
534
  result = get_document_by_id(token, doc_id)
535
+
536
  if result.get("success") and result["data"].get("hits", {}).get("hits"):
537
  doc = result["data"]["hits"]["hits"][0] if result["data"]["hits"]["hits"] else None
538
  return jsonify({"success": True, "document": doc})