Metadata-Version: 2.4
Name: escavador-api
Version: 0.1.26
Summary: Python API to interact with Escavador endpoints
License: BSD-3-Clause License
License-File: LICENSE
Author: André Andrade Baceti
Author-email: a.baceti@murabei.com
Requires-Python: >=3.12
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Requires-Dist: loguru
Requires-Dist: pandas
Requires-Dist: python-slugify
Requires-Dist: requests
Requires-Dist: tenacity
Description-Content-Type: text/markdown

# escavador-api

A Python library for interacting with the Escavador API, providing access
to Brazilian legal process data, documents, and monitoring services.

## Objective and motivation

Python client for the Escavador HTTP API: Brazilian legal process data,
documents, AI summaries and monitoring services.

### Why this exists
Escavador exposes court and process endpoints over HTTP with auth tokens
and credit billing. This library wraps those calls with CNJ validation,
pagination, retries, and typed exceptions so Murabei (and other) services
do not reimplement the same client logic.

### How it is used
Import `EscavadorAPI` from `escavador_api.data`, pass an Escavador auth
token, and call methods for process lookup, documents, updates,
monitoring, related parties, and credits. Typical consumers are ETL
workers and internal tools that need structured process data.

### Scope
In scope: Escavador REST client behavior (requests, retries, error
mapping) and optional pandas transforms for process, involved, and
movement data.
Out of scope: Escavador account management, credit purchase, and
downstream storage or ETL orchestration beyond this library.

## Features

- **Process Information**: Retrieve detailed information about legal
  processes using CNJ numbers
- **Process Updates**: Get chronological update history of legal processes
- **Court Listing**: List available courts for searches
- **Document Access**: Download public and restricted process documents
- **AI Summaries**: Generate and retrieve AI-powered process summaries
- **Process Monitoring**: Set up monitoring for new processes or updates
  to existing processes
- **Related Processes**: List processes linked to a person or a company
  by CPF, CNPJ, or name
- **Credit Management**: Check API usage credits and limits
- **Court Data Refresh**: Request fresh data updates from court sources
- **Retry Logic**: GET, POST, DELETE, and PATCH retry connection
  errors and timeouts (5 attempts, 3 seconds apart). `get_binary`
  uses the same retry. Each failed attempt logs a warning before
  the next try
- **Pagination cap**: Paginated calls fetch the first page, then at
  most `ESCAVADOR_API__MAX_PAGES` further pages (default 200)
- **Process transforms**: `TransformProcessData` turns API process
  JSON into `process`, `process_by_court`, and `involved` DataFrames
  (court UF, role normalization, per-CNJ deduplication)
- **Movement transforms**: `TransformUpdateData` maps movement
  `tipo` to `update` or `publication` and can attach `file_path`

## Installation

### From Source

```bash
git clone https://github.com/Murabei-OpenSource-Codes/escavador-api.git
cd escavador-api
pip install .
```

## Requirements

- Python >= 3.12
- requests
- tenacity
- loguru
- pandas
- python-slugify

Declared in `pyproject.toml` (unpinned package names). **loguru**
logs pagination cap warnings and HTTP retry attempts.
**pandas** and
**python-slugify** support `escavador_api.transform` (role mapping).

## Configuration

Read when `escavador_api.config` is imported (the first import of
`EscavadorAPI`). Later environment changes apply only after the
process restarts.

- `ESCAVADOR_API__REQUEST_TIMEOUT`: request timeout in seconds.
  Defaults to 60.
- `ESCAVADOR_API__PROXY_URL`: proxy URL for HTTP and HTTPS. If unset,
  no proxy is used.
- `ESCAVADOR_API__MAX_PAGES`: extra pages after the first response
  on paginated calls. Defaults to 200. The first page is always
  requested. Hitting the cap logs a warning and keeps items already
  fetched.

`ESCAVADOR_API__REQUEST_TIMEOUT` and `ESCAVADOR_API__MAX_PAGES` must
be positive integers. A missing or blank value keeps the default.
Any other value raises `ValueError` at import.

