# PrazoBR — Brazilian Legal Deadlines & Obligations Extractor (`joaosbp/legal-deadlines-extractor-br`) Actor

Extrai prazos e obrigações de documentos jurídicos BR (ofício, portaria, edital, contrato, decisão, notificação, lei) em PDF, HTML ou texto. Juridiquês PT-BR: dias úteis, recorrência, fonte exata. Determinístico grátis + LLM BYOK. CSV + SUMMARY.md.

- **URL**: https://apify.com/joaosbp/legal-deadlines-extractor-br.md
- **Developed by:** [João Victor](https://apify.com/joaosbp) (community)
- **Categories:** Automation, Developer tools, AI
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

Pay per usage

This Actor is paid per platform usage. The Actor is free to use, and you only pay for the Apify platform usage, which gets cheaper the higher subscription plan you have.

Learn more: https://docs.apify.com/platform/actors/running/actors-in-store#pay-per-usage

## What's an Apify Actor?

Actors are web data automations that power AI and operations. They run on the Apify platform to scrape websites, process data, connect APIs, and automate workflows.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.
Actors are written with capital "A".

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.
The best way to integrate Actors is as follows.

- **AI agents and MCP clients** — the [Apify MCP server](https://docs.apify.com/integrations/mcp.md) at `https://mcp.apify.com` (remote, streamable HTTP, OAuth on first use).
- **Agentic workflows and local Actor development** — [Agent Skills](https://apify.com/.well-known/agent-skills/index.json) with the [Apify CLI](https://docs.apify.com/cli/docs.md): `npm install -g apify-cli`, then `apify login`.
- **JavaScript/TypeScript projects** — the official [JS/TS client](https://docs.apify.com/api/client/js/docs.md): `npm install apify-client`.
- **Python projects** — the official [Python client](https://docs.apify.com/api/client/python/docs.md): `pip install apify-client`.
- **Any other language** — the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).

# README

## PrazoBR — Brazilian Legal Deadlines & Obligations Extractor

> **Para brasileiros:** extraia prazos e obrigações de ofícios, portarias, editais, contratos, decisões e notificações — com a fonte exata de cada achado. Documentação completa em português abaixo.
>
> **For English speakers:** See [English documentation](#-english-documentation) below.

### 🇧🇷 Documentação em Português

Extrai **obrigações, pedidos e prazos** de documentos jurídicos e administrativos brasileiros — ofícios, portarias, editais, contratos, decisões, notificações, regulamentos, leis e decretos — em **PDF, página HTML pública ou texto colado**.

Não é mais um extrator genérico de PDF: o PrazoBR **interpreta juridiquês brasileiro** — "no prazo de cinco dias úteis", "a contar do recebimento", "sob pena de multa", "desde que aprovada a proposta" — e devolve uma relação estruturada e auditável, com **indicação exata da fonte** (trecho original + página).

### O que você recebe

Cada achado é um item estruturado:

```json
{
  "documentType": "oficio",
  "findingType": "OBLIGATION",
  "obligation": "apresentar o cronograma revisado",
  "responsibleParty": null,
  "recipient": null,
  "deadlineValue": 10,
  "deadlineUnit": "dias úteis",
  "deadlineDate": null,
  "recurrence": null,
  "triggerEvent": "recebimento do ofício",
  "suspensiveCondition": "aprovada a proposta técnica",
  "legalBasis": "art. 57",
  "nonComplianceConsequence": "aplicação de multa contratual",
  "documentDate": "2026-07-28",
  "sourcePage": 1,
  "sourceExcerpt": "Nos termos do art. 57 da Lei nº 14.133/2021, o cronograma revisado deverá ser apresentado no prazo de 10 dias úteis...",
  "confidence": 0.9,
  "requiresHumanReview": false,
  "extractionLayer": "HEURISTIC+LLM"
}
```

Além do dataset, o Actor gera na key-value store:

- **`SUMMARY.md`** — relatório legível com tabela de achados por documento
- **`obligations.csv`** — todos os achados em CSV pronto para planilha/CRM
- **`OUTPUT`** — contadores gerais (documentos, páginas, achados, revisões pendentes, erros)

### ⚖️ Escopo honesto (leia antes de usar)

- O PrazoBR **extrai** prazos e obrigações com a fonte. Ele **não calcula datas finais** — isso exige calendário oficial, feriados e regras de suspensão, que variam por órgão e processo.
- **Não é aconselhamento jurídico.** Confira sempre o trecho original indicado em `sourceExcerpt`.
- Documentos grandes (>50 páginas) são limitados por `maxPagesPerDocument`.
- Achados com `requiresHumanReview: true` tinham informação incompleta ou ambígua.

### Como funciona (2 camadas)

**Camada 1 — Determinística (sempre ativa, grátis, instantânea)**
Regex e heurísticas especializadas em jurídico PT-BR: prazos numéricos e **por extenso** ("cinco dias úteis", "3 (três) dias"), dias úteis × corridos, termo inicial ("a contar de", "contados da intimação"), datas absolutas, classificação obrigação/pedido/recomendação, fundamento legal, data e tipo do documento.

**Camada 2 — LLM opcional (BYOK)**
Com uma chave de API compatível com OpenAI (OpenRouter, OpenAI, Azure, proxies), o Actor refina cada achado: redação normalizada da obrigação em infinitivo, parte responsável, destinatário, revisão da classificação, condição suspensiva e consequência. **A chave é fornecida por você no input** — nunca é armazenada nem logada.

### Input

| Campo | Tipo | Obrigatório | Descrição |
|---|---|---|---|
| `urls` | array | — | URLs públicas de documentos (PDF, HTML, TXT) |
| `pastedText` | string | — | Texto colado diretamente (ofício, decisão, cláusula) |
| `maxPagesPerDocument` | int | — | Limite de páginas por PDF (padrão 50, máx 200) |
| `maxFindingsPerDocument` | int | — | Limite de achados por documento (padrão 50) |
| `llmApiKey` | string | — | Chave BYOK (OpenAI-compatível). Vazio = só camada determinística |
| `llmBaseUrl` | string | — | Endpoint OpenAI-compatível (padrão OpenRouter) |
| `llmModel` | string | — | Modelo (padrão: `google/gemini-2.5-flash`) |

`urls` e `pastedText` podem ser usados juntos; ao menos um é obrigatório.

### Casos de uso

- **Compliance / jurídico**: levantar obrigações e prazos de ofícios, notificações e decisões recebidas
- **Licitações**: extrair prazos de editais, atas e contratos administrativos
- **Gestão contratual**: auditar obrigações de contratos em PDF
- **Automação documental / agentes jurídicos**: alimentar pipelines com achados estruturados e citáveis

### Privacidade e segurança

- Documentos são processados **em memória** e descartados ao fim da execução — nada é persistido.
- O conteúdo integral dos documentos **nunca** vai para logs.
- Com a camada LLM ativa, os **trechos relevantes** (não o documento inteiro) são enviados ao endpoint configurado por você (BYOK). Sem chave, nada sai da execução.
- URLs passam por validação anti-SSRF (apenas HTTP(S) com destinos públicos) e limite de tamanho.

### Limitações conhecidas

- **Páginas escaneadas (imagem) não têm OCR** — são detectadas e reportadas em `ocrPagesSkipped`, mas seu conteúdo não é extraído.
- Classificação determinística é conservadora: documentos longos e fragmentados (leis extensas) tendem a gerar mais `DEADLINE_MENTION`; a camada LLM melhora a interpretação nesses casos.
- Idioma otimizado: **português jurídico brasileiro**.

### Custos

A camada determinística não tem custo externo. A camada LLM consome créditos do **seu** provedor (BYOK): ~1 requisição por documento com os trechos relevantes (tipicamente poucos milhares de tokens).

***

### 🇬🇧 English Documentation

PrazoBR extracts **obligations, requests and deadlines** from Brazilian legal and administrative documents — official letters (ofícios), ordinances, public tenders (editais), contracts, court decisions, notices, regulations, laws and decrees — from **PDF, public HTML pages, or pasted text**.

Not another generic PDF extractor: PrazoBR **understands Brazilian legal Portuguese** — "no prazo de cinco dias úteis", "a contar do recebimento", "sob pena de multa" — and returns a structured, auditable list with the **exact source** of every finding (original excerpt + page number).

#### What you get

Each finding is a structured item (see the JSON example above): document type, obligation in normalized wording, numeric deadline (business vs calendar days), absolute deadline date (`deadlineDate`), recurrence for periodic obligations, trigger event, suspensive condition, legal basis, consequence of non-compliance, source excerpt/page, confidence, and a human-review flag.

The key-value store also receives **`SUMMARY.md`** (readable report), **`obligations.csv`** (spreadsheet-ready), and **`OUTPUT`** (run counters).

#### How it works (2 layers)

1. **Deterministic layer (always on, free, instant):** regex and heuristics specialized in Brazilian legal Portuguese — numeric and spelled-out deadlines ("cinco dias úteis"), business vs calendar days, trigger events, absolute dates, obligation/request/recommendation classification, legal basis, document type and date.
2. **Optional LLM layer (BYOK):** with any OpenAI-compatible API key (OpenRouter, OpenAI, Azure), each finding is refined — normalized obligation wording, responsible party, recipient. Your key is passed in the input, never stored or logged.

#### Honest scope

- PrazoBR **extracts** deadlines with their source. It does **not compute final due dates** — that requires official calendars, holidays and procedural rules.
- **Not legal advice.** Always check the original excerpt in `sourceExcerpt`.
- Scanned (image-only) PDF pages have **no OCR** — they are detected and reported in `ocrPagesSkipped`.
- Optimized for **Brazilian legal Portuguese**.

***

### 🇧🇷 Suite de Dados Públicos BR / BR Public Data Suite

Este Actor faz parte de uma suite brasileira de dados públicos e jurídicos. Combine-os em pipelines:

- **LicitacoesBR** — radar de licitações PNCP (editais e vencedores): https://apify.com/joaosbp/licitacoes-pncp-br
- **CNPJ Lookup BR** — consulta CNPJ em lote com dados da Receita Federal: https://apify.com/joaosbp/cnpj-enrichment-lookup-br
- **CnpjDeltaBR** — monitor de mudanças cadastrais de CNPJs: https://apify.com/joaosbp/cnpj-delta-monitor-br
- **ComplianceBR** — screening de sanções CEIS/CNEP/CEPIM: https://apify.com/joaosbp/cnpj-sanctions-screening-br
- **Contact Scraper BR** — emails, WhatsApp + enriquecimento CNPJ: https://apify.com/joaosbp/website-contact-finder-br
- **PrazoBR** — extrator de prazos e obrigações jurídicas: https://apify.com/joaosbp/legal-deadlines-extractor-br
- **AutosTimeline BR** — cronologia de autos e pendências: https://apify.com/joaosbp/case-timeline-builder-br
- **PublicaBR** — monitor de publicações processuais (DataJud/CNJ): https://apify.com/joaosbp/publicacoes-processuais-br
- **EditalBR** — extrator de editais de concurso em PDF: https://apify.com/joaosbp/edital-extractor-br
- **Pricing Monitor BR** — monitor de páginas de preço SaaS: https://apify.com/joaosbp/competitor-pricing-page-monitor

**Pipeline sugerido:** LicitacoesBR encontra editais → CNPJ Lookup enriquece o vencedor → ComplianceBR verifica sanções → CnpjDeltaBR monitora mudanças cadastrais.

# Actor input Schema

## `urls` (type: `array`):

Public URLs of documents to analyze (PDF, HTML page, or plain text). Examples: ofício, portaria, edital, contrato, decisão, notificação, regulamento.

## `text` (type: `string`):

Paste the full text of a document to analyze directly, without providing a URL. Processed as a single document.

## `maxPagesPerDocument` (type: `integer`):

Safety limit of pages analyzed per document (PDFs). Extra pages are skipped and reported.

## `maxObligationsPerDocument` (type: `integer`):

Maximum number of obligation items returned per document.

## `llmApiKey` (type: `string`):

Your own API key for an OpenAI-compatible LLM endpoint (OpenRouter, OpenAI, etc.). When provided, an interpretation layer classifies each finding (obligation vs request vs recommendation), extracts responsible parties, consequences, and legal basis. Without a key, only the deterministic extractor runs (free, no external calls). The key is never logged or stored.

## `llmBaseUrl` (type: `string`):

OpenAI-compatible API base URL. Only used when an LLM API key is provided.

## `llmModel` (type: `string`):

Model identifier at the configured endpoint (e.g. google/gemini-2.5-flash, openai/gpt-4o-mini). Only used when an LLM API key is provided.

## Actor input object example

```json
{
  "urls": [
    "https://www.planalto.gov.br/ccivil_03/_ato2019-2022/2021/lei/l14133.htm"
  ],
  "maxPagesPerDocument": 40,
  "maxObligationsPerDocument": 50,
  "llmBaseUrl": "https://openrouter.ai/api/v1",
  "llmModel": "google/gemini-2.5-flash"
}
```

# Actor output Schema

## `obligationsCsv` (type: `string`):

UTF-8 CSV with one row per finding: document, type, obligation, deadline value/unit, trigger event, responsible, legal basis, consequence, page, excerpt, confidence, review flag.

## `datasetItems` (type: `string`):

Full structured findings with all fields, including source excerpts and confidence scores.

## `summary` (type: `string`):

Counts of documents processed, pages analyzed, findings by type, review-required items, errors, and whether the LLM layer was active.

## `executiveSummary` (type: `string`):

Human-readable SUMMARY.md with findings grouped by document, upcoming-deadline style listing, and review queue. Open this first.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "urls": [
        "https://www.planalto.gov.br/ccivil_03/_ato2019-2022/2021/lei/l14133.htm"
    ],
    "llmBaseUrl": "https://openrouter.ai/api/v1",
    "llmModel": "google/gemini-2.5-flash"
};

// Run the Actor and wait for it to finish
const run = await client.actor("joaosbp/legal-deadlines-extractor-br").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "urls": ["https://www.planalto.gov.br/ccivil_03/_ato2019-2022/2021/lei/l14133.htm"],
    "llmBaseUrl": "https://openrouter.ai/api/v1",
    "llmModel": "google/gemini-2.5-flash",
}

# Run the Actor and wait for it to finish
run = client.actor("joaosbp/legal-deadlines-extractor-br").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print("💾 Check your data here: https://console.apify.com/storage/datasets/" + run["defaultDatasetId"])
for item in client.dataset(run["defaultDatasetId"]).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "urls": [
    "https://www.planalto.gov.br/ccivil_03/_ato2019-2022/2021/lei/l14133.htm"
  ],
  "llmBaseUrl": "https://openrouter.ai/api/v1",
  "llmModel": "google/gemini-2.5-flash"
}' |
apify call joaosbp/legal-deadlines-extractor-br --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "command": "npx",
            "args": [
                "mcp-remote",
                "https://mcp.apify.com/?tools=joaosbp/legal-deadlines-extractor-br",
                "--header",
                "Authorization: Bearer <YOUR_API_TOKEN>"
            ]
        }
    }
}

```

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/acts/gHbtD7paaqkPHgSeG/builds/9eMsUq26RvUC3jHcG/openapi.json
