juscraper 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. juscraper/__init__.py +44 -0
  2. juscraper/aggregators/__init__.py +16 -0
  3. juscraper/aggregators/datajud/__init__.py +6 -0
  4. juscraper/aggregators/datajud/client.py +289 -0
  5. juscraper/aggregators/datajud/download.py +88 -0
  6. juscraper/aggregators/datajud/mappings.py +117 -0
  7. juscraper/aggregators/datajud/parse.py +66 -0
  8. juscraper/aggregators/jusbr/__init__.py +7 -0
  9. juscraper/aggregators/jusbr/client.py +382 -0
  10. juscraper/aggregators/jusbr/download.py +178 -0
  11. juscraper/aggregators/jusbr/parse.py +104 -0
  12. juscraper/core/base.py +45 -0
  13. juscraper/core/download.py +1 -0
  14. juscraper/core/parse_utils.py +1 -0
  15. juscraper/courts/__init__.py +1 -0
  16. juscraper/courts/tjdft/__init__.py +0 -0
  17. juscraper/courts/tjdft/client.py +66 -0
  18. juscraper/courts/tjdft/download.py +43 -0
  19. juscraper/courts/tjdft/parse.py +10 -0
  20. juscraper/courts/tjpr/__init__.py +0 -0
  21. juscraper/courts/tjpr/client.py +72 -0
  22. juscraper/courts/tjpr/download.py +124 -0
  23. juscraper/courts/tjpr/parse.py +126 -0
  24. juscraper/courts/tjrs/__init__.py +1 -0
  25. juscraper/courts/tjrs/client.py +141 -0
  26. juscraper/courts/tjrs/download.py +88 -0
  27. juscraper/courts/tjrs/parse.py +79 -0
  28. juscraper/courts/tjsp/__init__.py +0 -0
  29. juscraper/courts/tjsp/acordao_download.py +32 -0
  30. juscraper/courts/tjsp/auth.py +0 -0
  31. juscraper/courts/tjsp/cjpg_download.py +120 -0
  32. juscraper/courts/tjsp/cjpg_parse.py +108 -0
  33. juscraper/courts/tjsp/cjsg_download.py +138 -0
  34. juscraper/courts/tjsp/cjsg_parse.py +146 -0
  35. juscraper/courts/tjsp/client.py +375 -0
  36. juscraper/courts/tjsp/cpopg_download.py +222 -0
  37. juscraper/courts/tjsp/cpopg_parse.py +308 -0
  38. juscraper/courts/tjsp/cposg_download.py +103 -0
  39. juscraper/courts/tjsp/cposg_parse.py +290 -0
  40. juscraper/tribunal_manager.py +28 -0
  41. juscraper/utils/__init__.py +34 -0
  42. juscraper/utils/cnj.py +35 -0
  43. juscraper/utils/logging_cfg.py +1 -0
  44. juscraper-0.1.0.dist-info/METADATA +232 -0
  45. juscraper-0.1.0.dist-info/RECORD +47 -0
  46. juscraper-0.1.0.dist-info/WHEEL +4 -0
  47. juscraper-0.1.0.dist-info/licenses/LICENSE +22 -0
