caarleexx commited on
Commit
780b2b1
·
verified ·
1 Parent(s): 1b45748

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +128 -137
app.py CHANGED
@@ -1,5 +1,4 @@
1
  import os
2
- import sys
3
  import json
4
  import time
5
  import logging
@@ -7,7 +6,6 @@ import requests
7
  import urllib3
8
  from flask import Flask, request, jsonify
9
  from playwright.sync_api import sync_playwright
10
- from datetime import datetime
11
 
12
  urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
13
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
@@ -21,180 +19,167 @@ HEADERS = {
21
  "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
22
  "Referer": "https://jurisprudencia.stf.jus.br/pages/search",
23
  "Origin": "https://jurisprudencia.stf.jus.br",
 
24
  "Sec-Fetch-Dest": "empty",
25
  "Sec-Fetch-Mode": "cors",
26
  "Sec-Fetch-Site": "same-origin"
27
  }
28
  token_cache = {"token": None, "expires_at": 0}
29
 
30
- PAYLOAD_BASE = {
31
- "query": {
32
- "function_score": {
33
- "functions": [{"exp": {"julgamento_data": {"origin": "now", "scale": "47450d", "offset": "1095d", "decay": 0.1}}}],
34
- "query": {
35
- "bool": {
36
- "should": [
37
- {"query_string": {"fields": ["ementa_texto.plural^3"], "query": "", "type": "cross_fields", "fuzziness": "AUTO:4,7"}},
38
- {"query_string": {"fields": ["acordao_ata.plural^3", "decisao_texto.plural^2"], "query": "", "type": "cross_fields", "fuzziness": "AUTO:4,7"}},
39
- {"query_string": {"fields": ["documental_tese_texto.plural^3"], "query": "", "type": "cross_fields", "fuzziness": "AUTO:4,7"}}
40
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  }
42
  }
43
- }
44
- },
45
- "_source": [
46
- "id", "titulo", "ementa_texto", "acordao_ata", "decisao_texto",
47
- "documental_tese_texto", "orgao_julgador", "relator_processo_nome",
48
- "julgamento_data", "processo_codigo_completo", "inteiro_teor_url",
49
- "acompanhamento_processual_url", "dje_url"
50
- ],
51
- "highlight": {
52
- "fields": {
53
- "ementa_texto": {"matched_fields": ["ementa_texto.plural"], "type": "fvh", "fragment_size": 1000},
54
- "acordao_ata": {"matched_fields": ["acordao_ata.plural"], "type": "fvh", "fragment_size": 800},
55
- "decisao_texto": {"matched_fields": ["decisao_texto.plural"], "type": "fvh", "fragment_size": 800},
56
- "documental_tese_texto": {"matched_fields": ["documental_tese_texto.plural"], "type": "fvh", "fragment_size": 800}
57
  },
58
- "pre_tags": ["<em>"], "post_tags": ["</em>"]
59
- },
60
- "size": 20,
61
- "sort": [{"_score": "desc"}],
62
- "track_total_hits": True
63
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
 
65
 
66
- def get_fresh_token_stealth():
67
- """Token com Playwright stealth melhorado"""
68
  global token_cache
69
  if token_cache["token"] and time.time() < token_cache["expires_at"]:
70
  return token_cache["token"]
71
-
72
- logger.info("🔄 Obtendo token STEALTH...")
73
  try:
74
  with sync_playwright() as p:
75
- browser = p.chromium.launch(
76
- headless=True,
77
- args=[
78
- "--no-sandbox",
79
- "--disable-setuid-sandbox",
80
- "--disable-dev-shm-usage",
81
- "--disable-accelerated-2d-canvas",
82
- "--no-first-run",
83
- "--no-zygote",
84
- "--disable-gpu"
85
- ]
86
- )
87
  context = browser.new_context(
88
  viewport={"width": 1920, "height": 1080},
89
  user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
90
  locale="pt-BR",
91
  timezone_id="America/Sao_Paulo",
92
- permissions=["geolocation"],
93
- extra_http_headers={
94
- "Accept-Language": "pt-BR,pt;q=0.9,en;q=0.8",
95
- "Sec-Ch-Ua": '"Not_A Brand";v="8", "Chromium";v="122", "Google Chrome";v="122"',
96
- "Sec-Ch-Ua-Mobile": "?0",
97
- "Sec-Ch-Ua-Platform": '"Windows"'
98
- }
99
  )
100
  page = context.new_page()
101
-
102
- # Simula scroll e mouse
103
  page.goto("https://jurisprudencia.stf.jus.br/pages/search", wait_until="networkidle", timeout=45000)
104
- page.wait_for_timeout(5000)
105
  page.mouse.move(300, 400)
106
  page.wait_for_timeout(1000)
107
- page.mouse.wheel(0, 300)
108
- page.wait_for_timeout(2000)
109
-
110
  cookies = context.cookies()
111
- token = next((c.get("value") for c in cookies if c.get("name") == "aws-waf-token"), None)
112
  browser.close()
113
-
114
  if token:
115
  token_cache["token"] = token
116
  token_cache["expires_at"] = time.time() + 3300
117
- logger.info(f"✅ Token obtido: {token[:20]}...")
118
  return token
119
- logger.error("❌ Token não encontrado")
120
  except Exception as e:
121
- logger.error(f"❌ Erro stealth: {e}")
122
  return None
123
 
124
 
125
- def search_stf(query, page=1):
126
- token = get_fresh_token_stealth()
 
127
  if not token:
128
- # Fallback direto sem token (algumas APIs funcionam)
129
- logger.warning("Tentando sem token...")
130
- payload = json.loads(json.dumps(PAYLOAD_BASE))
131
- payload["query"]["function_score"]["query"]["bool"]["should"][0]["query_string"]["query"] = query
132
- payload["query"]["function_score"]["query"]["bool"]["should"][1]["query_string"]["query"] = query
133
- payload["query"]["function_score"]["query"]["bool"]["should"][2]["query_string"]["query"] = query
134
- payload["from"] = (page - 1) * payload["size"]
135
-
136
- try:
137
- resp = requests.post(URL_API, headers=HEADERS, json=payload, verify=False, timeout=20)
138
- if resp.status_code == 200:
139
- return process_response(resp.json(), query, page)
140
- logger.warning(f"Fallback falhou: {resp.status_code}")
141
- except:
142
- pass
143
- return {"error": "Token WAF bloqueou. Tente novamente em 30s"}
144
-
145
  headers = HEADERS.copy()
146
  headers["Cookie"] = f"aws-waf-token={token}"
147
-
148
- payload = json.loads(json.dumps(PAYLOAD_BASE))
149
- payload["query"]["function_score"]["query"]["bool"]["should"][0]["query_string"]["query"] = query
150
- payload["query"]["function_score"]["query"]["bool"]["should"][1]["query_string"]["query"] = query
151
- payload["query"]["function_score"]["query"]["bool"]["should"][2]["query_string"]["query"] = query
152
- payload["from"] = (page - 1) * payload["size"]
153
-
154
  try:
155
  resp = requests.post(URL_API, headers=headers, json=payload, verify=False, timeout=30)
 
 
 
 
156
  if resp.status_code != 200:
157
- if resp.status_code == 403:
158
- token_cache["token"] = None
159
- logger.warning(f"HTTP {resp.status_code}")
160
- return {"error": f"HTTP {resp.status_code}. Token pode ter expirado"}
161
-
162
  data = resp.json()
163
- return process_response(data, query, page)
 
 
 
164
  except Exception as e:
165
- logger.error(f"Erro busca: {e}")
166
- return {"error": str(e)}
167
 
168
 
169
- def process_response(data, query, page):
170
- hits = data.get("hits", {}).get("hits", [])
171
  results = []
172
-
173
  for hit in hits:
174
  source = hit.get("_source", {})
175
  hl = hit.get("highlight", {})
176
 
177
- # Ementa com prioridade
178
- ementa_candidates = [
179
- hl.get("ementa_texto", [None])[0],
180
- hl.get("documental_tese_texto", [None])[0],
181
- hl.get("acordao_ata", [None])[0],
182
- hl.get("decisao_texto", [None])[0],
183
- source.get("ementa_texto"),
184
- source.get("documental_tese_texto"),
185
- source.get("acordao_ata"),
186
- source.get("decisao_texto")
187
- ]
188
- ementa_raw = next((c for c in ementa_candidates if c), "")
189
- ementa = ementa_raw[:800] + "..." if len(ementa_raw) > 800 else ementa_raw
190
-
191
- # URL documento
192
- url_doc = (source.get("inteiro_teor_url") or
193
- source.get("acompanhamento_processual_url") or
194
- source.get("dje_url") or None)
195
-
196
- # Citação
197
- citacao = f"({source.get('orgao_julgador', 'STF')} - {source.get('processo_codigo_completo', '')} - Rel: {source.get('relator_processo_nome', 'N/I')} - {source.get('julgamento_data', '')[:10]})"
 
198
 
199
  results.append({
200
  "id": source.get("id"),
@@ -207,34 +192,40 @@ def process_response(data, query, page):
207
  "ementa": ementa.strip(),
208
  "citacao": citacao.strip()
209
  })
210
-
211
- return {
212
- "success": True,
213
- "query": query,
214
- "total": data.get("hits", {}).get("total", {}).get("value", 0),
215
- "page": page,
216
- "size": PAYLOAD_BASE["size"],
217
- "results": results
218
- }
219
 
220
 
221
  @app.route("/busca")
222
  def busca():
223
  query = request.args.get("q", "").strip()
224
  page = max(1, int(request.args.get("page", 1)))
 
225
 
226
  if not query:
227
  return jsonify({"error": "Parâmetro 'q' é obrigatório"}), 400
228
 
229
- return jsonify(search_stf(query, page))
 
 
 
 
 
 
 
 
 
 
 
 
 
230
 
231
 
232
  @app.route("/health")
233
  def health():
234
  return jsonify({
235
- "status": "ok",
236
  "token_ok": bool(token_cache["token"]),
237
- "token_expires": max(0, token_cache["expires_at"] - time.time()) if token_cache["expires_at"] else 0
238
  })
239
 
240
 
 
1
  import os
 
2
  import json
3
  import time
4
  import logging
 
6
  import urllib3
7
  from flask import Flask, request, jsonify
8
  from playwright.sync_api import sync_playwright
 
9
 
10
  urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
11
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
 
19
  "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
20
  "Referer": "https://jurisprudencia.stf.jus.br/pages/search",
21
  "Origin": "https://jurisprudencia.stf.jus.br",
22
+ "Accept-Language": "pt-BR,pt;q=0.9",
23
  "Sec-Fetch-Dest": "empty",
24
  "Sec-Fetch-Mode": "cors",
25
  "Sec-Fetch-Site": "same-origin"
26
  }
27
  token_cache = {"token": None, "expires_at": 0}
28
 
29
+
30
+ def build_payload(query, page=1, size=20):
31
+ """Payload fiel ao app-7.py com query substituível"""
32
+ q = query or "*"
33
+ return {
34
+ "query": {
35
+ "function_score": {
36
+ "functions": [
37
+ {"exp": {"julgamento_data": {"origin": "now", "scale": "47450d", "offset": "1095d", "decay": 0.1}}}
38
+ ],
39
+ "query": {
40
+ "bool": {
41
+ "filter": [
42
+ {
43
+ "query_string": {
44
+ "default_operator": "AND",
45
+ "fields": [
46
+ "ementa_texto.plural^3",
47
+ "acordao_ata.plural^3",
48
+ "documental_tese_texto.plural^3",
49
+ "documental_tese_tema_texto.plural^3",
50
+ "titulo.plural^6",
51
+ "decisao_texto.plural^2",
52
+ "sumula_texto.plural^3",
53
+ "ramo_direito.plural^1",
54
+ "documental_legislacao_citada_texto.plural",
55
+ "documental_jurisprudencia_citada_texto.plural"
56
+ ],
57
+ "query": q,
58
+ "type": "cross_fields",
59
+ "fuzziness": "AUTO:4,7"
60
+ }
61
+ }
62
+ ]
63
+ }
64
  }
65
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  },
67
+ "_source": [
68
+ "id", "titulo", "ementa_texto", "acordao_ata", "decisao_texto",
69
+ "documental_tese_texto", "orgao_julgador", "relator_processo_nome",
70
+ "julgamento_data", "processo_codigo_completo",
71
+ "inteiro_teor_url", "acompanhamento_processual_url", "dje_url"
72
+ ],
73
+ "highlight": {
74
+ "fields": {
75
+ "ementa_texto": {"matched_fields": ["ementa_texto.plural"], "type": "fvh", "fragment_size": 24000},
76
+ "acordao_ata": {"matched_fields": ["acordao_ata.plural"], "type": "fvh", "fragment_size": 600},
77
+ "decisao_texto": {"matched_fields": ["decisao_texto.plural"], "type": "fvh", "fragment_size": 1200},
78
+ "documental_tese_texto": {"matched_fields": ["documental_tese_texto.plural"], "type": "fvh", "fragment_size": 2000}
79
+ },
80
+ "pre_tags": ["<em>"],
81
+ "post_tags": ["</em>"],
82
+ "fragment_size": 300,
83
+ "number_of_fragments": 64,
84
+ "order": "score"
85
+ },
86
+ "size": size,
87
+ "from": (page - 1) * size,
88
+ "sort": [{"_score": "desc"}],
89
+ "track_total_hits": True
90
+ }
91
 
92
 
93
+ def get_fresh_token():
 
94
  global token_cache
95
  if token_cache["token"] and time.time() < token_cache["expires_at"]:
96
  return token_cache["token"]
97
+ logger.info("🔄 Obtendo token via Playwright...")
 
98
  try:
99
  with sync_playwright() as p:
100
+ browser = p.chromium.launch(headless=True, args=[
101
+ "--no-sandbox", "--disable-setuid-sandbox",
102
+ "--disable-dev-shm-usage", "--no-first-run"
103
+ ])
 
 
 
 
 
 
 
 
104
  context = browser.new_context(
105
  viewport={"width": 1920, "height": 1080},
106
  user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
107
  locale="pt-BR",
108
  timezone_id="America/Sao_Paulo",
109
+ extra_http_headers={"Accept-Language": "pt-BR,pt;q=0.9,en;q=0.8"}
 
 
 
 
 
 
110
  )
111
  page = context.new_page()
 
 
112
  page.goto("https://jurisprudencia.stf.jus.br/pages/search", wait_until="networkidle", timeout=45000)
113
+ page.wait_for_timeout(4000)
114
  page.mouse.move(300, 400)
115
  page.wait_for_timeout(1000)
 
 
 
116
  cookies = context.cookies()
117
+ token = next((c["value"] for c in cookies if c["name"] == "aws-waf-token"), None)
118
  browser.close()
 
119
  if token:
120
  token_cache["token"] = token
121
  token_cache["expires_at"] = time.time() + 3300
122
+ logger.info(f"✅ Token OK: {token[:20]}...")
123
  return token
124
+ logger.error("❌ Token não encontrado nos cookies")
125
  except Exception as e:
126
+ logger.error(f"❌ Playwright erro: {e}")
127
  return None
128
 
129
 
130
+ def do_search(payload):
131
+ """Executa POST na API e extrai hits/total"""
132
+ token = get_fresh_token()
133
  if not token:
134
+ return None, "Token WAF não obtido"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
  headers = HEADERS.copy()
136
  headers["Cookie"] = f"aws-waf-token={token}"
 
 
 
 
 
 
 
137
  try:
138
  resp = requests.post(URL_API, headers=headers, json=payload, verify=False, timeout=30)
139
+ logger.info(f"HTTP {resp.status_code}")
140
+ if resp.status_code == 403:
141
+ token_cache["token"] = None
142
+ return None, "Token expirado (403)"
143
  if resp.status_code != 200:
144
+ return None, f"HTTP {resp.status_code}: {resp.text[:300]}"
 
 
 
 
145
  data = resp.json()
146
+ # ⚠️ A API STF retorna {"result": {"hits": {...}}}
147
+ hits_root = data.get("result", data)
148
+ hits = hits_root.get("hits", {})
149
+ return {"hits": hits.get("hits", []), "total": hits.get("total", {}).get("value", 0)}, None
150
  except Exception as e:
151
+ return None, str(e)
 
152
 
153
 
154
+ def format_results(raw, query):
155
+ hits = raw.get("hits", [])
156
  results = []
 
157
  for hit in hits:
158
  source = hit.get("_source", {})
159
  hl = hit.get("highlight", {})
160
 
161
+ # Ementa com highlight > fallback raw
162
+ ementa = (
163
+ hl.get("ementa_texto", [None])[0] or
164
+ hl.get("documental_tese_texto", [None])[0] or
165
+ hl.get("acordao_ata", [None])[0] or
166
+ hl.get("decisao_texto", [None])[0] or
167
+ source.get("ementa_texto") or
168
+ source.get("documental_tese_texto") or
169
+ source.get("acordao_ata") or
170
+ source.get("decisao_texto") or ""
171
+ )
172
+ if len(ementa) > 800:
173
+ ementa = ementa[:800] + "..."
174
+
175
+ url_doc = (
176
+ source.get("inteiro_teor_url") or
177
+ source.get("acompanhamento_processual_url") or
178
+ source.get("dje_url")
179
+ )
180
+
181
+ data_j = (source.get("julgamento_data") or "")[:10]
182
+ citacao = f"({source.get('orgao_julgador','STF')} - {source.get('processo_codigo_completo','')} - Rel: {source.get('relator_processo_nome','N/I')} - {data_j})"
183
 
184
  results.append({
185
  "id": source.get("id"),
 
192
  "ementa": ementa.strip(),
193
  "citacao": citacao.strip()
194
  })
195
+ return results
 
 
 
 
 
 
 
 
196
 
197
 
198
  @app.route("/busca")
199
  def busca():
200
  query = request.args.get("q", "").strip()
201
  page = max(1, int(request.args.get("page", 1)))
202
+ size = min(int(request.args.get("size", 20)), 100)
203
 
204
  if not query:
205
  return jsonify({"error": "Parâmetro 'q' é obrigatório"}), 400
206
 
207
+ payload = build_payload(query, page, size)
208
+ raw, err = do_search(payload)
209
+
210
+ if err:
211
+ return jsonify({"success": False, "error": err}), 500
212
+
213
+ return jsonify({
214
+ "success": True,
215
+ "query": query,
216
+ "total": raw["total"],
217
+ "page": page,
218
+ "size": size,
219
+ "results": format_results(raw, query)
220
+ })
221
 
222
 
223
  @app.route("/health")
224
  def health():
225
  return jsonify({
226
+ "status": "ok",
227
  "token_ok": bool(token_cache["token"]),
228
+ "token_expires_in": max(0, token_cache["expires_at"] - time.time())
229
  })
230
 
231