caarleexx commited on
Commit
f2cdf9f
·
verified ·
1 Parent(s): 3f9d9e2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +10 -493
app.py CHANGED
@@ -1,4 +1,8 @@
 
1
 
 
 
 
2
  import os
3
  import sys
4
  import json
@@ -22,7 +26,7 @@ logger = logging.getLogger(__name__)
22
  app = Flask(__name__)
23
 
24
  # ============================================
25
- # PAYLOAD COMPLETO com TODOS os campos
26
  # ============================================
27
  PAYLOAD_COMPLETO = {
28
  "query": {
@@ -358,7 +362,7 @@ PAYLOAD_COMPLETO = {
358
  "size": 100,
359
  "from": 0,
360
  "sort": [{"julgamento_data": {"order": "desc"}}],
361
- "track_total_hits": true
362
  }
363
 
364
  # Payload para busca de um documento específico por ID
@@ -389,497 +393,12 @@ token_cache = {
389
  "expires_at": 0
390
  }
391
 
392
- # Template HTML com visualização completa dos campos
393
- HTML_TEMPLATE = """
394
- <!DOCTYPE html>
395
- <html>
396
- <head>
397
- <title>⚖️ STF Jurisprudência - Visualizador Completo</title>
398
- <meta charset="utf-8">
399
- <meta name="viewport" content="width=device-width, initial-scale=1">
400
- <style>
401
- body { font-family: 'Segoe UI', Roboto, system-ui, sans-serif; max-width: 1600px; margin: 0 auto; padding: 20px; background: #f0f2f5; }
402
- .container { background: white; border-radius: 12px; padding: 30px; box-shadow: 0 8px 20px rgba(0,0,0,0.1); }
403
- h1 { color: #1a1a2e; border-bottom: 3px solid #4CAF50; padding-bottom: 15px; display: flex; align-items: center; gap: 10px; }
404
- h1:before { content: "⚖️"; font-size: 1.2em; }
405
- h2 { color: #2c3e50; margin-top: 25px; margin-bottom: 15px; font-size: 1.5em; border-left: 5px solid #4CAF50; padding-left: 15px; }
406
- h3 { color: #34495e; margin-top: 20px; margin-bottom: 10px; font-size: 1.2em; border-bottom: 1px solid #e0e0e0; padding-bottom: 8px; }
407
- .info-box { background: #e8f0fe; border-left: 5px solid #2196F3; padding: 15px 20px; margin: 20px 0; border-radius: 8px; }
408
- .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin: 25px 0; }
409
- .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); }
410
- .stat-value { font-size: 32px; font-weight: bold; color: #1a73e8; }
411
- .stat-label { color: #5f6368; font-size: 14px; margin-top: 8px; text-transform: uppercase; letter-spacing: 0.5px; }
412
- .button-group { display: flex; gap: 15px; flex-wrap: wrap; margin: 25px 0; }
413
- 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); }
414
- button:hover { background: #1557b0; transform: translateY(-2px); box-shadow: 0 4px 12px rgba(26,115,232,0.4); }
415
- button:disabled { background: #a0a0a0; cursor: not-allowed; transform: none; box-shadow: none; }
416
- button.secondary { background: #34a853; }
417
- button.secondary:hover { background: #2d8745; }
418
- button.download { background: #f9ab00; color: #1a1a2e; }
419
- button.download:hover { background: #e69c00; }
420
- .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; }
421
- @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
422
- 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); }
423
- .success { color: #0f9d58; background: #e6f4ea; border-left: 5px solid #34a853; padding: 15px 20px; margin: 15px 0; border-radius: 8px; font-weight: 500; }
424
- .error { color: #d93025; background: #fce8e6; border-left: 5px solid #ea4335; padding: 15px 20px; margin: 15px 0; border-radius: 8px; font-weight: 500; }
425
- .warning { color: #e37400; background: #fef7e0; border-left: 5px solid #f9ab00; padding: 15px 20px; margin: 15px 0; border-radius: 8px; font-weight: 500; }
426
- .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; }
427
- .token-label { color: #f9ab00; font-weight: bold; margin-bottom: 8px; display: block; }
428
- .filters { background: #f8f9fa; border-radius: 8px; padding: 20px; margin: 20px 0; border: 1px solid #e0e0e0; }
429
- .filter-group { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; align-items: end; }
430
- .filter-item { min-width: 200px; }
431
- .filter-item label { display: block; margin-bottom: 8px; color: #5f6368; font-size: 14px; font-weight: 500; }
432
- .filter-item input, .filter-item select { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; font-size: 14px; }
433
- .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); }
434
- .badge { display: inline-block; background: #e8f0fe; color: #1a73e8; padding: 4px 12px; border-radius: 20px; font-size: 13px; font-weight: 500; margin: 2px; }
435
- .campo-lista { background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 15px; margin: 10px 0; }
436
- .campo-nome { font-weight: bold; color: #2c3e50; font-size: 14px; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 5px; }
437
- .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; }
438
- .campo-vazio { color: #999; font-style: italic; }
439
- .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; }
440
- .nav-tabs { display: flex; gap: 5px; margin: 20px 0; flex-wrap: wrap; border-bottom: 2px solid #e0e0e0; padding-bottom: 10px; }
441
- .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; }
442
- .nav-tab:hover { background: #f0f0f0; }
443
- .nav-tab.active { background: #1a73e8; color: white; border-color: #1a73e8; }
444
- .tab-content { display: none; padding: 20px; background: white; border: 1px solid #e0e0e0; border-top: none; border-radius: 0 0 8px 8px; }
445
- .tab-content.active { display: block; }
446
- .campo-card { background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 15px; margin: 10px 0; transition: all 0.2s; }
447
- .campo-card:hover { box-shadow: 0 4px 12px rgba(0,0,0,0.1); border-color: #1a73e8; }
448
- .flag-true { color: #0f9d58; font-weight: bold; }
449
- .flag-false { color: #d93025; }
450
- .url-link { color: #1a73e8; text-decoration: none; word-break: break-all; }
451
- .url-link:hover { text-decoration: underline; }
452
- .highlight { background-color: #f9ab00; color: #1a1a2e; font-weight: bold; padding: 2px 4px; border-radius: 4px; }
453
- .highlight-box { background: #fef7e0; border: 1px solid #f9ab00; padding: 10px; border-radius: 8px; margin: 10px 0; }
454
- .highlight-title { font-weight: bold; color: #e37400; margin-bottom: 5px; }
455
- </style>
456
- </head>
457
- <body>
458
- <div class="container">
459
- <h1>STF Jurisprudência - Visualizador Completo</h1>
460
-
461
- <div class="info-box">
462
- <strong>📌 API de Jurisprudência do STF - Todos os Campos com Highlight</strong><br>
463
- • Total de campos disponíveis: <span id="totalCampos">102</span><br>
464
- • Campos com highlight: 22 campos configurados<br>
465
- • Documentos disponíveis: <span id="totalDocs">carregando...</span>
466
- </div>
467
-
468
- <div class="stats-grid">
469
- <div class="stat-card"><div class="stat-value" id="requestsCount">0</div><div class="stat-label">Requisições</div></div>
470
- <div class="stat-card"><div class="stat-value" id="successCount">0</div><div class="stat-label">Sucessos</div></div>
471
- <div class="stat-card"><div class="stat-value" id="failCount">0</div><div class="stat-label">Falhas</div></div>
472
- <div class="stat-card"><div class="stat-value" id="docsCount">0</div><div class="stat-label">Docs Obtidos</div></div>
473
- </div>
474
-
475
- <div class="filters">
476
- <h3 style="margin-top: 0;">🔍 Filtros de Busca</h3>
477
- <div class="filter-group">
478
- <div class="filter-item">
479
- <label>Quantidade</label>
480
- <select id="pageSize">
481
- <option value="5">5 resultados</option>
482
- <option value="10">10 resultados</option>
483
- <option value="25">25 resultados</option>
484
- <option value="50">50 resultados</option>
485
- <option value="100" selected>100 resultados</option>
486
- </select>
487
- </div>
488
- <div class="filter-item">
489
- <label>Ordenar por</label>
490
- <select id="sortOrder">
491
- <option value="desc">Mais recentes</option>
492
- <option value="asc">Mais antigos</option>
493
- </select>
494
- </div>
495
- <div class="filter-item">
496
- <label>Base</label>
497
- <select id="base">
498
- <option value="acordaos">Acórdãos</option>
499
- <option value="decisoes">Decisões</option>
500
- <option value="sumulas">Súmulas</option>
501
- <option value="informativos">Informativos</option>
502
- <option value="">Todas</option>
503
- </select>
504
- </div>
505
- <div class="filter-item">
506
- <label>Busca por ID</label>
507
- <input type="text" id="docId" placeholder="Ex: sjur505215">
508
- </div>
509
- </div>
510
- </div>
511
-
512
- <div class="button-group">
513
- <button id="testBtn" onclick="runSearch()">
514
- <span class="loading" id="loading" style="display: none;"></span>
515
- <span>🔍 Buscar Documentos</span>
516
- </button>
517
- <button id="getByIdBtn" class="secondary" onclick="getDocumentById()">
518
- <span>📄 Buscar por ID</span>
519
- </button>
520
- <button id="downloadBtn" class="download" onclick="downloadJSON()" disabled>
521
- 📥 Download JSON
522
- </button>
523
- <button id="copyBtn" class="secondary" onclick="copyToken()">
524
- 🔑 Copiar Token
525
- </button>
526
- </div>
527
-
528
- <div id="tokenDisplay" style="display: none;" class="token-box">
529
- <span class="token-label">🔐 Token AWS WAF</span>
530
- <span id="tokenValue"></span>
531
- </div>
532
-
533
- <div id="result" style="margin-top: 25px;"></div>
534
- </div>
535
-
536
- <script>
537
- let lastResult = null;
538
- let lastToken = null;
539
- let requestsCount = 0, successCount = 0, failCount = 0, docsCount = 0;
540
- let currentTab = 'visao-geral';
541
-
542
- function renderCampo(nome, valor, tipo = 'normal') {
543
- if (valor === null || valor === undefined || valor === '') {
544
- return `<div class="campo-card"><div class="campo-nome">${nome}</div><div class="campo-vazio">(vazio)</div></div>`;
545
- }
546
-
547
- if (tipo === 'url' && valor) {
548
- 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>`;
549
- }
550
-
551
- if (tipo === 'flag') {
552
- const flagClass = valor ? 'flag-true' : 'flag-false';
553
- return `<div class="campo-card"><div class="campo-nome">${nome}</div><div class="campo-valor ${flagClass}">${valor ? '✓ Sim' : '✗ Não'}</div></div>`;
554
- }
555
-
556
- if (tipo === 'texto' && valor && valor.length > 200) {
557
- 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>`;
558
- }
559
-
560
- if (Array.isArray(valor)) {
561
- return `<div class="campo-card"><div class="campo-nome">${nome}</div><div class="campo-valor">${valor.join('<br>')}</div></div>`;
562
- }
563
-
564
- 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>`;
565
- }
566
-
567
- function renderHighlight(highlight) {
568
- if (!highlight) return '';
569
-
570
- let html = '<div class="highlight-box"><div class="highlight-title">🔆 Termos destacados (highlight):</div>';
571
- for (const [campo, valores] of Object.entries(highlight)) {
572
- if (valores && valores.length > 0) {
573
- html += `<div><strong>${campo}:</strong> `;
574
- valores.forEach(valor => {
575
- html += `<div style="margin-left: 20px; margin-top: 5px;">${valor.replace(/<em>/g, '<span class="highlight">').replace(/<\\/em>/g, '</span>')}</div>`;
576
- });
577
- html += '</div>';
578
- }
579
- }
580
- html += '</div>';
581
- return html;
582
- }
583
-
584
- function displayResult(data) {
585
- if (!data || !data.result || !data.result.hits || !data.result.hits.hits || data.result.hits.hits.length === 0) {
586
- document.getElementById('result').innerHTML = '<div class="warning">⚠️ Nenhum documento encontrado</div>';
587
- return;
588
- }
589
-
590
- const hits = data.result.hits.hits;
591
- const total = data.result.hits.total?.value || 0;
592
-
593
- let html = `<div class="success">✅ Encontrados ${total.toLocaleString()} documentos. Exibindo ${hits.length} resultados.</div>`;
594
-
595
- hits.forEach((hit, index) => {
596
- const source = hit._source || {};
597
- const highlight = hit.highlight || {};
598
- const docId = source.id || hit._id || `doc_${index}`;
599
-
600
- html += `<div class="campo-lista" style="margin-top: 30px;">`;
601
- html += `<h3 style="display: flex; justify-content: space-between; align-items: center;">
602
- <span>📄 Documento ${index + 1}: ${source.titulo || source.processo_codigo_completo || docId}</span>
603
- <span class="badge">ID: ${docId}</span>
604
- </h3>`;
605
-
606
- // Abas internas para cada documento
607
- html += `<div style="display: flex; gap: 5px; margin: 15px 0; flex-wrap: wrap;">`;
608
- html += `<button class="badge" style="cursor: pointer;" onclick="showDocTab('geral-${index}')">📋 Geral</button>`;
609
- html += `<button class="badge" style="cursor: pointer;" onclick="showDocTab('ementa-${index}')">📝 Ementa</button>`;
610
- html += `<button class="badge" style="cursor: pointer;" onclick="showDocTab('acordao-${index}')">⚖️ Acórdão</button>`;
611
- html += `<button class="badge" style="cursor: pointer;" onclick="showDocTab('legislacao-${index}')">📚 Legislação</button>`;
612
- html += `<button class="badge" style="cursor: pointer;" onclick="showDocTab('highlight-${index}')">🔆 Highlight</button>`;
613
- html += `<button class="badge" style="cursor: pointer;" onclick="showDocTab('completo-${index}')">📋 Todos Campos</button>`;
614
- html += `</div>`;
615
-
616
- // Aba: Geral
617
- html += `<div id="doc-tab-geral-${index}" class="doc-tab" style="display: block;">`;
618
- html += renderCampo('Processo', source.processo_codigo_completo);
619
- html += renderCampo('Classe', source.processo_classe_processual_unificada_extenso);
620
- html += renderCampo('Órgão Julgador', source.orgao_julgador);
621
- html += renderCampo('Relator', source.relator_processo_nome);
622
- html += renderCampo('Relator Acórdão', source.relator_acordao_nome);
623
- html += renderCampo('Ministros', source.ministro_facet);
624
- html += renderCampo('Data Julgamento', source.julgamento_data);
625
- html += renderCampo('Data Publicação', source.publicacao_data);
626
- html += renderCampo('Procedência', source.procedencia_geografica_completo);
627
- html += renderCampo('UF', source.procedencia_geografica_uf_sigla);
628
- html += `</div>`;
629
-
630
- // Aba: Ementa
631
- html += `<div id="doc-tab-ementa-${index}" class="doc-tab" style="display: none;">`;
632
- html += renderCampo('Ementa', source.ementa_texto, 'texto');
633
- html += renderCampo('Tese', source.documental_tese_texto, 'texto');
634
- html += renderCampo('Tema', source.documental_tese_tema_texto);
635
- html += `</div>`;
636
-
637
- // Aba: Acórdão
638
- html += `<div id="doc-tab-acordao-${index}" class="doc-tab" style="display: none;">`;
639
- html += renderCampo('Acórdão/Ata', source.acordao_ata, 'texto');
640
- html += renderCampo('Decisão', source.decisao_texto, 'texto');
641
- html += renderCampo('Súmula', source.sumula_texto, 'texto');
642
- html += renderCampo('Indexação', source.documental_indexacao_texto, 'texto');
643
- html += renderCampo('Observações', source.documental_observacao_texto, 'texto');
644
- html += `</div>`;
645
-
646
- // Aba: Legislação
647
- html += `<div id="doc-tab-legislacao-${index}" class="doc-tab" style="display: none;">`;
648
- html += renderCampo('Legislação Citada', source.documental_legislacao_citada_texto, 'texto');
649
- html += renderCampo('Jurisprudência Citada', source.documental_jurisprudencia_citada_texto, 'texto');
650
- html += renderCampo('Doutrina', source.documental_doutrina_texto, 'texto');
651
- html += renderCampo('Precedentes', source.processo_precedente_texto, 'texto');
652
- html += `</div>`;
653
-
654
- // Aba: Highlight
655
- html += `<div id="doc-tab-highlight-${index}" class="doc-tab" style="display: none;">`;
656
- if (Object.keys(highlight).length > 0) {
657
- for (const [campo, valores] of Object.entries(highlight)) {
658
- if (valores && valores.length > 0) {
659
- html += `<div class="campo-card">`;
660
- html += `<div class="campo-nome">${campo}</div>`;
661
- valores.forEach(valor => {
662
- html += `<div class="highlight-box" style="margin-top: 5px;">${valor.replace(/<em>/g, '<span class="highlight">').replace(/<\\/em>/g, '</span>')}</div>`;
663
- });
664
- html += `</div>`;
665
- }
666
- }
667
- } else {
668
- html += `<div class="campo-vazio">Nenhum termo destacado</div>`;
669
- }
670
- html += `</div>`;
671
-
672
- // Aba: Todos Campos
673
- html += `<div id="doc-tab-completo-${index}" class="doc-tab" style="display: none;">`;
674
- html += `<pre>${JSON.stringify(source, null, 2).replace(/<em>/g, '<span class="highlight">').replace(/<\\/em>/g, '</span>')}</pre>`;
675
- html += `</div>`;
676
-
677
- // URLs importantes
678
- if (source.inteiro_teor_url) {
679
- html += `<div style="margin-top: 15px; padding: 10px; background: #e8f0fe; border-radius: 8px;">`;
680
- html += `<strong>🔗 Links:</strong><br>`;
681
- html += `<a href="${source.inteiro_teor_url}" target="_blank" class="url-link">📄 Inteiro Teor</a><br>`;
682
- if (source.acompanhamento_processual_url) {
683
- html += `<a href="${source.acompanhamento_processual_url}" target="_blank" class="url-link">📊 Acompanhamento Processual</a><br>`;
684
- }
685
- if (source.dje_url) {
686
- html += `<a href="${source.dje_url}" target="_blank" class="url-link">📰 DJE</a>`;
687
- }
688
- html += `</div>`;
689
- }
690
-
691
- html += `</div>`; // Fecha campo-lista
692
- });
693
-
694
- document.getElementById('result').innerHTML = html;
695
- }
696
-
697
- function showDocTab(tabId) {
698
- const docIndex = tabId.split('-')[2];
699
- // Esconder todas as abas deste documento
700
- document.querySelectorAll(`[id^="doc-tab-"]`).forEach(el => {
701
- if (el.id.includes(`-${docIndex}`)) {
702
- el.style.display = 'none';
703
- }
704
- });
705
- // Mostrar a aba selecionada
706
- const selectedTab = document.getElementById(`doc-tab-${tabId}`);
707
- if (selectedTab) {
708
- selectedTab.style.display = 'block';
709
- }
710
- }
711
-
712
- async function runSearch() {
713
- const btn = document.getElementById('testBtn');
714
- const loading = document.getElementById('loading');
715
- const resultDiv = document.getElementById('result');
716
- const pageSize = document.getElementById('pageSize').value;
717
- const sortOrder = document.getElementById('sortOrder').value;
718
- const base = document.getElementById('base').value;
719
-
720
- btn.disabled = true;
721
- loading.style.display = 'inline-block';
722
- resultDiv.innerHTML = '<div class="info-box">⏳ Executando busca no STF...</div>';
723
-
724
- try {
725
- const response = await fetch('/api/search-advanced', {
726
- method: 'POST',
727
- headers: { 'Content-Type': 'application/json' },
728
- body: JSON.stringify({
729
- pageSize: parseInt(pageSize),
730
- sortOrder,
731
- base: base || undefined
732
- })
733
- });
734
-
735
- const data = await response.json();
736
- requestsCount++;
737
- document.getElementById('requestsCount').textContent = requestsCount;
738
-
739
- if (data.success) {
740
- successCount++;
741
- document.getElementById('successCount').textContent = successCount;
742
-
743
- if (data.data && data.data.result && data.data.result.hits) {
744
- docsCount = data.data.result.hits.hits.length;
745
- document.getElementById('docsCount').textContent = docsCount;
746
-
747
- if (data.data.result.hits.total && data.data.result.hits.total.value) {
748
- document.getElementById('totalDocs').textContent = data.data.result.hits.total.value.toLocaleString();
749
- }
750
- }
751
-
752
- lastResult = data.data;
753
- lastToken = data.token;
754
-
755
- if (lastToken) {
756
- document.getElementById('tokenValue').textContent = lastToken;
757
- document.getElementById('tokenDisplay').style.display = 'block';
758
- document.getElementById('downloadBtn').disabled = false;
759
- }
760
-
761
- displayResult(data.data);
762
-
763
- } else {
764
- failCount++;
765
- document.getElementById('failCount').textContent = failCount;
766
-
767
- let errorHtml = '<div class="error">❌ Falha na busca</div>';
768
- if (data.attempts) {
769
- data.attempts.forEach(attempt => {
770
- errorHtml += `<div class="warning"><strong>${attempt.method}:</strong> ${attempt.error || 'Erro'}</div>`;
771
- });
772
- }
773
- errorHtml += '<pre>' + JSON.stringify(data, null, 2) + '</pre>';
774
- resultDiv.innerHTML = errorHtml;
775
- }
776
- } catch (error) {
777
- failCount++;
778
- document.getElementById('failCount').textContent = failCount;
779
- resultDiv.innerHTML = '<div class="error">❌ Erro: ' + error.message + '</div>';
780
- } finally {
781
- btn.disabled = false;
782
- loading.style.display = 'none';
783
- }
784
- }
785
-
786
- async function getDocumentById() {
787
- const docId = document.getElementById('docId').value.trim();
788
- if (!docId) {
789
- alert('Digite um ID');
790
- return;
791
- }
792
-
793
- const btn = document.getElementById('getByIdBtn');
794
- const loading = document.getElementById('loading');
795
- const resultDiv = document.getElementById('result');
796
-
797
- btn.disabled = true;
798
- loading.style.display = 'inline-block';
799
- resultDiv.innerHTML = '<div class="info-box">⏳ Buscando documento...</div>';
800
-
801
- try {
802
- const response = await fetch(`/api/document/${docId}`);
803
- const data = await response.json();
804
-
805
- requestsCount++;
806
- document.getElementById('requestsCount').textContent = requestsCount;
807
-
808
- if (data.success && data.document) {
809
- successCount++;
810
- document.getElementById('successCount').textContent = successCount;
811
- docsCount++;
812
- document.getElementById('docsCount').textContent = docsCount;
813
-
814
- lastResult = { result: { hits: { hits: [data.document] } } };
815
-
816
- displayResult(lastResult);
817
- } else {
818
- failCount++;
819
- document.getElementById('failCount').textContent = failCount;
820
- resultDiv.innerHTML = '<div class="error">❌ Documento não encontrado</div>';
821
- }
822
- } catch (error) {
823
- failCount++;
824
- document.getElementById('failCount').textContent = failCount;
825
- resultDiv.innerHTML = '<div class="error">❌ Erro: ' + error.message + '</div>';
826
- } finally {
827
- btn.disabled = false;
828
- loading.style.display = 'none';
829
- }
830
- }
831
-
832
- function downloadJSON() {
833
- if (!lastResult) {
834
- alert('Nenhum resultado para download');
835
- return;
836
- }
837
-
838
- const dataStr = JSON.stringify(lastResult, null, 2);
839
- const blob = new Blob([dataStr], { type: 'application/json' });
840
- const url = URL.createObjectURL(blob);
841
- const a = document.createElement('a');
842
- a.href = url;
843
- a.download = `stf_jurisprudencia_${new Date().toISOString().slice(0,10)}.json`;
844
- document.body.appendChild(a);
845
- a.click();
846
- document.body.removeChild(a);
847
- URL.revokeObjectURL(url);
848
- }
849
-
850
- function copyToken() {
851
- if (!lastToken) {
852
- alert('Nenhum token disponível. Execute uma busca primeiro.');
853
- return;
854
- }
855
-
856
- navigator.clipboard.writeText(lastToken).then(() => {
857
- alert('✅ Token copiado para área de transferência!');
858
- }).catch(() => {
859
- alert('❌ Erro ao copiar token');
860
- });
861
- }
862
-
863
- // Carregar total de documentos ao iniciar
864
- window.onload = async () => {
865
- try {
866
- const response = await fetch('/api/health');
867
- const data = await response.json();
868
- if (data.total_docs) {
869
- document.getElementById('totalDocs').textContent = data.total_docs.toLocaleString();
870
- }
871
- document.getElementById('totalCampos').textContent = "102";
872
- } catch (e) {
873
- document.getElementById('totalDocs').textContent = 'indisponível';
874
- }
875
- };
876
- </script>
877
- </body>
878
- </html>
879
- """
880
 
881
  # ============================================
882
- # Funções auxiliares
883
  # ============================================
884
 
885
  def get_fresh_token():
@@ -1252,5 +771,3 @@ if __name__ == '__main__':
1252
  logger.warning(f"⚠️ Playwright pode não estar configurado: {e}")
1253
 
1254
  port = int(os.environ.get('PORT', 7860))
1255
- app.run(host='0.0.0.0', port=port, debug=False)
1256
-
 
1
+ O erro é simples: em Python, true e false devem ser escritos com T maiúsculo: True e False. No payload, você usou true (JavaScript) em vez de True (Python).
2
 
3
+ Aqui está o app.py corrigido:
4
+
5
+ ```python
6
  import os
7
  import sys
8
  import json
 
26
  app = Flask(__name__)
27
 
28
  # ============================================
29
+ # PAYLOAD COMPLETO com TODOS os campos (CORRIGIDO: True/False com maiúsculas)
30
  # ============================================
31
  PAYLOAD_COMPLETO = {
32
  "query": {
 
362
  "size": 100,
363
  "from": 0,
364
  "sort": [{"julgamento_data": {"order": "desc"}}],
365
+ "track_total_hits": True # <--- CORRIGIDO: true -> True
366
  }
367
 
368
  # Payload para busca de um documento específico por ID
 
393
  "expires_at": 0
394
  }
395
 
396
+ # Template HTML com visualização completa dos campos (MESMO CÓDIGO ANTERIOR)
397
+ # ... (manter o HTML_TEMPLATE exatamente como estava, omitido aqui por brevidade)
398
+ # NOTA: No código real, você deve copiar o HTML_TEMPLATE completo da resposta anterior
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
399
 
400
  # ============================================
401
+ # Funções auxiliares (MANTIDAS)
402
  # ============================================
403
 
404
  def get_fresh_token():
 
771
  logger.warning(f"⚠️ Playwright pode não estar configurado: {e}")
772
 
773
  port = int(os.environ.get('PORT', 7860))