Paginated HTTP routes use `fetch_paginated` internally.
`get_related_processes` returns `list[dict]` directly. These methods
return `list[dict]` after all pages are fetched (subject to
`ESCAVADOR_API__MAX_PAGES`): `get_process_updates`,
`get_documents_all`, `list_monitoring_new_process`,
`get_results_monitoring_new_process`, and
`list_monitoring_existing_process`. `get_documents_public` pages
the public-document route and returns those rows. Downloads run
when `download_files` is true. `save_files` writes them and sets
`file_path`; otherwise the bytes go on `file_content`.

The auth token is an argument of `EscavadorAPI`. The library does not
read it from the environment.

## Quick Start

```python
from escavador_api.data import EscavadorAPI

# Initialize with your API token
api = EscavadorAPI("your_auth_token_here")

# Check credit balance
balance = api.get_credit_balance()
print(balance)

# Get process information. The number must have 20 CNJ digits.
process_info = api.get_process_info("00000016620260000001")
print(process_info)
```

### Process transforms (ETL)

```python
from escavador_api.data import EscavadorAPI
from escavador_api.transform import TransformProcessData

api = EscavadorAPI("your_auth_token_here")
raw = api.get_related_processes(cpf_cnpj="00000000000")
tables = TransformProcessData.process_list(process_list=raw)
process_df = tables["process"]
involved_df = tables["involved"]
```

`process_list` returns `process` (one row per CNJ after deduplication),
`process_by_court` (one row per court grade), and `involved` (parties
with normalized roles and first-court polarity). An empty
`process_list` returns empty frames. `involved` still has the
first-court polarity columns.

`involved.normalized_role` is `judge`, `court`, `lawyer`, `party`,
`third_party`, `auxiliary`, `fiscal`, `representative`, `unknown`,
or `other`. `normalized_polarity` is `active`, `passive`, `neutral`,
or `other`. A source type with no mapping becomes `other` / `other`.

`escavador_api.singletons.transform_process_party_role` applies the
default map inside `process`. `set_custom_mapping` replaces
`TransformPartyRole.ROLE_MAPPING_DEFAULT` for later calls. The two
lists are not merged. When the same slug appears twice in a mapping
list, the later entry wins.

Invalid `numero_cnj` values in transform input raise
`EscavadorAPIInvalidDocumentException` from `process_list` and
`process`.

### Movement transforms

```python
from escavador_api.transform import TransformUpdateData

frame = TransformUpdateData.merge_documents(
    updates=updates, documents=documents)
```

`updates` is the list from `get_process_updates`. `documents` is
the list from `get_documents_public` when files were saved.
`andamento` becomes `update` and `publicacao` becomes
`publication`. Any other `tipo` is skipped. `file_path` is null
when no saved document points at that movement.

## API Reference

### Initialization

```python
EscavadorAPI(escavador_auth_token: str)
```

**Parameters:**
- `escavador_auth_token` (str): Your Escavador API authentication token

### Core Methods

Methods marked **(paid)** consume Escavador API credits.

#### Credit Management

```python
get_credit_balance() -> dict
```
Returns current credit balance and monthly limits.

#### Courts

```python
get_courts() -> dict
```
List all available courts for searches in Escavador.

#### Process Information

```python
get_process_info(process_number: str) -> dict
```
Retrieve basic process information. **(paid)**

**Parameters:**
- `process_number` (str): CNJ process number (20 digits, punctuation
  optional)

```python
get_process_updates(process_number: str) -> list[dict]
```
Returns one dictionary per process update. **(paid)**

```python
get_documents_public(
    process_number: str,
    download_files: bool = False,
    folder_path: str = None,
    save_files: bool = False,
) -> list[dict]
```
Pages `GET .../documentos-publicos`. **(paid)** Both flags false
returns the document rows. `download_files` true and `save_files`
false sets `file_content`. Both true writes each file and sets
`file_path`. A later failure keeps that exception and adds
`file_key` plus `written_paths` for files already saved.
`save_files` without `download_files` raises.