@@ -0,0 +1,382 @@
1
+ """
2
+ Module client.py: Orchestrates the flow for JUSBR (user entry point).
3
+ Contains the JusbrScraper class for interaction with the API
4
+ from Platforma Digital do Poder Judiciario (PDPJ).
5
+ """
6
+ # Orchestrates the flow for JUSBR (user entry point)
7
+ # Will contain JusbrScraper class
8
+
9
+ import logging
10
+ import time
11
+ from typing import List, Optional, Union
12
+ import urllib
13
+ import browser_cookie3
14
+
15
+ import jwt
16
+ import pandas as pd
17
+ import requests
18
+ import numpy as np
19
+
20
+ from ...core.base import BaseScraper
21
+ from ...utils.cnj import clean_cnj
22
+ from .download import (
23
+ fetch_process_list,
24
+ fetch_process_details,
25
+ fetch_document_text,
26
+ USER_AGENT
27
+ )
28
+ from .parse import (
29
+ parse_process_list_response,
30
+ parse_process_details_response,
31
+ clean_document_text
32
+ )
33
+
34
+ logger = logging.getLogger(__name__)
35
+
36
+ class JusbrScraper(BaseScraper):
37
+ """
38
+ Raspador para o JusBR (consulta unificada da PDPJ-CNJ).
39
+ Este scraper interage com a API da Plataforma Digital do Poder Judiciario (PDPJ).
40
+ """
41
+ BASE_API_URL_V2 = "https://portaldeservicos.pdpj.jus.br/api/v2/processos/"
42
+ BASE_API_URL_V1_DOCS = (
43
+ "https://api-processo.data-lake.pdpj.jus.br/processo-api/api/v1/processos/"
44
+ )
45
+
46
+ def __init__(
47
+ self,
48
+ verbose: int = 0,
49
+ download_path: Optional[str] = None,
50
+ sleep_time: float = 0.5,
51
+ token: Optional[str] = None
52
+ ):
53
+ super().__init__("jusbr")
54
+ self.set_verbose(verbose)
55
+ self.set_download_path(download_path)
56
+ self.sleep_time = sleep_time
57
+ self.session = requests.Session()
58
+ self.token = token
59
+ if self.token:
60
+ self.session.headers.update({'authorization': f'Bearer {self.token}'})
61
+ self.session.headers.update({'user-agent': USER_AGENT})
62
+
63
+ def auth(self, token: str) -> bool:
64
+ """
65
+ Define o token JWT para autenticacao e o decodifica para verificacao.
66
+ """
67
+ try:
68
+ decoded = jwt.decode(token,
69
+ options={"verify_signature": False, "verify_aud": False},
70
+ algorithms=["RS256", "HS256", "ES256", "none"])
71
+ self.token = token
72
+ self.session.headers.update({'authorization': f'Bearer {self.token}'})
73
+ if self.verbose > 0:
74
+ logger.info("Token JWT definido e decodificado com sucesso!")
75
+ if self.verbose > 1:
76
+ for k, v in decoded.items():
77
+ logger.debug(" Token claim %s: %s", k, v)
78
+ return True
79
+ except jwt.ExpiredSignatureError as exc:
80
+ logger.error("Token JWT expirado.")
81
+ raise ValueError("Token JWT expirado.") from exc
82
+ except jwt.InvalidTokenError as exc:
83
+ logger.error("Token JWT inválido: %s", exc)
84
+ raise ValueError(f"Token JWT inválido: {exc}") from exc
85
+ return False
86
+
87
+ def auth_firefox(self):
88
+ """
89
+ Authentication via Firefox.
90
+ """
91
+ # url de autenticação
92
+ u = (
93
+ "https://sso.cloud.pje.jus.br/auth/realms/pje/protocol/"
94
+ "openid-connect/auth?client_id=portalexterno-frontend"
95
+ "&redirect_uri=https://portaldeservicos.pdpj.jus.br/home?state=meu_state"
96
+ "&session_state=1234&state=1234&response_mode=fragment&response_type=code"
97
+ "&scope=openid&nonce=1234&prompt=none"
98
+ )
99
+
100
+ # pega cookies do firefox
101
+ cookies = browser_cookie3.firefox(domain_name="sso.cloud.pje.jus.br")
102
+ session = requests.Session()
103
+ session.cookies.update(cookies)
104
+
105
+ # faz request para obter o token
106
+ resp = session.get(u, allow_redirects=False)
107
+ location_url = resp.headers.get("Location")
108
+ fragment = urllib.parse.urlparse(location_url).fragment
109
+ params = urllib.parse.parse_qs(fragment)
110
+ code = params.get("code", [None])[0]
111
+ token_url = "https://sso.cloud.pje.jus.br/auth/realms/pje/protocol/openid-connect/token"
112
+ data = {
113
+ "grant_type": "authorization_code",
114
+ "code": code,
115
+ "client_id": "portalexterno-frontend",
116
+ "redirect_uri": (
117
+ "https://portaldeservicos.pdpj.jus.br/home?state=meu_state&session_state=1234"
118
+ )
119
+ }
120
+ resp = session.post(token_url, data=data)
121
+ token = resp.json()["access_token"]
122
+ self.token = token
123
+ self.session.headers.update({'authorization': f'Bearer {self.token}'})
124
+ return True
125
+
126
+ def cpopg(self, id_cnj: Union[str, List[str]]) -> pd.DataFrame:
127
+ """
128
+ Consulta processos pelo numero CNJ (ou lista de numeros CNJ) via API nacional.
129
+ """
130
+ if not self.token:
131
+ raise RuntimeError("Autenticacao necessaria. Chame o metodo auth(token) primeiro.")
132
+
133
+ id_cnj_list = [id_cnj] if isinstance(id_cnj, str) else id_cnj
134
+ all_process_data = []
135
+
136
+ for cnj_input in id_cnj_list:
137
+ cnj_cleaned = clean_cnj(cnj_input)
138
+ if not cnj_cleaned:
139
+ logger.warning("CNJ inválido fornecido e não pôde ser limpo: %s", cnj_input)
140
+ all_process_data.append({
141
+ 'processo_pesquisado': cnj_input,
142
+ 'status_consulta': 'CNJ Invalido'
143
+ })
144
+ continue
145
+
146
+ logger.info("Consultando processo CNJ: %s", cnj_cleaned)
147
+
148
+ raw_list_data = fetch_process_list(self.session, cnj_cleaned, self.BASE_API_URL_V2)
149
+ processos_content = parse_process_list_response(raw_list_data)
150
+
151
+ if not processos_content:
152
+ logger.warning("Nenhum processo encontrado para o CNJ: %s", cnj_cleaned)
153
+ all_process_data.append({
154
+ 'processo_pesquisado': cnj_cleaned,
155
+ 'status_consulta': 'Nao encontrado na lista inicial'
156
+ })
157
+ time.sleep(self.sleep_time)
158
+ continue
159
+
160
+ for processo_item in processos_content:
161
+ numero_processo_oficial = processo_item.get('numeroProcesso')
162
+ if not numero_processo_oficial:
163
+ logger.warning(
164
+ "Item de processo sem 'numeroProcesso' para CNJ %s. Item: %s",
165
+ cnj_cleaned, processo_item
166
+ )
167
+ continue
168
+
169
+ raw_details_data = fetch_process_details(
170
+ self.session, numero_processo_oficial, self.BASE_API_URL_V2
171
+ )
172
+ parsed_details = parse_process_details_response(raw_details_data, cnj_cleaned)
173
+ if parsed_details:
174
+ all_process_data.append(parsed_details)
175
+ else:
176
+ all_process_data.append({
177
+ 'processo_pesquisado': cnj_cleaned,
178
+ 'numeroProcessoOficial': numero_processo_oficial,
179
+ 'status_consulta': 'Erro ao obter ou parsear detalhes'
180
+ })
181
+ time.sleep(self.sleep_time)
182
+
183
+ if not all_process_data:
184
+ return pd.DataFrame()
185
+ df_resultados = pd.DataFrame(all_process_data)
186
+ if 'processo_pesquisado' in df_resultados.columns:
187
+ cols1 = [col for col in df_resultados.columns if col != 'processo_pesquisado']
188
+ cols = ['processo_pesquisado'] + cols1
189
+ df_resultados = df_resultados[cols]
190
+ return df_resultados
191
+
192
+ def download_documents(self,
193
+ base_df: pd.DataFrame,
194
+ max_docs_per_process: Optional[int] = None) -> pd.DataFrame:
195
+ """
196
+ Downloads document texts for processes in base_df.
197
+ Iterates through processes in base_df, extracts document metadata from the
198
+ 'detalhes' column, fetches, and cleans document texts.
199
+ Returns a DataFrame where each row is a document.
200
+ """
201
+ if not self.token:
202
+ raise RuntimeError("Autenticação necessária. Chame o método auth(token) primeiro.")
203
+
204
+ all_docs_data = []
205
+ logger.info("Iniciando download de documentos para %d processos...", len(base_df))
206
+
207
+ for index, row in base_df.iterrows():
208
+ numero_processo_api = row.get('numeroProcesso') # Official CNJ for API calls
209
+ cnj_original_pesquisa = row.get('processo') # User's search term
210
+
211
+ if not numero_processo_api:
212
+ logger.warning(
213
+ "Linha %d (CNJ: %s) sem 'numeroProcesso' para download de documentos",
214
+ index, cnj_original_pesquisa
215
+ )
216
+ continue
217
+
218
+ detalhes = row.get('detalhes')
219
+ if not isinstance(detalhes, dict):
220
+ logger.warning(
221
+ "Campo 'detalhes' não é um dicionário para o"
222
+ "processo %s (linha %d). Tipo: %s. Pulando documentos.",
223
+ numero_processo_api, index, type(detalhes).__name__
224
+ )
225
+ continue
226
+
227
+ document_metadata_list = []
228
+ # Try common paths for document metadata list within 'detalhes'
229
+ if 'dadosBasicos' in detalhes and isinstance(detalhes['dadosBasicos'], dict):
230
+ document_metadata_list = detalhes['dadosBasicos'].get('documentos', [])
231
+
232
+ if (not document_metadata_list and
233
+ 'documentos' in detalhes and
234
+ isinstance(detalhes['documentos'], list)):
235
+ document_metadata_list = detalhes['documentos']
236
+
237
+ if (not document_metadata_list and
238
+ 'tramitacaoAtual' in detalhes and
239
+ isinstance(detalhes['tramitacaoAtual'], dict)):
240
+ document_metadata_list = detalhes['tramitacaoAtual'].get('documentos', [])
241
+ if isinstance(document_metadata_list, np.ndarray):
242
+ document_metadata_list = document_metadata_list.tolist()
243
+
244
+ # Ensure it's a list
245
+ if not isinstance(document_metadata_list, list):
246
+ logger.warning(
247
+ "Lista de metadados de documentos não encontrada ou não é uma lista "
248
+ "para o processo %s. Conteúdo de 'detalhes' (início): %s",
249
+ numero_processo_api, str(detalhes)[:200]
250
+ )
251
+ document_metadata_list = []
252
+
253
+ logger.info(
254
+ "Processo %s (pesquisado: %s): %d documentos encontrados na metadata.",
255
+ numero_processo_api, cnj_original_pesquisa, len(document_metadata_list)
256
+ )
257
+
258
+ docs_processed_count = 0
259
+ for doc_meta in document_metadata_list:
260
+ if not isinstance(doc_meta, dict):
261
+ logger.warning(
262
+ "Item na lista de documentos não é um"
263
+ "dicionário para o processo %s. Item: %s",
264
+ numero_processo_api, str(doc_meta)[:100]
265
+ )
266
+ continue
267
+
268
+ if (max_docs_per_process is not None and
269
+ docs_processed_count >= max_docs_per_process):
270
+ logger.info(
271
+ "Limite de %d documentos atingido para o processo %s.",
272
+ max_docs_per_process, numero_processo_api
273
+ )
274
+ break
275
+
276
+ # Para o download correto, sempre usar o UUID extraído
277
+ # de hrefTexto como identificador do documento na URL.
278
+ href_texto = doc_meta.get('hrefTexto')
279
+ id_doc_uuid = None
280
+ if href_texto and isinstance(href_texto, str) and '/documentos/' in href_texto:
281
+ try:
282
+ id_doc_uuid = href_texto.split('/documentos/')[1].split('/')[0]
283
+ except IndexError:
284
+ logger.warning(
285
+ "Não foi possível extrair UUID do hrefTexto: %s"
286
+ " para processo %s",
287
+ href_texto,
288
+ numero_processo_api
289
+ )
290
+ if not id_doc_uuid:
291
+ logger.warning(
292
+ "Documento sem UUID extraível de 'hrefTexto'"
293
+ "para o processo %s. Metadados: %s",
294
+ numero_processo_api, str(doc_meta)[:200]
295
+ )
296
+ continue
297
+ logger.debug(
298
+ "[JUSBR DEBUG] doc_meta para processo %s: %r",
299
+ numero_processo_api, doc_meta
300
+ )
301
+ logger.debug(
302
+ "Tentando baixar texto do documento UUID %s para processo %s.",
303
+ id_doc_uuid, numero_processo_api
304
+ )
305
+ # Usa CNJ limpo para a API de documentos
306
+ numero_processo_api_clean = clean_cnj(numero_processo_api)
307
+ raw_text = fetch_document_text(
308
+ self.session,
309
+ numero_processo_api_clean,
310
+ str(id_doc_uuid),
311
+ self.BASE_API_URL_V1_DOCS
312
+ )
313
+ cleaned_text = clean_document_text(raw_text)
314
+
315
+ if cleaned_text:
316
+ logger.debug(
317
+ "Sucesso ao baixar e limpar texto do doc UUID %s"
318
+ "(processo %s), tamanho limpo: %d",
319
+ id_doc_uuid,
320
+ numero_processo_api,
321
+ len(cleaned_text)
322
+ )
323
+ elif raw_text:
324
+ logger.debug(
325
+ "Texto baixado para doc UUID %s"
326
+ "(processo %s) mas resultou em None/vazio"
327
+ "após limpeza. Raw tamanho: %d",
328
+ id_doc_uuid,
329
+ numero_processo_api,
330
+ len(raw_text)
331
+ )
332
+ else:
333
+ logger.warning(
334
+ "Falha ao baixar texto do doc UUID %s"
335
+ "(processo %s), ou texto vazio.",
336
+ id_doc_uuid,
337
+ numero_processo_api
338
+ )
339
+
340
+ doc_data_row = {
341
+ 'numero_processo': numero_processo_api,
342
+ 'texto': cleaned_text,
343
+ '_raw_text_api': raw_text # Store raw text for inspection if needed
344
+ }
345
+ doc_data_row.update(doc_meta) # Add all metadata from the document item
346
+ all_docs_data.append(doc_data_row)
347
+ docs_processed_count += 1
348
+ time.sleep(self.sleep_time)
349
+
350
+ if not all_docs_data:
351
+ logger.info("Nenhum documento foi baixado ou processado.")
352
+ return pd.DataFrame()
353
+
354
+ df_docs = pd.DataFrame(all_docs_data)
355
+
356
+ # Define preferred columns based on original and common JusBR fields
357
+ # 'nome' from original might map to 'descricao' in API meta
358
+ preferred_columns = [
359
+ 'numero_processo', 'idDocumento', 'idCodex', 'sequencia', 'descricao', 'nome',
360
+ 'tipoDocumento', 'tipo', 'dataHoraJuntada', 'dataJuntada', 'nivelSigilo',
361
+ 'hrefTexto', 'hrefBinario', 'texto', '_raw_text_api'
362
+ ]
363
+ # Ensure preferred columns are present and in order, add others at the end
364
+ final_cols = []
365
+ existing_cols_set = set(df_docs.columns)
366
+ for col in preferred_columns:
367
+ if col in existing_cols_set:
368
+ final_cols.append(col)
369
+ existing_cols_set.remove(col) # Avoid duplication
370
+ final_cols.extend(sorted(list(existing_cols_set))) # Add remaining columns alphabetically
371
+
372
+ df_docs = df_docs[final_cols]
373
+ # Fill with None if some preferred columns were entirely missing from all docs
374
+ for col_pref in preferred_columns:
375
+ if col_pref not in df_docs.columns:
376
+ df_docs[col_pref] = None
377
+
378
+ logger.info(
379
+ "Download de documentos finalizado. Total de linhas de documentos: %d.",
380
+ len(df_docs)
381
+ )
382
+ return df_docs
@@ -0,0 +1,178 @@
1
+ """
2
+ Funções de download específicas para JUSBR
3
+ """
4
+
5
+ import logging
6
+ import time
7
+ from typing import Optional, Dict, Any
8
+ import requests
9
+ from ...utils.cnj import clean_cnj
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+ def request_with_retry(session, url, *, headers=None, timeout=15, max_retries=5, backoff_factor=1.0, **kwargs):
14
+ """
15
+ Faz uma requisição GET com retry exponencial para status 429 (Too Many Requests).
16
+ """
17
+ attempt = 0
18
+ wait = backoff_factor
19
+ while attempt <= max_retries:
20
+ try:
21
+ response = session.get(url, headers=headers, timeout=timeout, **kwargs)
22
+ if response.status_code == 429:
23
+ logger.warning(f"[429] Too Many Requests para {url}. Tentativa {attempt+1}/{max_retries}. Aguardando {wait}s...")
24
+ time.sleep(wait)
25
+ attempt += 1
26
+ wait = min(wait * 2, 32) # Limite de 32 segundos
27
+ continue
28
+ response.raise_for_status()
29
+ return response
30
+ except requests.Timeout:
31
+ logger.error(f"Timeout ao acessar {url} (tentativa {attempt+1}/{max_retries})")
32
+ time.sleep(wait)
33
+ attempt += 1
34
+ wait = min(wait * 2, 32)
35
+ except requests.RequestException as e:
36
+ logger.error(f"Erro de requisição em {url}: {e} (tentativa {attempt+1}/{max_retries})")
37
+ # Só faz retry se for 429, outros erros retornam direto
38
+ break
39
+ logger.error(f"Falha após {max_retries} tentativas para {url}")
40
+ return None
41
+
42
+ USER_AGENT = (
43
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
44
+ "AppleWebKit/537.36 (KHTML, like Gecko) "
45
+ "Chrome/135.0.0.0 Safari/537.36 Edg/135.0.0.0"
46
+ )
47
+
48
+ def fetch_process_list(
49
+ session: requests.Session,
50
+ cnj_cleaned: str,
51
+ base_api_url: str
52
+ ) -> Optional[Dict[str, Any]]:
53
+ """
54
+ Fetches the initial list of processes matching a CNJ.
55
+ Corresponds to the first API call in the original cpopg.
56
+ """
57
+ url = f"{base_api_url}?numeroProcesso={cnj_cleaned}"
58
+ logger.debug("Fetching process list from: %s", url)
59
+ try:
60
+ response = request_with_retry(session, url, timeout=15)
61
+ if response is None:
62
+ return None
63
+ return response.json()
64
+ except requests.Timeout:
65
+ logger.error(
66
+ "Timeout ao buscar lista de processos para %s em %s",
67
+ cnj_cleaned, url
68
+ )
69
+ return None
70
+ except requests.RequestException as e:
71
+ logger.error(
72
+ "Erro ao buscar lista de processos para %s em %s: %s",
73
+ cnj_cleaned, url, e
74
+ )
75
+ return None
76
+ except ValueError as e: # JSONDecodeError
77
+ logger.error(
78
+ "Erro ao decodificar JSON da lista de processos para %s em %s: %s",
79
+ cnj_cleaned, url, e
80
+ )
81
+ return None
82
+
83
+ def fetch_process_details(
84
+ session: requests.Session,
85
+ numero_processo_oficial: str,
86
+ base_api_url: str
87
+ ) -> Optional[Dict[str, Any]]:
88
+ """
89
+ Fetches detailed information for a specific official process number.
90
+ Corresponds to the second API call in the original cpopg.
91
+ """
92
+ url = f"{base_api_url}{numero_processo_oficial}"
93
+ logger.debug("Fetching process details from: %s", url)
94
+ try:
95
+ response = request_with_retry(session, url, timeout=15)
96
+ if response is None:
97
+ return None
98
+ return response.json()
99
+ except requests.Timeout:
100
+ logger.error(
101
+ "Timeout ao buscar detalhes do processo %s em %s",
102
+ numero_processo_oficial, url
103
+ )
104
+ return None
105
+ except requests.RequestException as e:
106
+ logger.error(
107
+ "Erro ao buscar detalhes do processo %s em %s: %s",
108
+ numero_processo_oficial, url, e
109
+ )
110
+ return None
111
+ except ValueError as e: # JSONDecodeError
112
+ logger.error(
113
+ "Erro ao decodificar JSON dos detalhes do processo %s em %s: %s",
114
+ numero_processo_oficial, url, e
115
+ )
116
+ return None
117
+
118
+ def fetch_document_text(
119
+ session: requests.Session,
120
+ numero_processo: str,
121
+ id_documento: str,
122
+ base_api_url_docs: str
123
+ ) -> Optional[str]:
124
+ """
125
+ Fetches the raw text of a specific document for a given process number.
126
+ """
127
+ # Recebe o CNJ limpo na URL, mas espera o CNJ original (com máscara) para a query string
128
+ numero_processo_url = clean_cnj(numero_processo)
129
+ numero_processo_param = numero_processo # original, pode estar com máscara
130
+ doc_url = (
131
+ f"{base_api_url_docs.rstrip('/')}/{numero_processo_url}/documentos/{id_documento}/texto"
132
+ f"?numeroProcesso={numero_processo_param}&idDocumento={id_documento}"
133
+ )
134
+
135
+ # Headers explícitos (garante todos)
136
+ request_headers = {
137
+ 'accept': '*/*',
138
+ 'authorization': session.headers.get('authorization', ''),
139
+ 'user-agent': USER_AGENT,
140
+ 'referer': 'https://portaldeservicos.pdpj.jus.br/consulta',
141
+ }
142
+
143
+ logger.debug("[JUSBR DEBUG] Baixando documento: URL=%s", doc_url)
144
+ logger.debug("[JUSBR DEBUG] Headers: %s", request_headers)
145
+
146
+ try:
147
+ response = request_with_retry(session, doc_url, headers=request_headers, timeout=30)
148
+ if response is None:
149
+ return None
150
+ try:
151
+ return response.content.decode('utf-8')
152
+ except UnicodeDecodeError:
153
+ logger.warning(
154
+ "UTF-8 decoding failed for document %s of process %s."
155
+ "Falling back to response.text (detected encoding: %s)",
156
+ id_documento, numero_processo, response.encoding
157
+ )
158
+ return response.text # Fallback to requests' auto-detected encoding
159
+ except requests.exceptions.HTTPError as e:
160
+ logger.error(
161
+ "HTTP Error fetching document %s for process %s (URL: %s): %s. Response: %s",
162
+ id_documento, numero_processo, doc_url, e, response.text[:200] if response else "N/A"
163
+ )
164
+ except requests.exceptions.RequestException as e:
165
+ logger.error(
166
+ "Request Exception fetching document %s for process %s (URL: %s): %s",
167
+ id_documento, numero_processo, doc_url, e
168
+ )
169
+ # Catching Exception as a last resort to avoid
170
+ # crashing on unexpected errors during scraping.
171
+ # All known exceptions are handled above;
172
+ # this is to log and continue in production environments.
173
+ except Exception as e:
174
+ logger.error(
175
+ "Unexpected error fetching document %s for process %s (URL: %s): %s",
176
+ id_documento, numero_processo, doc_url, e
177
+ )
178
+ return None
@@ -0,0 +1,104 @@
1
+ """
2
+ Module parse.py: Functions for parsing and cleaning results and documents from JUSBR.
3
+ Includes utilities for processing API responses and cleaning document texts.
4
+ """
5
+
6
+ # Functions for parsing and cleaning results and documents from JUSBR
7
+
8
+ import logging
9
+ from typing import Optional, Dict, Any, List, Union
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+ def parse_process_list_response(json_data: Optional[Dict[str, Any]]) -> List[Dict[str, Any]]:
14
+ """
15
+ Parses the JSON response from fetching the process list.
16
+ Returns the list of process items under the 'content' key.
17
+ """
18
+ if json_data is None:
19
+ return []
20
+ processos_content = json_data.get('content', [])
21
+ if not isinstance(processos_content, list):
22
+ logger.warning(
23
+ "Chave 'content' não é uma lista ou está ausente"
24
+ "na resposta da lista de processos: %s",
25
+ json_data
26
+ )
27
+ return []
28
+ return processos_content
29
+
30
+ def parse_process_details_response(json_data: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]],
31
+ cnj_searched: str) -> Optional[Dict[str, Any]]:
32
+ """
33
+ Parses the JSON response for process details.
34
+ Adds 'processo_pesquisado' to the data.
35
+ Handles cases where API returns a list with a single details object.
36
+ """
37
+ if json_data is None:
38
+ logger.warning(
39
+ "No JSON data received for process details for CNJ: %s", cnj_searched
40
+ )
41
+ return None
42
+
43
+ details_dict: Optional[Dict[str, Any]] = None
44
+
45
+ if isinstance(json_data, list):
46
+ if json_data: # Check if list is not empty
47
+ if isinstance(json_data[0], dict):
48
+ details_dict = json_data[0]
49
+ if len(json_data) > 1:
50
+ logger.warning(
51
+ "Process details API returned a list with %d"
52
+ "items for CNJ %s, using only the first.",
53
+ len(json_data), cnj_searched
54
+ )
55
+ else:
56
+ logger.error(
57
+ "Process details API returned a list, but the first item"
58
+ "is not a dictionary for CNJ %s. Data: %s",
59
+ cnj_searched, str(json_data[0])[:200] # Log snippet of problematic data
60
+ )
61
+ return None
62
+ else:
63
+ logger.warning("Process details API returned an empty list for CNJ: %s", cnj_searched)
64
+ return None
65
+ elif isinstance(json_data, dict):
66
+ details_dict = json_data
67
+
68
+ # Can add more sophisticated parsing here if needed, e.g., flattening nested structures
69
+ # For now, it mostly returns the JSON data, augmented with the searched CNJ.
70
+ parsed_data = {
71
+ 'processo': cnj_searched, # Matches screenshot column 'processo'
72
+ 'numeroProcesso': details_dict.get('numeroProcesso'), # Matches screenshot
73
+ 'idCodexTribunal': details_dict.get('idCodexTribunal'), # Matches screenshot
74
+ 'detalhes': details_dict # Full details dictionary as per screenshot
75
+ }
76
+ return parsed_data
77
+
78
+ def clean_document_text(text_content: Optional[str]) -> Optional[str]:
79
+ """
80
+ Cleans the raw text content of a document.
81
+ """
82
+ if not text_content:
83
+ return None
84
+ try:
85
+ # Comprehensive cleaning based on original code and common issues
86
+ cleaned_text = text_content.replace('\x00', '') # Remove null characters
87
+ cleaned_text = cleaned_text.replace('\x1a', '') # Remove SUB character
88
+ cleaned_text = cleaned_text.replace('\r\n', '\n').replace('\r', '\n') # Normalize newlines
89
+ cleaned_text = cleaned_text.replace('\xa0', ' ') # non-breaking space to regular space
90
+ cleaned_text = cleaned_text.replace('\u2028', '\n') # Line separator to newline
91
+ cleaned_text = cleaned_text.replace('\u2029', '\n') # Paragraph separator to nl
92
+ cleaned_text = cleaned_text.strip() # Strip leading/trailing whitespace
93
+ # Potentially add more specific cleaning if other problematic characters are found
94
+ return cleaned_text
95
+ except Exception as e:
96
+ # Catching Exception as a last resort to avoid crashing
97
+ # on unexpected text cleaning errors.
98
+ # All known issues should be handled above; this logs
99
+ # and continues for unpredictable encoding/corruption.
100
+ logger.error(
101
+ "Erro ao limpar texto do documento: %s. Conteúdo (início): %s",
102
+ e, str(text_content)[:100]
103
+ )
104
+ return None