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
juscraper/__init__.py ADDED
@@ -0,0 +1,44 @@
1
+ """
2
+ juscraper
3
+ ~~~~~~~~~
4
+ Public interface: jus.scraper(<sigla>, **kwargs)
5
+
6
+ The real implementation of each scraper is in:
7
+ - juscraper.courts.<sigla_tribunal>.client.TJ<sigla_tribunal>Scraper
8
+ - juscraper.aggregators.<sigla_agregador>.client.<Nome>Scraper
9
+ """
10
+ from importlib import import_module
11
+ from typing import Any
12
+ from importlib.metadata import version
13
+
14
+ _SCRAPERS: dict[str, str] = {
15
+ "tjsp": "juscraper.courts.tjsp.client:TJSPScraper",
16
+ "tjdft": "juscraper.courts.tjdft.client:TJDFTScraper",
17
+ "tjrs": "juscraper.courts.tjrs.client:TJRSScraper",
18
+ "tjpr": "juscraper.courts.tjpr.client:TJPRScraper",
19
+ "datajud": "juscraper.aggregators.datajud.client:DatajudScraper",
20
+ "jusbr": "juscraper.aggregators.jusbr.client:JusbrScraper",
21
+ }
22
+
23
+ def scraper(sigla: str, *args: Any, **kwargs: Any):
24
+ """
25
+ Factory that returns the correct scraper.
26
+
27
+ Examples
28
+ --------
29
+ >>> import juscraper as jus
30
+ >>> tjsp = jus.scraper("tjsp")
31
+ >>> jusbr = jus.scraper("jusbr")
32
+ """
33
+ sigla = sigla.lower()
34
+ if sigla not in _SCRAPERS:
35
+ raise ValueError(
36
+ f"Scraper '{sigla}' not supported. Available: {', '.join(_SCRAPERS)}"
37
+ )
38
+ path, cls_name = _SCRAPERS[sigla].split(":")
39
+ mod = import_module(path)
40
+ cls = getattr(mod, cls_name)
41
+ return cls(*args, **kwargs)
42
+
43
+ __version__ = version("juscraper")
44
+ __all__ = ["scraper"]
@@ -0,0 +1,16 @@
1
+ """
2
+ Aggregators
3
+ ~~~~~~~~~~~
4
+ Interface pública: jus.scrapers(<sigla>, **kwargs)
5
+
6
+ A implementação real de cada scraper mora em:
7
+ - juscraper.aggregators.<sigla_agregador>.client.<Nome>Scraper
8
+ """
9
+
10
+ from .datajud import DatajudScraper
11
+ from .jusbr import JusbrScraper
12
+
13
+ __all__ = [
14
+ "DatajudScraper",
15
+ "JusbrScraper",
16
+ ]
@@ -0,0 +1,6 @@
1
+ """
2
+ Exports DatajudScraper for easier access
3
+ """
4
+ from .client import DatajudScraper
5
+
6
+ __all__ = ["DatajudScraper"]
@@ -0,0 +1,289 @@
1
+ """
2
+ Orchestrates the flow for DATAJUD (user entry point) - API BASED
3
+ """
4
+ import os
5
+ import tempfile
6
+ from typing import Optional, Dict, List, Union, Any
7
+ from collections import defaultdict
8
+ import logging
9
+ import time
10
+ import requests
11
+ import pandas as pd
12
+ from tqdm.auto import tqdm
13
+
14
+ from ...core.base import BaseScraper
15
+ from ...utils.cnj import clean_cnj # Assuming this utility exists and is relevant
16
+ # Import mappings for tribunal and justice aliases.
17
+ from .mappings import ID_JUSTICA_TRIBUNAL_TO_ALIAS, TRIBUNAL_TO_ALIAS
18
+
19
+ from .download import call_datajud_api # To be created for API calls
20
+ from .parse import parse_datajud_api_response # To be created for API response parsing
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+ class DatajudScraper(BaseScraper):
25
+ """Scraper for CNJ's Datajud API."""
26
+ DEFAULT_API_KEY = "cDZHYzlZa0JadVREZDJCendQbXY6SkJlTzNjLV9TRENyQk1RdnFKZGRQdw=="
27
+ BASE_API_URL = "https://api-publica.datajud.cnj.jus.br"
28
+
29
+ def __init__(
30
+ self,
31
+ api_key: Optional[str] = None,
32
+ verbose: int = 1,
33
+ download_path: Optional[str] = None, # For temporary files if needed
34
+ sleep_time: float = 0.5,
35
+ ):
36
+ super().__init__("DatajudAPI")
37
+ self.set_verbose(verbose)
38
+ # download_path for API responses if saved temporarily, or can be ignored if
39
+ # data is processed in memory
40
+ self.download_path = download_path or tempfile.mkdtemp(prefix="datajud_api_")
41
+ if not os.path.exists(self.download_path):
42
+ os.makedirs(self.download_path)
43
+ self.session = requests.Session()
44
+ self.api_key = api_key or self.DEFAULT_API_KEY
45
+ self.sleep_time = sleep_time
46
+ logger.info(
47
+ "DatajudScraper initialized. API Key: "
48
+ "{'Provided' if api_key else 'Default'}. Temp path: %s",
49
+ self.download_path
50
+ )
51
+
52
+ def listar_processos(
53
+ self,
54
+ numero_processo: Optional[Union[str, List[str]]] = None,
55
+ tribunal: Optional[str] = None, # Sigla, e.g., TJSP, TRF1
56
+ # justica: Optional[str] = "8", # This was in original, but tribunal alias seems more direct
57
+ ano_ajuizamento: Optional[int] = None,
58
+ classe: Optional[str] = None, # Codigo da classe
59
+ assuntos: Optional[List[str]] = None, # Lista de códigos de assuntos
60
+ mostrar_movs: bool = False,
61
+ paginas: Optional[range] = None, # For specific page range, else fetch all
62
+ tamanho_pagina: int = 1000 # Max allowed by API is often 1000 or 10000
63
+ ) -> pd.DataFrame:
64
+ """
65
+ Lists processes from Datajud via API, with support for multiple filters and pagination.
66
+ """
67
+ all_dfs = []
68
+ # Determine target aliases
69
+ target_aliases = []
70
+ if tribunal:
71
+ alias = TRIBUNAL_TO_ALIAS.get(tribunal.upper())
72
+ if alias:
73
+ target_aliases.append(alias)
74
+ else:
75
+ logger.error("Tribunal %s não encontrado nos mappings.", tribunal)
76
+ return pd.DataFrame()
77
+ elif numero_processo:
78
+ # Group by alias if multiple CNJs from different tribunals are provided
79
+ processos_por_alias = defaultdict(list)
80
+ if isinstance(numero_processo, str):
81
+ cnjs_to_query = [numero_processo]
82
+ else:
83
+ cnjs_to_query = numero_processo
84
+ for num_cnj in cnjs_to_query:
85
+ num_limpo = clean_cnj(num_cnj)
86
+ if len(num_limpo) == 20:
87
+ id_justica_cnj = num_limpo[13]
88
+ id_tribunal_cnj = num_limpo[14:16]
89
+ alias = ID_JUSTICA_TRIBUNAL_TO_ALIAS.get((id_justica_cnj, id_tribunal_cnj))
90
+ if alias:
91
+ processos_por_alias[alias].append(num_cnj)
92
+ else:
93
+ logger.warning("Não foi possível determinar alias para CNJ: %s", num_cnj)
94
+ else:
95
+ logger.warning("CNJ inválido: %s", num_cnj)
96
+ if not processos_por_alias:
97
+ logger.error("Nenhum CNJ válido para determinar tribunal/alias.")
98
+ return pd.DataFrame()
99
+ target_aliases = list(processos_por_alias.keys())
100
+ else:
101
+ # Potentially iterate all known aliases if no tribunal/CNJ specified - very broad!
102
+ # For now, require tribunal or numero_processo if not querying all.
103
+ # Or, could default to a list of all aliases from TRIBUNAL_TO_ALIAS.values()
104
+ logger.error("É necessário especificar 'tribunal' ou 'numero_processo'.")
105
+ return pd.DataFrame()
106
+
107
+ for alias_idx, alias_name in enumerate(target_aliases):
108
+ logger.info("Consultando: %s (%d/%d)", alias_name, alias_idx+1, len(target_aliases))
109
+ # If CNJs were grouped, use only the CNJs for this specific alias
110
+ if numero_processo and not tribunal:
111
+ current_cnjs_for_alias = processos_por_alias[alias_name]
112
+ else:
113
+ current_cnjs_for_alias = numero_processo
114
+ df_alias = self._listar_processos_por_alias(
115
+ alias=alias_name,
116
+ numero_processo=current_cnjs_for_alias,
117
+ ano_ajuizamento=ano_ajuizamento,
118
+ classe=classe,
119
+ assuntos=assuntos,
120
+ mostrar_movs=mostrar_movs,
121
+ paginas_range=paginas,
122
+ tamanho_pagina=tamanho_pagina
123
+ )
124
+ if not df_alias.empty:
125
+ all_dfs.append(df_alias)
126
+
127
+ if not all_dfs:
128
+ return pd.DataFrame()
129
+ return pd.concat(all_dfs, ignore_index=True)
130
+
131
+ def _listar_processos_por_alias(
132
+ self,
133
+ alias: str,
134
+ numero_processo: Optional[Union[str, List[str]]],
135
+ ano_ajuizamento: Optional[int],
136
+ classe: Optional[str],
137
+ assuntos: Optional[List[str]],
138
+ mostrar_movs: bool,
139
+ paginas_range: Optional[range],
140
+ tamanho_pagina: int,
141
+ ) -> pd.DataFrame:
142
+ """Helper to fetch and parse data for a single alias with pagination."""
143
+ dfs_alias = []
144
+ current_page = paginas_range.start if paginas_range else 1
145
+ end_page = paginas_range.stop if paginas_range else float('inf')
146
+ search_after_params = None # For deep pagination
147
+ sort_field = "id.keyword" # Use .keyword for sorting text fields
148
+
149
+ # Initialize tqdm progress bar
150
+ if paginas_range:
151
+ total_pages_to_fetch = paginas_range.stop - paginas_range.start
152
+ # Disable pbar if no pages are to be fetched based on range
153
+ pbar_disabled = total_pages_to_fetch <= 0
154
+ pbar = tqdm(
155
+ total=total_pages_to_fetch,
156
+ desc=f"Paginando {alias}",
157
+ unit=" página",
158
+ disable=pbar_disabled
159
+ )
160
+ else:
161
+ # If paginas_range is None, total is unknown
162
+ pbar = tqdm(desc=f"Paginando {alias}", unit=" página")
163
+
164
+ try:
165
+ while current_page < end_page:
166
+ logger.info("Fetching page %d for alias %s...", current_page, alias)
167
+ # Construct query payload (Elasticsearch DSL)
168
+ must_conditions = []
169
+ if numero_processo:
170
+ if isinstance(numero_processo, str):
171
+ nproc = [numero_processo]
172
+ else:
173
+ nproc = numero_processo
174
+ must_conditions.append({
175
+ "terms": {
176
+ "numeroProcesso": nproc
177
+ }
178
+ })
179
+ if ano_ajuizamento:
180
+ must_conditions.append({
181
+ "range": {
182
+ "dataAjuizamento": {
183
+ "gte": f"{ano_ajuizamento}-01-01",
184
+ "lte": f"{ano_ajuizamento}-12-31"
185
+ }
186
+ }
187
+ })
188
+ if classe:
189
+ must_conditions.append({
190
+ "match": {
191
+ "classe.codigo": str(classe)
192
+ }
193
+ })
194
+ if assuntos:
195
+ must_conditions.append({
196
+ "terms": {
197
+ "assuntos.codigo": assuntos
198
+ }
199
+ })
200
+
201
+ if must_conditions:
202
+ query_values = {"bool": {"must": must_conditions}}
203
+ else:
204
+ query_values = {"match_all": {}}
205
+
206
+ query_payload: Dict[str, Any] = {
207
+ "query": query_values,
208
+ "size": tamanho_pagina
209
+ }
210
+
211
+ # Handle pagination: search_after is preferred for deep pagination
212
+ # The original _download_datajud used 'from', which is inefficient for deep pages
213
+ # DataJud API supports search_after. Requires a sort field.
214
+ query_payload["sort"] = [{sort_field: "asc"}] # Example sort
215
+ if search_after_params:
216
+ query_payload["search_after"] = search_after_params
217
+ else:
218
+ # For the first page if not using search_after from the start,
219
+ # or if API doesn't fully support it
220
+ # query_payload["from"] = (current_page - 1) * tamanho_pagina
221
+ # However, if we commit to search_after, 'from' is not used.
222
+ pass # First page, no search_after yet unless seeded
223
+
224
+ if not mostrar_movs:
225
+ query_payload["_source"] = {"excludes": ["movimentacoes", "movimentos"]}
226
+ else:
227
+ query_payload["_source"] = True
228
+ api_response_json = call_datajud_api(
229
+ base_url=self.BASE_API_URL,
230
+ alias=alias,
231
+ api_key=self.api_key,
232
+ session=self.session,
233
+ query_payload=query_payload,
234
+ verbose=self.verbose > 1 # Pass verbose flag for more detailed logging
235
+ )
236
+
237
+ if api_response_json is None:
238
+ logger.error(
239
+ "Failed to get API response for alias %s, page %d."
240
+ "Stopping.",
241
+ alias,
242
+ current_page
243
+ )
244
+ break
245
+
246
+ df_page = parse_datajud_api_response(api_response_json, mostrar_movs)
247
+ if df_page.empty:
248
+ logger.info(
249
+ "No more results for alias %s on page %d (or parsing failed).",
250
+ alias,
251
+ current_page
252
+ )
253
+ break
254
+ dfs_alias.append(df_page)
255
+ pbar.update(1) # Update progress bar
256
+
257
+ # For search_after pagination: extract the sort values of the last hit
258
+ # This part depends on the exact structure of api_response_json
259
+ # Assuming api_response_json is a dict parsed from the JSON string
260
+ hits = api_response_json.get("hits", {}).get("hits", [])
261
+ if not hits or len(hits) < tamanho_pagina:
262
+ logger.info(
263
+ "Last page reached for alias %s (less than %d results or no hits).",
264
+ alias,
265
+ tamanho_pagina
266
+ )
267
+ break
268
+ last_hit = hits[-1]
269
+ search_after_params = last_hit.get("sort")
270
+ if search_after_params is None:
271
+ logger.warning(
272
+ "Sort parameters for 'search_after' not found in last hit."
273
+ "Cannot continue deep pagination."
274
+ )
275
+ break # Fallback or stop if search_after cannot be determined
276
+
277
+ if paginas_range is None: # if fetching all, continue
278
+ current_page += 1
279
+ elif current_page < paginas_range.stop -1: # if in specified range, continue
280
+ current_page +=1
281
+ else: # reached end of specified range
282
+ break
283
+ time.sleep(self.sleep_time) # Respect sleep time
284
+ finally:
285
+ pbar.close() # Ensure progress bar is closed
286
+
287
+ if not dfs_alias:
288
+ return pd.DataFrame()
289
+ return pd.concat(dfs_alias, ignore_index=True)
@@ -0,0 +1,88 @@
1
+ """
2
+ Functions for downloading specific data from the Datajud API.
3
+ """
4
+ from typing import Optional, Dict, Any
5
+ import logging
6
+ import requests
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+ def call_datajud_api(
11
+ base_url: str,
12
+ alias: str,
13
+ api_key: str,
14
+ session: requests.Session,
15
+ query_payload: Dict[str, Any],
16
+ verbose: bool = False,
17
+ timeout: int = 60 # seconds
18
+ ) -> Optional[Dict[str, Any]]:
19
+ """
20
+ Calls the Datajud API for a given alias with a specific query.
21
+
22
+ Args:
23
+ base_url (str): The base URL of Datajud API (e.g. https://api-publica.datajud.cnj.jus.br).
24
+ alias (str): The API alias for the specific tribunal/service (e.g. api_publica_tjsp).
25
+ api_key (str): The API key for authorization.
26
+ session (requests.Session): The requests session to use.
27
+ query_payload (Dict[str, Any]): The Elasticsearch query payload.
28
+ verbose (bool): If True, logs more details about the request.
29
+ timeout (int): Request timeout in seconds.
30
+
31
+ Returns:
32
+ Optional[Dict[str, Any]]: The JSON response from the API as a dictionary,
33
+ or None if the request fails or returns an error.
34
+ """
35
+ api_url = f"{base_url}/{alias}/_search"
36
+ headers = {
37
+ "Authorization": f"APIKey {api_key}",
38
+ "Content-Type": "application/json"
39
+ }
40
+
41
+ if verbose:
42
+ logger.info("Calling Datajud API: %s", api_url)
43
+ # Redact key in log for security
44
+ logger.debug(
45
+ "Headers: {'Authorization': 'APIKey [REDACTED]',"
46
+ "'Content-Type': 'application/json'}"
47
+ )
48
+ logger.debug("Payload: %s", query_payload)
49
+
50
+ try:
51
+ response = session.post(api_url, json=query_payload, headers=headers, timeout=timeout)
52
+ if verbose:
53
+ logger.debug("Response Status Code: %s", response.status_code)
54
+ # Optionally log more details, but be mindful of verbosity and sensitive data
55
+ # logger.debug(f"Response Headers: {response.headers}")
56
+ # logger.debug(f"Response Content (first 500 chars): {response.text[:500]}")
57
+
58
+ response.raise_for_status() # Raises HTTPError for bad responses (4XX or 5XX)
59
+ return response.json()
60
+
61
+ except requests.exceptions.HTTPError as e:
62
+ logger.error("HTTP Error calling Datajud API (%s): %s", api_url, e)
63
+ if e.response is not None:
64
+ logger.error("Response status: %s", e.response.status_code)
65
+ try:
66
+ logger.error("Response content: %s", e.response.text[:1000])
67
+ except Exception:
68
+ logger.error("Could not retrieve error response content.")
69
+ else:
70
+ logger.error("No response object available in HTTPError.")
71
+ return None
72
+ except requests.exceptions.Timeout:
73
+ logger.error("Timeout calling Datajud API (%s) after %d seconds.", api_url, timeout)
74
+ return None
75
+ except requests.exceptions.RequestException as e:
76
+ logger.error("Request failed for Datajud API (%s): %s", api_url, e)
77
+ return None
78
+ except ValueError as e: # Includes JSONDecodeError if response is not valid JSON
79
+ logger.error("Failed to decode JSON response from Datajud API (%s): %s", api_url, e)
80
+ # Try to log part of the response text if available and decoding failed
81
+ response_text_snippet = 'N/A'
82
+ if 'response' in locals() and hasattr(response, 'text'):
83
+ response_text_snippet = response.text[:500]
84
+ logger.error("Response text (first 500 chars): %s", response_text_snippet)
85
+ return None
86
+ except Exception as e:
87
+ logger.error("An unexpected error occurred calling Datajud API (%s): %s", api_url, e)
88
+ return None
@@ -0,0 +1,117 @@
1
+ """
2
+ Maps (id_justica, id_tribunal) from CNJ to Datajud API alias.
3
+ """
4
+
5
+ ID_JUSTICA_TRIBUNAL_TO_ALIAS = {
6
+ # Justiça Estadual (id_justica="8")
7
+ ("8", "01"): "api_publica_tjac", # TJAC
8
+ ("8", "02"): "api_publica_tjal", # TJAL
9
+ ("8", "03"): "api_publica_tjap", # TJAP
10
+ ("8", "04"): "api_publica_tjam", # TJAM
11
+ ("8", "05"): "api_publica_tjba", # TJBA
12
+ ("8", "06"): "api_publica_tjce", # TJCE
13
+ ("8", "07"): "api_publica_tjdft", # TJDFT
14
+ ("8", "08"): "api_publica_tjes", # TJES
15
+ ("8", "09"): "api_publica_tjgo", # TJGO
16
+ ("8", "10"): "api_publica_tjma", # TJMA
17
+ ("8", "11"): "api_publica_tjmg", # TJMG
18
+ ("8", "12"): "api_publica_tjms", # TJMS
19
+ ("8", "13"): "api_publica_tjmt", # TJMT
20
+ ("8", "14"): "api_publica_tjpa", # TJPA
21
+ ("8", "15"): "api_publica_tjpb", # TJPB
22
+ ("8", "16"): "api_publica_tjpr", # TJPR
23
+ ("8", "17"): "api_publica_tjpe", # TJPE
24
+ ("8", "18"): "api_publica_tjpi", # TJPI
25
+ ("8", "19"): "api_publica_tjrj", # TJRJ
26
+ ("8", "20"): "api_publica_tjrn", # TJRN
27
+ ("8", "21"): "api_publica_tjrs", # TJRS
28
+ ("8", "22"): "api_publica_tjro", # TJRO
29
+ ("8", "23"): "api_publica_tjrr", # TJRR
30
+ ("8", "24"): "api_publica_tjsc", # TJSC
31
+ ("8", "25"): "api_publica_tjse", # TJSE
32
+ ("8", "26"): "api_publica_tjsp", # TJSP
33
+ ("8", "27"): "api_publica_tjto", # TJTO
34
+ # Justiça Federal (id_justica="4")
35
+ ("4", "01"): "api_publica_trf1", # TRF1
36
+ ("4", "02"): "api_publica_trf2", # TRF2
37
+ ("4", "03"): "api_publica_trf3", # TRF3
38
+ ("4", "04"): "api_publica_trf4", # TRF4
39
+ ("4", "05"): "api_publica_trf5", # TRF5
40
+ ("4", "06"): "api_publica_trf6", # TRF6
41
+ # Justiça do Trabalho (id_justica="5")
42
+ # Add TRT aliases as needed, e.g., ("5", "01"): "api_publica_trt1"
43
+ # Justiça Eleitoral (id_justica="6")
44
+ # Add TRE aliases as needed
45
+ # Justiça Militar da União (id_justica="7")
46
+ ("7", "00"): "api_publica_stm", # STM
47
+ # Justiça Militar Estadual (id_justica="9")
48
+ ("9", "11"): "api_publica_tjmmg", # TJMMG (MG)
49
+ ("9", "21"): "api_publica_tjmrs", # TJMRS (RS)
50
+ ("9", "25"): "api_publica_tjmsp", # TJMSP (SP)
51
+ # Conselhos (id_justica="3")
52
+ ("3", "00"): "api_publica_cnj", # CNJ
53
+ # Tribunais Superiores (id_justica="1", "2")
54
+ ("1", "00"): "api_publica_stf", # STF
55
+ ("2", "00"): "api_publica_stj", # STJ
56
+ }
57
+
58
+ # Maps Tribunal Acronym to Datajud API alias
59
+ TRIBUNAL_TO_ALIAS = {
60
+ # Supremo Tribunal Federal
61
+ "STF": "api_publica_stf",
62
+ # Conselho Nacional de Justiça
63
+ "CNJ": "api_publica_cnj",
64
+ # Superior Tribunal de Justiça
65
+ "STJ": "api_publica_stj",
66
+ # Justiça Federal
67
+ "TRF1": "api_publica_trf1",
68
+ "TRF2": "api_publica_trf2",
69
+ "TRF3": "api_publica_trf3",
70
+ "TRF4": "api_publica_trf4",
71
+ "TRF5": "api_publica_trf5",
72
+ "TRF6": "api_publica_trf6",
73
+ # Justiça Estadual
74
+ "TJAC": "api_publica_tjac",
75
+ "TJAL": "api_publica_tjal",
76
+ "TJAP": "api_publica_tjap",
77
+ "TJAM": "api_publica_tjam",
78
+ "TJBA": "api_publica_tjba",
79
+ "TJCE": "api_publica_tjce",
80
+ "TJDFT": "api_publica_tjdft",
81
+ "TJES": "api_publica_tjes",
82
+ "TJGO": "api_publica_tjgo",
83
+ "TJMA": "api_publica_tjma",
84
+ "TJMG": "api_publica_tjmg",
85
+ "TJMS": "api_publica_tjms",
86
+ "TJMT": "api_publica_tjmt",
87
+ "TJPA": "api_publica_tjpa",
88
+ "TJPB": "api_publica_tjpb",
89
+ "TJPR": "api_publica_tjpr",
90
+ "TJPE": "api_publica_tjpe",
91
+ "TJPI": "api_publica_tjpi",
92
+ "TJRJ": "api_publica_tjrj",
93
+ "TJRN": "api_publica_tjrn",
94
+ "TJRS": "api_publica_tjrs",
95
+ "TJRO": "api_publica_tjro",
96
+ "TJRR": "api_publica_tjrr",
97
+ "TJSC": "api_publica_tjsc",
98
+ "TJSP": "api_publica_tjsp",
99
+ "TJSE": "api_publica_tjse",
100
+ "TJTO": "api_publica_tjto",
101
+ # Justiça do Trabalho (Example, expand as needed)
102
+ "TST": "api_publica_tst",
103
+ "TRT1": "api_publica_trt1",
104
+ "TRT2": "api_publica_trt2",
105
+ # ... add all TRTs
106
+ # Justiça Eleitoral (Example, expand as needed)
107
+ "TSE": "api_publica_tse",
108
+ "TRE-AC": "api_publica_tre-ac",
109
+ "TRE-AL": "api_publica_tre-al",
110
+ # ... add all TREs
111
+ # Justiça Militar da União
112
+ "STM": "api_publica_stm",
113
+ # Justiça Militar Estadual
114
+ "TJMMG": "api_publica_tjmmg",
115
+ "TJMRS": "api_publica_tjmrs",
116
+ "TJMSP": "api_publica_tjmsp",
117
+ }
@@ -0,0 +1,66 @@
1
+ """
2
+ Functions for parsing DATAJUD API responses
3
+ """
4
+ import pandas as pd
5
+ from typing import Dict, Any, Optional
6
+ import logging
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+ def parse_datajud_api_response(
11
+ api_response_json: Optional[Dict[str, Any]],
12
+ mostrar_movs: bool = True
13
+ ) -> pd.DataFrame:
14
+ """
15
+ Parses the JSON response from the Datajud API into a pandas DataFrame.
16
+
17
+ Args:
18
+ api_response_json (Optional[Dict[str, Any]]): The parsed JSON response from the API
19
+ (output of call_datajud_api).
20
+ mostrar_movs (bool): If True, includes 'movimentacoes' in the DataFrame.
21
+ Otherwise, they are excluded.
22
+
23
+ Returns:
24
+ pd.DataFrame: A DataFrame containing the process data. Returns an empty
25
+ DataFrame if parsing fails or no data is found.
26
+ """
27
+ if api_response_json is None:
28
+ logger.warning("Received None for API response, cannot parse.")
29
+ return pd.DataFrame()
30
+
31
+ try:
32
+ hits = api_response_json.get("hits", {}).get("hits", [])
33
+ if not hits:
34
+ logger.info("No 'hits' found in API response.")
35
+ return pd.DataFrame()
36
+
37
+ processos = []
38
+ for hit in hits:
39
+ # _source contains the actual document data
40
+ processo_data = hit.get("_source")
41
+ if processo_data is None:
42
+ logger.warning(f"Hit found without '_source' field: {hit.get('_id', 'N/A')}")
43
+ continue
44
+
45
+ # Handle 'movimentacoes' based on mostrar_movs flag
46
+ if not mostrar_movs:
47
+ # Create a new dict excluding movimentacoes to avoid modifying original
48
+ processo_data_filtered = {
49
+ key: value for key, value in processo_data.items()
50
+ if key not in ["movimentacoes", "movimentos"] # Check for both common keys
51
+ }
52
+ processos.append(processo_data_filtered)
53
+ else:
54
+ processos.append(processo_data) # Include all fields
55
+
56
+ if not processos:
57
+ logger.info("No process data extracted from hits.")
58
+ return pd.DataFrame()
59
+
60
+ df = pd.DataFrame(processos)
61
+ return df
62
+
63
+ except Exception as e:
64
+ logger.error("Error parsing Datajud API JSON response: %s", e)
65
+ logger.debug("Problematic JSON (or part of it): %s", str(api_response_json)[:500])
66
+ return pd.DataFrame()
@@ -0,0 +1,7 @@
1
+
2
+ """
3
+ Exports JusbrScraper for easier access
4
+ """
5
+ from .client import JusbrScraper
6
+
7
+ __all__ = ["JusbrScraper"]