```python
get_documents_all(process_number: str) -> list[dict]
```
Returns one dictionary per document from `GET .../autos`, including
restricted documents when the caller is authorized. **(paid)**

#### Process Updates

```python
request_process_update_public(process_number: str) -> dict
```
Request update of public process information with JSON
`{"documentos_publicos": 1}`. **(paid)** HTTP 422
`UNPROCESSABLE_ENTITY` for a duplicate request raises
`EscavadorAPIProcessUpdateAlreadyRequestedException`.

```python
request_process_update_full(
    process_number: str,
    auth_username: str | None = None,
    auth_password: str | None = None,
    certificate_id: int | None = None,
    use_certificate: bool = False,
) -> dict
```
Request full update including restricted documents. **(paid)**
Duplicate-update HTTP 422 is remapped the same way as
`request_process_update_public`.

```python
get_process_update_status(process_number: str) -> dict
```
Check the status of an update request. **(paid)**

#### Document Downloads

```python
download_file(
    process_number: str,
    file_key: str,
    folder_path: str = None,
    file_name: str = None,
    save_file: bool = False,
) -> bytes | str
```
Downloads one document from `GET .../documentos/{file_key}`.
**(paid)** When `save_file` is false, the method returns the bytes
and ignores `folder_path` and `file_name`. When `save_file` is
true, a missing directory defaults to `./` and a missing name
defaults to `{file_key}.pdf`, with slashes in the key replaced.
`file_key` is quoted in the URL. `file_name` must be a basename.
The return value is the joined path.

#### AI Summaries

```python
request_ai_summary(process_number: str) -> dict
```
Request generation of an AI summary. **(paid)**

```python
get_ai_summary_status(process_number: str) -> dict
```
Check AI summary generation status.

```python
get_ai_summary(process_number: str) -> dict
```
Retrieve the generated AI summary. **(paid)**

### Related processes

```python
get_related_processes(
    cpf_cnpj: str | None = None,
    nome: str | None = None,
    ordena_por: str = "data_inicio",
    ordem: str = "desc",
    limit: Literal[20, 50, 100] = 100,
    tribunais: list[str] | None = None,
    incluir_homonimos: bool | None = None,
    incluir_mesma_raiz_cnpj: bool | None = None,
    polo: Literal["ATIVO", "PASSIVO", "ADVOGADO", "OUTROS"] | None = None,
    status: Literal["ATIVO", "INATIVO"] | None = None,
    data_minima: str | None = None,
    data_maxima: str | None = None,
    assuntos_codigos_cnj: list[int] | None = None,
    classes_codigos_cnj: list[int] | None = None,
    materias_codigos_cnj: list[int] | None = None,
    valor_causa_minimo: float | None = None,
    valor_causa_maximo: float | None = None,
    envolvidos_relacionados: list[str] | None = None,
) -> list[dict]
```

List processes for a person or a company. `cpf_cnpj` or `nome` is
required. Other arguments are optional filters. Raises
`EscavadorAPIInvalidParametersException` when both identifiers are
missing.

### Monitoring

#### New Process Monitoring

```python
create_monitoring_new_process(
    keyword: str,
    keyword_variations: list[str] | None = None,
    aux_keywords: list[KeywordDict] | None = None,
    courts: list[str] | None = None,
) -> dict
```
Create monitoring for new processes matching criteria.

```python
list_monitoring_new_process() -> list[dict]
```
Returns one dictionary per new-process monitoring.

```python
get_monitoring_new_process(monitoring_id: int) -> dict
```
Get details of a specific monitoring.

```python
edit_monitoring_new_process(
    monitoring_id: int,
    keyword_variations: list[str] | None = None,
    aux_keywords: list[KeywordDict] | None = None,
    courts: list[str] | None = None,
) -> dict
```
Edit an existing monitoring.

```python
delete_monitoring_new_process(monitoring_id: int) -> bool
```
Delete a monitoring.

