caarleexx commited on
Commit
ed7a252
·
verified ·
1 Parent(s): cd040e7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +99 -512
app.py CHANGED
@@ -20,7 +20,7 @@ logger = logging.getLogger(__name__)
20
  app = Flask(__name__)
21
 
22
  # ============================================
23
- # PAYLOAD COMPLETO (com True/False maiúsculos)
24
  # ============================================
25
  PAYLOAD_COMPLETO = {
26
  "query": {
@@ -233,11 +233,35 @@ PAYLOAD_COMPLETO = {
233
  "track_total_hits": True
234
  }
235
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
236
  # Payload para busca por ID
237
  PAYLOAD_POR_ID = {
238
  "query": {"ids": {"values": []}},
239
  "_source": PAYLOAD_COMPLETO["_source"],
240
- "highlight": PAYLOAD_COMPLETO["highlight"],
241
  "size": 1
242
  }
243
 
@@ -255,485 +279,9 @@ HEADERS = {
255
  token_cache = {"token": None, "expires_at": 0}
256
 
257
  # ============================================
258
- # HTML TEMPLATE COMPLETO (com abas, botões, etc.)
259
  # ============================================
260
- HTML_TEMPLATE = """
261
- <!DOCTYPE html>
262
- <html>
263
- <head>
264
- <title>⚖️ STF Jurisprudência - Visualizador Completo</title>
265
- <meta charset="utf-8">
266
- <meta name="viewport" content="width=device-width, initial-scale=1">
267
- <style>
268
- body { font-family: 'Segoe UI', Roboto, system-ui, sans-serif; max-width: 1600px; margin: 0 auto; padding: 20px; background: #f0f2f5; }
269
- .container { background: white; border-radius: 12px; padding: 30px; box-shadow: 0 8px 20px rgba(0,0,0,0.1); }
270
- h1 { color: #1a1a2e; border-bottom: 3px solid #4CAF50; padding-bottom: 15px; display: flex; align-items: center; gap: 10px; }
271
- h1:before { content: "⚖️"; font-size: 1.2em; }
272
- h2 { color: #2c3e50; margin-top: 25px; margin-bottom: 15px; font-size: 1.5em; border-left: 5px solid #4CAF50; padding-left: 15px; }
273
- h3 { color: #34495e; margin-top: 20px; margin-bottom: 10px; font-size: 1.2em; border-bottom: 1px solid #e0e0e0; padding-bottom: 8px; }
274
- .info-box { background: #e8f0fe; border-left: 5px solid #2196F3; padding: 15px 20px; margin: 20px 0; border-radius: 8px; }
275
- .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin: 25px 0; }
276
- .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); }
277
- .stat-value { font-size: 32px; font-weight: bold; color: #1a73e8; }
278
- .stat-label { color: #5f6368; font-size: 14px; margin-top: 8px; text-transform: uppercase; letter-spacing: 0.5px; }
279
- .button-group { display: flex; gap: 15px; flex-wrap: wrap; margin: 25px 0; }
280
- 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); }
281
- button:hover { background: #1557b0; transform: translateY(-2px); box-shadow: 0 4px 12px rgba(26,115,232,0.4); }
282
- button:disabled { background: #a0a0a0; cursor: not-allowed; transform: none; box-shadow: none; }
283
- button.secondary { background: #34a853; }
284
- button.secondary:hover { background: #2d8745; }
285
- button.download { background: #f9ab00; color: #1a1a2e; }
286
- button.download:hover { background: #e69c00; }
287
- .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; }
288
- @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
289
- 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); }
290
- .success { color: #0f9d58; background: #e6f4ea; border-left: 5px solid #34a853; padding: 15px 20px; margin: 15px 0; border-radius: 8px; font-weight: 500; }
291
- .error { color: #d93025; background: #fce8e6; border-left: 5px solid #ea4335; padding: 15px 20px; margin: 15px 0; border-radius: 8px; font-weight: 500; }
292
- .warning { color: #e37400; background: #fef7e0; border-left: 5px solid #f9ab00; padding: 15px 20px; margin: 15px 0; border-radius: 8px; font-weight: 500; }
293
- .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; }
294
- .token-label { color: #f9ab00; font-weight: bold; margin-bottom: 8px; display: block; }
295
- .filters { background: #f8f9fa; border-radius: 8px; padding: 20px; margin: 20px 0; border: 1px solid #e0e0e0; }
296
- .filter-group { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; align-items: end; }
297
- .filter-item { min-width: 200px; }
298
- .filter-item label { display: block; margin-bottom: 8px; color: #5f6368; font-size: 14px; font-weight: 500; }
299
- .filter-item input, .filter-item select { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; font-size: 14px; }
300
- .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); }
301
- .badge { display: inline-block; background: #e8f0fe; color: #1a73e8; padding: 4px 12px; border-radius: 20px; font-size: 13px; font-weight: 500; margin: 2px; }
302
- .campo-lista { background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 15px; margin: 10px 0; }
303
- .campo-nome { font-weight: bold; color: #2c3e50; font-size: 14px; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 5px; }
304
- .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; }
305
- .campo-vazio { color: #999; font-style: italic; }
306
- .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; }
307
- .nav-tabs { display: flex; gap: 5px; margin: 20px 0; flex-wrap: wrap; border-bottom: 2px solid #e0e0e0; padding-bottom: 10px; }
308
- .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; }
309
- .nav-tab:hover { background: #f0f0f0; }
310
- .nav-tab.active { background: #1a73e8; color: white; border-color: #1a73e8; }
311
- .tab-content { display: none; padding: 20px; background: white; border: 1px solid #e0e0e0; border-top: none; border-radius: 0 0 8px 8px; }
312
- .tab-content.active { display: block; }
313
- .campo-card { background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 15px; margin: 10px 0; transition: all 0.2s; }
314
- .campo-card:hover { box-shadow: 0 4px 12px rgba(0,0,0,0.1); border-color: #1a73e8; }
315
- .flag-true { color: #0f9d58; font-weight: bold; }
316
- .flag-false { color: #d93025; }
317
- .url-link { color: #1a73e8; text-decoration: none; word-break: break-all; }
318
- .url-link:hover { text-decoration: underline; }
319
- .highlight { background-color: #f9ab00; color: #1a1a2e; font-weight: bold; padding: 2px 4px; border-radius: 4px; }
320
- .highlight-box { background: #fef7e0; border: 1px solid #f9ab00; padding: 10px; border-radius: 8px; margin: 10px 0; }
321
- .highlight-title { font-weight: bold; color: #e37400; margin-bottom: 5px; }
322
- </style>
323
- </head>
324
- <body>
325
- <div class="container">
326
- <h1>STF Jurisprudência - Visualizador Completo</h1>
327
-
328
- <div class="info-box">
329
- <strong>📌 API de Jurisprudência do STF - Todos os Campos com Highlight</strong><br>
330
- • Total de campos disponíveis: <span id="totalCampos">102</span><br>
331
- • Campos com highlight: 22 campos configurados<br>
332
- • Documentos disponíveis: <span id="totalDocs">carregando...</span>
333
- </div>
334
-
335
- <div class="stats-grid">
336
- <div class="stat-card"><div class="stat-value" id="requestsCount">0</div><div class="stat-label">Requisições</div></div>
337
- <div class="stat-card"><div class="stat-value" id="successCount">0</div><div class="stat-label">Sucessos</div></div>
338
- <div class="stat-card"><div class="stat-value" id="failCount">0</div><div class="stat-label">Falhas</div></div>
339
- <div class="stat-card"><div class="stat-value" id="docsCount">0</div><div class="stat-label">Docs Obtidos</div></div>
340
- </div>
341
-
342
- <div class="filters">
343
- <h3 style="margin-top: 0;">🔍 Filtros de Busca</h3>
344
- <div class="filter-group">
345
- <div class="filter-item">
346
- <label>Quantidade</label>
347
- <select id="pageSize">
348
- <option value="5">5 resultados</option>
349
- <option value="10">10 resultados</option>
350
- <option value="25">25 resultados</option>
351
- <option value="50">50 resultados</option>
352
- <option value="100" selected>100 resultados</option>
353
- </select>
354
- </div>
355
- <div class="filter-item">
356
- <label>Ordenar por</label>
357
- <select id="sortOrder">
358
- <option value="desc">Mais recentes</option>
359
- <option value="asc">Mais antigos</option>
360
- </select>
361
- </div>
362
- <div class="filter-item">
363
- <label>Base</label>
364
- <select id="base">
365
- <option value="acordaos">Acórdãos</option>
366
- <option value="decisoes">Decisões</option>
367
- <option value="sumulas">Súmulas</option>
368
- <option value="informativos">Informativos</option>
369
- <option value="">Todas</option>
370
- </select>
371
- </div>
372
- <div class="filter-item">
373
- <label>Busca por ID</label>
374
- <input type="text" id="docId" placeholder="Ex: sjur505215">
375
- </div>
376
- </div>
377
- </div>
378
-
379
- <div class="button-group">
380
- <button id="testBtn" onclick="runSearch()">
381
- <span class="loading" id="loading" style="display: none;"></span>
382
- <span>🔍 Buscar Documentos</span>
383
- </button>
384
- <button id="getByIdBtn" class="secondary" onclick="getDocumentById()">
385
- <span>📄 Buscar por ID</span>
386
- </button>
387
- <button id="downloadBtn" class="download" onclick="downloadJSON()" disabled>
388
- 📥 Download JSON
389
- </button>
390
- <button id="copyBtn" class="secondary" onclick="copyToken()">
391
- 🔑 Copiar Token
392
- </button>
393
- </div>
394
-
395
- <div id="tokenDisplay" style="display: none;" class="token-box">
396
- <span class="token-label">🔐 Token AWS WAF</span>
397
- <span id="tokenValue"></span>
398
- </div>
399
-
400
- <div id="result" style="margin-top: 25px;"></div>
401
- </div>
402
-
403
- <script>
404
- let lastResult = null;
405
- let lastToken = null;
406
- let requestsCount = 0, successCount = 0, failCount = 0, docsCount = 0;
407
-
408
- function renderCampo(nome, valor, tipo = 'normal') {
409
- if (valor === null || valor === undefined || valor === '') {
410
- return `<div class="campo-card"><div class="campo-nome">${nome}</div><div class="campo-vazio">(vazio)</div></div>`;
411
- }
412
- if (tipo === 'url' && valor) {
413
- 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>`;
414
- }
415
- if (tipo === 'flag') {
416
- const flagClass = valor ? 'flag-true' : 'flag-false';
417
- return `<div class="campo-card"><div class="campo-nome">${nome}</div><div class="campo-valor ${flagClass}">${valor ? '✓ Sim' : '✗ Não'}</div></div>`;
418
- }
419
- if (tipo === 'texto' && valor && valor.length > 200) {
420
- 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>`;
421
- }
422
- if (Array.isArray(valor)) {
423
- return `<div class="campo-card"><div class="campo-nome">${nome}</div><div class="campo-valor">${valor.join('<br>')}</div></div>`;
424
- }
425
- 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>`;
426
- }
427
-
428
- function renderHighlight(highlight) {
429
- if (!highlight) return '';
430
- let html = '<div class="highlight-box"><div class="highlight-title">🔆 Termos destacados (highlight):</div>';
431
- for (const [campo, valores] of Object.entries(highlight)) {
432
- if (valores && valores.length > 0) {
433
- html += `<div><strong>${campo}:</strong> `;
434
- valores.forEach(valor => {
435
- html += `<div style="margin-left: 20px; margin-top: 5px;">${valor.replace(/<em>/g, '<span class="highlight">').replace(/<\\/em>/g, '</span>')}</div>`;
436
- });
437
- html += '</div>';
438
- }
439
- }
440
- html += '</div>';
441
- return html;
442
- }
443
-
444
- function displayResult(data) {
445
- if (!data || !data.result || !data.result.hits || !data.result.hits.hits || data.result.hits.hits.length === 0) {
446
- document.getElementById('result').innerHTML = '<div class="warning">⚠️ Nenhum documento encontrado</div>';
447
- return;
448
- }
449
-
450
- const hits = data.result.hits.hits;
451
- const total = data.result.hits.total?.value || 0;
452
-
453
- let html = `<div class="success">✅ Encontrados ${total.toLocaleString()} documentos. Exibindo ${hits.length} resultados.</div>`;
454
-
455
- hits.forEach((hit, index) => {
456
- const source = hit._source || {};
457
- const highlight = hit.highlight || {};
458
- const docId = source.id || hit._id || `doc_${index}`;
459
-
460
- html += `<div class="campo-lista" style="margin-top: 30px;">`;
461
- html += `<h3 style="display: flex; justify-content: space-between; align-items: center;">
462
- <span>📄 Documento ${index + 1}: ${source.titulo || source.processo_codigo_completo || docId}</span>
463
- <span class="badge">ID: ${docId}</span>
464
- </h3>`;
465
-
466
- // Abas internas para cada documento
467
- html += `<div style="display: flex; gap: 5px; margin: 15px 0; flex-wrap: wrap;">`;
468
- html += `<button class="badge" style="cursor: pointer;" onclick="showDocTab('geral-${index}')">📋 Geral</button>`;
469
- html += `<button class="badge" style="cursor: pointer;" onclick="showDocTab('ementa-${index}')">📝 Ementa</button>`;
470
- html += `<button class="badge" style="cursor: pointer;" onclick="showDocTab('acordao-${index}')">⚖️ Acórdão</button>`;
471
- html += `<button class="badge" style="cursor: pointer;" onclick="showDocTab('legislacao-${index}')">📚 Legislação</button>`;
472
- html += `<button class="badge" style="cursor: pointer;" onclick="showDocTab('highlight-${index}')">🔆 Highlight</button>`;
473
- html += `<button class="badge" style="cursor: pointer;" onclick="showDocTab('completo-${index}')">📋 Todos Campos</button>`;
474
- html += `</div>`;
475
-
476
- // Aba: Geral
477
- html += `<div id="doc-tab-geral-${index}" class="doc-tab" style="display: block;">`;
478
- html += renderCampo('Processo', source.processo_codigo_completo);
479
- html += renderCampo('Classe', source.processo_classe_processual_unificada_extenso);
480
- html += renderCampo('Órgão Julgador', source.orgao_julgador);
481
- html += renderCampo('Relator', source.relator_processo_nome);
482
- html += renderCampo('Relator Acórdão', source.relator_acordao_nome);
483
- html += renderCampo('Ministros', source.ministro_facet);
484
- html += renderCampo('Data Julgamento', source.julgamento_data);
485
- html += renderCampo('Data Publicação', source.publicacao_data);
486
- html += renderCampo('Procedência', source.procedencia_geografica_completo);
487
- html += renderCampo('UF', source.procedencia_geografica_uf_sigla);
488
- html += `</div>`;
489
-
490
- // Aba: Ementa
491
- html += `<div id="doc-tab-ementa-${index}" class="doc-tab" style="display: none;">`;
492
- html += renderCampo('Ementa', source.ementa_texto, 'texto');
493
- html += renderCampo('Tese', source.documental_tese_texto, 'texto');
494
- html += renderCampo('Tema', source.documental_tese_tema_texto);
495
- html += `</div>`;
496
-
497
- // Aba: Acórdão
498
- html += `<div id="doc-tab-acordao-${index}" class="doc-tab" style="display: none;">`;
499
- html += renderCampo('Acórdão/Ata', source.acordao_ata, 'texto');
500
- html += renderCampo('Decisão', source.decisao_texto, 'texto');
501
- html += renderCampo('Súmula', source.sumula_texto, 'texto');
502
- html += renderCampo('Indexação', source.documental_indexacao_texto, 'texto');
503
- html += renderCampo('Observações', source.documental_observacao_texto, 'texto');
504
- html += `</div>`;
505
-
506
- // Aba: Legislação
507
- html += `<div id="doc-tab-legislacao-${index}" class="doc-tab" style="display: none;">`;
508
- html += renderCampo('Legislação Citada', source.documental_legislacao_citada_texto, 'texto');
509
- html += renderCampo('Jurisprudência Citada', source.documental_jurisprudencia_citada_texto, 'texto');
510
- html += renderCampo('Doutrina', source.documental_doutrina_texto, 'texto');
511
- html += renderCampo('Precedentes', source.processo_precedente_texto, 'texto');
512
- html += `</div>`;
513
-
514
- // Aba: Highlight
515
- html += `<div id="doc-tab-highlight-${index}" class="doc-tab" style="display: none;">`;
516
- if (Object.keys(highlight).length > 0) {
517
- for (const [campo, valores] of Object.entries(highlight)) {
518
- if (valores && valores.length > 0) {
519
- html += `<div class="campo-card">`;
520
- html += `<div class="campo-nome">${campo}</div>`;
521
- valores.forEach(valor => {
522
- html += `<div class="highlight-box" style="margin-top: 5px;">${valor.replace(/<em>/g, '<span class="highlight">').replace(/<\\/em>/g, '</span>')}</div>`;
523
- });
524
- html += `</div>`;
525
- }
526
- }
527
- } else {
528
- html += `<div class="campo-vazio">Nenhum termo destacado</div>`;
529
- }
530
- html += `</div>`;
531
-
532
- // Aba: Todos Campos
533
- html += `<div id="doc-tab-completo-${index}" class="doc-tab" style="display: none;">`;
534
- html += `<pre>${JSON.stringify(source, null, 2).replace(/<em>/g, '<span class="highlight">').replace(/<\\/em>/g, '</span>')}</pre>`;
535
- html += `</div>`;
536
-
537
- // URLs importantes
538
- if (source.inteiro_teor_url) {
539
- html += `<div style="margin-top: 15px; padding: 10px; background: #e8f0fe; border-radius: 8px;">`;
540
- html += `<strong>🔗 Links:</strong><br>`;
541
- html += `<a href="${source.inteiro_teor_url}" target="_blank" class="url-link">📄 Inteiro Teor</a><br>`;
542
- if (source.acompanhamento_processual_url) {
543
- html += `<a href="${source.acompanhamento_processual_url}" target="_blank" class="url-link">📊 Acompanhamento Processual</a><br>`;
544
- }
545
- if (source.dje_url) {
546
- html += `<a href="${source.dje_url}" target="_blank" class="url-link">📰 DJE</a>`;
547
- }
548
- html += `</div>`;
549
- }
550
-
551
- html += `</div>`; // Fecha campo-lista
552
- });
553
-
554
- document.getElementById('result').innerHTML = html;
555
- }
556
-
557
- function showDocTab(tabId) {
558
- const docIndex = tabId.split('-')[2];
559
- document.querySelectorAll(`[id^="doc-tab-"]`).forEach(el => {
560
- if (el.id.includes(`-${docIndex}`)) {
561
- el.style.display = 'none';
562
- }
563
- });
564
- const selectedTab = document.getElementById(`doc-tab-${tabId}`);
565
- if (selectedTab) {
566
- selectedTab.style.display = 'block';
567
- }
568
- }
569
-
570
- async function runSearch() {
571
- const btn = document.getElementById('testBtn');
572
- const loading = document.getElementById('loading');
573
- const resultDiv = document.getElementById('result');
574
- const pageSize = document.getElementById('pageSize').value;
575
- const sortOrder = document.getElementById('sortOrder').value;
576
- const base = document.getElementById('base').value;
577
-
578
- btn.disabled = true;
579
- loading.style.display = 'inline-block';
580
- resultDiv.innerHTML = '<div class="info-box">⏳ Executando busca no STF...</div>';
581
-
582
- try {
583
- const response = await fetch('/api/search-advanced', {
584
- method: 'POST',
585
- headers: { 'Content-Type': 'application/json' },
586
- body: JSON.stringify({
587
- pageSize: parseInt(pageSize),
588
- sortOrder,
589
- base: base || undefined
590
- })
591
- });
592
-
593
- const data = await response.json();
594
- requestsCount++;
595
- document.getElementById('requestsCount').textContent = requestsCount;
596
-
597
- if (data.success) {
598
- successCount++;
599
- document.getElementById('successCount').textContent = successCount;
600
-
601
- if (data.data && data.data.result && data.data.result.hits) {
602
- docsCount = data.data.result.hits.hits.length;
603
- document.getElementById('docsCount').textContent = docsCount;
604
-
605
- if (data.data.result.hits.total && data.data.result.hits.total.value) {
606
- document.getElementById('totalDocs').textContent = data.data.result.hits.total.value.toLocaleString();
607
- }
608
- }
609
-
610
- lastResult = data.data;
611
- lastToken = data.token;
612
-
613
- if (lastToken) {
614
- document.getElementById('tokenValue').textContent = lastToken;
615
- document.getElementById('tokenDisplay').style.display = 'block';
616
- document.getElementById('downloadBtn').disabled = false;
617
- }
618
-
619
- displayResult(data.data);
620
-
621
- } else {
622
- failCount++;
623
- document.getElementById('failCount').textContent = failCount;
624
-
625
- let errorHtml = '<div class="error">❌ Falha na busca</div>';
626
- if (data.attempts) {
627
- data.attempts.forEach(attempt => {
628
- errorHtml += `<div class="warning"><strong>${attempt.method}:</strong> ${attempt.error || 'Erro'}</div>`;
629
- });
630
- }
631
- errorHtml += '<pre>' + JSON.stringify(data, null, 2) + '</pre>';
632
- resultDiv.innerHTML = errorHtml;
633
- }
634
- } catch (error) {
635
- failCount++;
636
- document.getElementById('failCount').textContent = failCount;
637
- resultDiv.innerHTML = '<div class="error">❌ Erro: ' + error.message + '</div>';
638
- } finally {
639
- btn.disabled = false;
640
- loading.style.display = 'none';
641
- }
642
- }
643
-
644
- async function getDocumentById() {
645
- const docId = document.getElementById('docId').value.trim();
646
- if (!docId) {
647
- alert('Digite um ID');
648
- return;
649
- }
650
-
651
- const btn = document.getElementById('getByIdBtn');
652
- const loading = document.getElementById('loading');
653
- const resultDiv = document.getElementById('result');
654
-
655
- btn.disabled = true;
656
- loading.style.display = 'inline-block';
657
- resultDiv.innerHTML = '<div class="info-box">⏳ Buscando documento...</div>';
658
-
659
- try {
660
- const response = await fetch(`/api/document/${docId}`);
661
- const data = await response.json();
662
-
663
- requestsCount++;
664
- document.getElementById('requestsCount').textContent = requestsCount;
665
-
666
- if (data.success && data.document) {
667
- successCount++;
668
- document.getElementById('successCount').textContent = successCount;
669
- docsCount++;
670
- document.getElementById('docsCount').textContent = docsCount;
671
-
672
- lastResult = { result: { hits: { hits: [data.document] } } };
673
-
674
- displayResult(lastResult);
675
- } else {
676
- failCount++;
677
- document.getElementById('failCount').textContent = failCount;
678
- resultDiv.innerHTML = '<div class="error">❌ Documento não encontrado</div>';
679
- }
680
- } catch (error) {
681
- failCount++;
682
- document.getElementById('failCount').textContent = failCount;
683
- resultDiv.innerHTML = '<div class="error">❌ Erro: ' + error.message + '</div>';
684
- } finally {
685
- btn.disabled = false;
686
- loading.style.display = 'none';
687
- }
688
- }
689
-
690
- function downloadJSON() {
691
- if (!lastResult) {
692
- alert('Nenhum resultado para download');
693
- return;
694
- }
695
-
696
- const dataStr = JSON.stringify(lastResult, null, 2);
697
- const blob = new Blob([dataStr], { type: 'application/json' });
698
- const url = URL.createObjectURL(blob);
699
- const a = document.createElement('a');
700
- a.href = url;
701
- a.download = `stf_jurisprudencia_${new Date().toISOString().slice(0,10)}.json`;
702
- document.body.appendChild(a);
703
- a.click();
704
- document.body.removeChild(a);
705
- URL.revokeObjectURL(url);
706
- }
707
-
708
- function copyToken() {
709
- if (!lastToken) {
710
- alert('Nenhum token disponível. Execute uma busca primeiro.');
711
- return;
712
- }
713
-
714
- navigator.clipboard.writeText(lastToken).then(() => {
715
- alert('✅ Token copiado para área de transferência!');
716
- }).catch(() => {
717
- alert('❌ Erro ao copiar token');
718
- });
719
- }
720
-
721
- window.onload = async () => {
722
- try {
723
- const response = await fetch('/api/health');
724
- const data = await response.json();
725
- if (data.total_docs) {
726
- document.getElementById('totalDocs').textContent = data.total_docs.toLocaleString();
727
- }
728
- document.getElementById('totalCampos').textContent = "102";
729
- } catch (e) {
730
- document.getElementById('totalDocs').textContent = 'indisponível';
731
- }
732
- };
733
- </script>
734
- </body>
735
- </html>
736
- """
737
 
738
  # ============================================
739
  # Funções auxiliares
@@ -774,22 +322,63 @@ def get_fresh_token():
774
  logger.error(f"Erro ao obter token: {str(e)}")
775
  return None
776
 
777
- def search_with_token(token, custom_payload=None):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
778
  if not token:
779
  return {"success": False, "error": "Token não fornecido"}
780
- payload = custom_payload or PAYLOAD_COMPLETO
781
  headers = HEADERS.copy()
782
  headers['Cookie'] = f'aws-waf-token={token}'
783
  try:
 
784
  response = requests.post(URL_API, headers=headers, json=payload, verify=False, timeout=30)
 
785
  if response.status_code == 200:
786
  return {"success": True, "data": response.json()}
787
  elif response.status_code == 403:
788
  token_cache["token"] = None
789
  return {"success": False, "error": "Token expirado", "status": 403}
790
  else:
791
- return {"success": False, "error": f"HTTP {response.status_code}", "text": response.text[:500]}
792
  except Exception as e:
 
793
  return {"success": False, "error": str(e)}
794
 
795
  def get_document_by_id(token, doc_id):
@@ -840,7 +429,7 @@ def test_with_playwright_full(payload):
840
  token_cache["expires_at"] = time.time() + 3300
841
  return {"success": True, "data": api_result.get('data'), "token": token}
842
  else:
843
- return {"success": False, "error": api_result.get('error', 'Falha desconhecida'), "token": token}
844
  except Exception as e:
845
  logger.error(f"Erro no Playwright: {str(e)}")
846
  return {"success": False, "error": str(e)}
@@ -862,40 +451,37 @@ def search_advanced():
862
  sort_order = data.get('sortOrder', 'desc')
863
  base = data.get('base')
864
 
865
- payload = PAYLOAD_COMPLETO.copy()
866
- payload["size"] = min(page_size, 250)
867
- payload["sort"] = [{"julgamento_data": {"order": sort_order}}]
868
-
869
- if base:
870
- if "post_filter" not in payload:
871
- payload["post_filter"] = {"bool": {"must": []}}
872
- payload["post_filter"]["bool"]["must"] = [{"term": {"base": base}}]
873
-
874
  token = get_fresh_token()
875
  if not token:
 
 
 
 
 
 
876
  res = test_with_playwright_full(payload)
877
  if res.get('success'):
878
  return jsonify({"success": True, "token": res.get('token'), "data": res['data'], "timestamp": time.time()})
879
  else:
880
- return jsonify({"success": False, "error": res.get('error')}), 500
881
 
882
- result = search_with_token(token, payload)
883
- if result.get("success"):
884
- return jsonify({"success": True, "token": token, "data": result["data"], "timestamp": time.time()})
 
 
885
  else:
886
- if result.get("status") == 403:
887
- token_cache["token"] = None
888
- token = get_fresh_token()
889
- if token:
890
- result = search_with_token(token, payload)
891
- if result.get("success"):
892
- return jsonify({"success": True, "token": token, "data": result["data"], "timestamp": time.time()})
893
- # fallback
894
  res = test_with_playwright_full(payload)
895
  if res.get('success'):
896
  return jsonify({"success": True, "token": res.get('token'), "data": res['data'], "timestamp": time.time()})
897
  else:
898
- return jsonify({"success": False, "error": result.get('error')}), 500
899
 
900
  @app.route('/api/document/<doc_id>', methods=['GET'])
901
  def get_document(doc_id):
@@ -913,10 +499,12 @@ def get_document(doc_id):
913
  def test_bypass():
914
  token = get_fresh_token()
915
  if token:
916
- res = search_with_token(token)
917
- if res.get('success'):
918
- return jsonify({"success": True, "method": "token", "token": token, "data": res['data']})
919
- res = test_with_playwright_full(PAYLOAD_COMPLETO)
 
 
920
  if res.get('success'):
921
  return jsonify({"success": True, "method": "playwright", "token": res.get('token'), "data": res['data']})
922
  return jsonify({"success": False, "error": res.get('error', 'Falha')}), 500
@@ -973,7 +561,6 @@ if __name__ == '__main__':
973
  logger.info("="*50)
974
  logger.info("🚀 Iniciando aplicação STF Jurisprudência")
975
  logger.info(f"📋 Campos _source: {len(PAYLOAD_COMPLETO['_source'])}")
976
- logger.info(f"🔆 Campos highlight: {len(PAYLOAD_COMPLETO['highlight']['fields'])}")
977
  logger.info("="*50)
978
  try:
979
  with sync_playwright() as p:
@@ -982,4 +569,4 @@ if __name__ == '__main__':
982
  except Exception as e:
983
  logger.warning(f"⚠️ Playwright pode não estar configurado: {e}")
984
  port = int(os.environ.get('PORT', 7860))
985
- app.run(host='0.0.0.0', port=port, debug=False)
 
20
  app = Flask(__name__)
21
 
22
  # ============================================
23
+ # PAYLOAD COMPLETO (com todos os campos e highlight)
24
  # ============================================
25
  PAYLOAD_COMPLETO = {
26
  "query": {
 
233
  "track_total_hits": True
234
  }
235
 
236
+ # Payload sem highlight e sem aggs (apenas _source e query)
237
+ PAYLOAD_SEM_HIGHLIGHT = {
238
+ "query": PAYLOAD_COMPLETO["query"],
239
+ "_source": PAYLOAD_COMPLETO["_source"],
240
+ "size": 100,
241
+ "from": 0,
242
+ "sort": [{"julgamento_data": {"order": "desc"}}],
243
+ "track_total_hits": True
244
+ }
245
+
246
+ # Payload mínimo (apenas o essencial, testado anteriormente)
247
+ PAYLOAD_MINIMO = {
248
+ "query": {
249
+ "bool": {
250
+ "filter": [
251
+ {"term": {"base": "acordaos"}}
252
+ ]
253
+ }
254
+ },
255
+ "_source": ["id", "titulo", "ementa_texto", "processo_numero", "julgamento_data", "relator_processo_nome", "inteiro_teor_url"],
256
+ "size": 100,
257
+ "sort": [{"julgamento_data": {"order": "desc"}}],
258
+ "track_total_hits": True
259
+ }
260
+
261
  # Payload para busca por ID
262
  PAYLOAD_POR_ID = {
263
  "query": {"ids": {"values": []}},
264
  "_source": PAYLOAD_COMPLETO["_source"],
 
265
  "size": 1
266
  }
267
 
 
279
  token_cache = {"token": None, "expires_at": 0}
280
 
281
  # ============================================
282
+ # HTML TEMPLATE COMPLETO (mesmo da resposta anterior)
283
  # ============================================
284
+ HTML_TEMPLATE = """ ... """ # (inserir o HTML completo da resposta anterior)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
285
 
286
  # ============================================
287
  # Funções auxiliares
 
322
  logger.error(f"Erro ao obter token: {str(e)}")
323
  return None
324
 
325
+ def try_search_with_payloads(token, base_payload, sort_order='desc', base_filter=None):
326
+ """
327
+ Tenta vários payloads em ordem decrescente de complexidade até obter sucesso.
328
+ Retorna (success, data, payload_usado)
329
+ """
330
+ # Payload 1: completo com aggs e highlight
331
+ payload1 = base_payload.copy()
332
+ payload1["sort"] = [{"julgamento_data": {"order": sort_order}}]
333
+ if base_filter:
334
+ payload1["post_filter"] = {"bool": {"must": [{"term": {"base": base_filter}}]}}
335
+
336
+ logger.info("Tentando payload completo...")
337
+ res = search_with_token(token, payload1)
338
+ if res.get("success"):
339
+ return True, res["data"], "completo"
340
+
341
+ # Se falhou com 400, tenta sem highlight e sem aggs
342
+ if res.get("status") == 400:
343
+ logger.info("Payload completo falhou (400). Tentando payload sem highlight...")
344
+ payload2 = PAYLOAD_SEM_HIGHLIGHT.copy()
345
+ payload2["sort"] = [{"julgamento_data": {"order": sort_order}}]
346
+ if base_filter:
347
+ payload2["post_filter"] = {"bool": {"must": [{"term": {"base": base_filter}}]}}
348
+ res2 = search_with_token(token, payload2)
349
+ if res2.get("success"):
350
+ return True, res2["data"], "sem_highlight"
351
+
352
+ if res2.get("status") == 400:
353
+ logger.info("Payload sem highlight falhou. Tentando payload mínimo...")
354
+ payload3 = PAYLOAD_MINIMO.copy()
355
+ payload3["sort"] = [{"julgamento_data": {"order": sort_order}}]
356
+ if base_filter:
357
+ payload3["post_filter"] = {"bool": {"must": [{"term": {"base": base_filter}}]}}
358
+ res3 = search_with_token(token, payload3)
359
+ if res3.get("success"):
360
+ return True, res3["data"], "minimo"
361
+
362
+ return False, None, None
363
+
364
+ def search_with_token(token, payload):
365
  if not token:
366
  return {"success": False, "error": "Token não fornecido"}
 
367
  headers = HEADERS.copy()
368
  headers['Cookie'] = f'aws-waf-token={token}'
369
  try:
370
+ logger.debug(f"Enviando payload: {json.dumps(payload)[:200]}...")
371
  response = requests.post(URL_API, headers=headers, json=payload, verify=False, timeout=30)
372
+ logger.info(f"Resposta: status {response.status_code}")
373
  if response.status_code == 200:
374
  return {"success": True, "data": response.json()}
375
  elif response.status_code == 403:
376
  token_cache["token"] = None
377
  return {"success": False, "error": "Token expirado", "status": 403}
378
  else:
379
+ return {"success": False, "error": f"HTTP {response.status_code}", "status": response.status_code, "text": response.text[:500]}
380
  except Exception as e:
381
+ logger.error(f"Erro na requisição: {str(e)}")
382
  return {"success": False, "error": str(e)}
383
 
384
  def get_document_by_id(token, doc_id):
 
429
  token_cache["expires_at"] = time.time() + 3300
430
  return {"success": True, "data": api_result.get('data'), "token": token}
431
  else:
432
+ return {"success": False, "error": api_result.get('error', 'Falha desconhecida'), "status": api_result.get('status'), "token": token}
433
  except Exception as e:
434
  logger.error(f"Erro no Playwright: {str(e)}")
435
  return {"success": False, "error": str(e)}
 
451
  sort_order = data.get('sortOrder', 'desc')
452
  base = data.get('base')
453
 
 
 
 
 
 
 
 
 
 
454
  token = get_fresh_token()
455
  if not token:
456
+ # Fallback para Playwright
457
+ payload = PAYLOAD_MINIMO.copy()
458
+ payload["size"] = min(page_size, 250)
459
+ payload["sort"] = [{"julgamento_data": {"order": sort_order}}]
460
+ if base:
461
+ payload["post_filter"] = {"bool": {"must": [{"term": {"base": base}}]]}
462
  res = test_with_playwright_full(payload)
463
  if res.get('success'):
464
  return jsonify({"success": True, "token": res.get('token'), "data": res['data'], "timestamp": time.time()})
465
  else:
466
+ return jsonify({"success": False, "error": res.get('error', 'Falha')}), 500
467
 
468
+ # Tentar com múltiplos payloads
469
+ success, data, payload_type = try_search_with_payloads(token, PAYLOAD_COMPLETO, sort_order, base)
470
+ if success:
471
+ logger.info(f"Busca bem-sucedida com payload: {payload_type}")
472
+ return jsonify({"success": True, "token": token, "data": data, "timestamp": time.time()})
473
  else:
474
+ # Último recurso: Playwright
475
+ payload = PAYLOAD_MINIMO.copy()
476
+ payload["size"] = min(page_size, 250)
477
+ payload["sort"] = [{"julgamento_data": {"order": sort_order}}]
478
+ if base:
479
+ payload["post_filter"] = {"bool": {"must": [{"term": {"base": base}}]]}
 
 
480
  res = test_with_playwright_full(payload)
481
  if res.get('success'):
482
  return jsonify({"success": True, "token": res.get('token'), "data": res['data'], "timestamp": time.time()})
483
  else:
484
+ return jsonify({"success": False, "error": "Todas as tentativas falharam"}), 500
485
 
486
  @app.route('/api/document/<doc_id>', methods=['GET'])
487
  def get_document(doc_id):
 
499
  def test_bypass():
500
  token = get_fresh_token()
501
  if token:
502
+ # Tenta payload completo
503
+ success, data, _ = try_search_with_payloads(token, PAYLOAD_COMPLETO, 'desc', None)
504
+ if success:
505
+ return jsonify({"success": True, "method": "token", "token": token, "data": data})
506
+ # Fallback Playwright com payload mínimo
507
+ res = test_with_playwright_full(PAYLOAD_MINIMO)
508
  if res.get('success'):
509
  return jsonify({"success": True, "method": "playwright", "token": res.get('token'), "data": res['data']})
510
  return jsonify({"success": False, "error": res.get('error', 'Falha')}), 500
 
561
  logger.info("="*50)
562
  logger.info("🚀 Iniciando aplicação STF Jurisprudência")
563
  logger.info(f"📋 Campos _source: {len(PAYLOAD_COMPLETO['_source'])}")
 
564
  logger.info("="*50)
565
  try:
566
  with sync_playwright() as p:
 
569
  except Exception as e:
570
  logger.warning(f"⚠️ Playwright pode não estar configurado: {e}")
571
  port = int(os.environ.get('PORT', 7860))
572
+ app.run(host='0.0.0.0', port=port, debug=False)