```python
get_results_monitoring_new_process(monitoring_id: int) -> list[dict]
```
Returns one dictionary per process found by the monitoring.

#### Existing Process Monitoring

```python
create_monitoring_existing_process(
    process_number: str,
    court: str | None = None,
    frequency: str | None = None,
) -> dict
```
Monitor updates to an existing process.

```python
list_monitoring_existing_process() -> list[dict]
```
Returns one dictionary per existing-process monitoring.

```python
get_monitoring_existing_process(monitoring_id: int) -> dict
```
Get monitoring details.

```python
delete_monitoring_existing_process(monitoring_id: int) -> bool
```
Delete monitoring.

## Error Handling

The library provides specific exception types:

- `EscavadorAPIException`: Base error. Carries `message` and `payload`.
- `EscavadorAPIAuthenticationError`: The auth token is empty, or HTTP 401.
- `EscavadorAPIInsufficientCreditsException`: HTTP 402.
- `EscavadorAPINotFoundException`: HTTP 404, or JSON code `NOT_FOUND`.
- `EscavadorAPIInvalidDocumentException`: The process number does not
  have exactly 20 digits, or JSON code `NUMERO_CNJ_INVALIDO`. That
  code does not also raise the generic HTTP 422 class.
- `EscavadorAPIInvalidParametersException`: A call is missing a required
  argument, HTTP 422, or JSON code `UNPROCESSABLE_ENTITY`.
- `EscavadorAPIProcessUpdateAlreadyRequestedException`: HTTP 422
  `UNPROCESSABLE_ENTITY` when a public or full update is already
  in progress (`request_process_update_public` and
  `request_process_update_full` only).
- `EscavadorAPIRateLimitException`: HTTP 429.
- `EscavadorAPIProblemAPIException`: A local check failed, such as
  inconsistent download flags or monitoring arguments. It is not the
  type raised for an HTTP error.
- `EscavadorAPIUnmappedErrorException`: The status or `code` matches
  no class. HTTP payloads include `request_error_code`.

## Retry Logic

`get`, `get_binary`, `post`, `delete`, and `patch` retry network
failures.

- **Attempts**: 5 (`stop_after_attempt`)
- **Delay**: 3 seconds between attempts
- **Retried errors**: `requests.ConnectionError` and `requests.Timeout`
- **Logging**: a loguru warning before each sleep (method name,
  exception type, attempt number)
- **Not retried**: Validation errors and HTTP error responses

## Process Number Format

Process numbers must follow the Brazilian CNJ
(Conselho Nacional de Justiça) format:

- 20 digits total
- Format: NNNNNNN-DD.AAAA.J.TR.OOOO

`validate_process_number` strips punctuation and requires 20 digits.
Escavador accepts or rejects the number on the server. Pass CNJ values
as strings when leading zeros matter.

## Authentication

To use the Escavador API, you need:

1. An Escavador account
2. An API authentication token
3. Sufficient credits for API calls

For restricted documents, additional authentication may be required
(username/password or digital certificate).

## Development

### Setup

```bash
# Install dependencies
pip install -e .

# Run tests
python -m unittest discover -s src/escavador_api/tests

# Build package
./build.sh
```

### Testing

Tests use `unittest` and call the live Escavador API. Set:

- `ESCAVADOR_AUTH_TOKEN`: API token passed into `EscavadorAPI`
- `TEST_PROCESS_NUMBER`: A 20-digit CNJ string for process tests
- `TEST_CPF_NUMBER`: A CPF for related-process tests

```bash
export ESCAVADOR_AUTH_TOKEN="your_token"
export TEST_PROCESS_NUMBER="process_number"
export TEST_CPF_NUMBER="cpf"
python -m unittest discover -s src/escavador_api/tests
```

## License

BSD 3-Clause License - see [LICENSE](LICENSE) file for details.

## Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests
5. Submit a pull request

## Support

For issues and questions:

- Check the [Escavador API documentation](https://api.escavador.com/)
- Open an issue on GitHub
- Contact Murabei Data Science at a.baceti@murabei.com

