Skip to content

ThomasMoreAI/legal-skills-open / br/litigation/skills/juriscan-brunobracaioli

juriscan-brunobracaioli

Verified

Análise forense de processos judiciais brasileiros. Extrai, classifica e cruza peças processuais, detecta contradições, calcula prazos CPC e gera relatórios de risco com exportação para Obsidian. Use quando mencionar: processo judicial, petição, sentença, acórdão, contradições, prazos, timeline, análise forense, Obsidian.

FileKindSize
.claude/agents/juriscan-advogado-autor.mdmarkdown4.3 KB
.claude/agents/juriscan-advogado-reu.mdmarkdown3.6 KB
.claude/agents/juriscan-auditor-processual.mdmarkdown7.0 KB
.claude/agents/juriscan-echo.mdmarkdown2.0 KB
.claude/agents/juriscan-parser.mdmarkdown4.7 KB
.claude/agents/juriscan-segmenter.mdmarkdown4.9 KB
.claude/agents/juriscan-sintetizador.mdmarkdown3.1 KB
.claude/agents/juriscan-verificador.mdmarkdown4.8 KB
.github/FUNDING.ymlconfig77 B
.github/workflows/ci.ymlconfig1.0 KB
.gitignoreother121 B
CHANGELOG.mdmarkdown20.6 KB
CLAUDE.mdmarkdown10.6 KB
LICENSEother1.0 KB
README.mdmarkdown16.9 KB
SKILL.mdskill md26.3 KB
assets/banner.svgother4.7 KB
docs/architecture.mdmarkdown10.3 KB
docs/index.htmlother4.3 KB
docs/operations.mdmarkdown6.7 KB
docs/subagent_contract.mdmarkdown6.0 KB
docs/subagents.mdmarkdown5.5 KB
install.shscript3.2 KB
pyproject.tomlmanifest272 B
references/agent_schemas/advogado_output.jsonconfig2.7 KB
references/agent_schemas/auditor_output.jsonconfig4.8 KB
references/agent_schemas/echo_output.jsonconfig666 B
references/agent_schemas/parser_output.jsonconfig4.4 KB
references/agent_schemas/recommendations_output.jsonconfig2.5 KB
references/agent_schemas/segmenter_output.jsonconfig2.9 KB
references/agent_schemas/sintetizador_output.jsonconfig2.7 KB
references/agent_schemas/verificador_output.jsonconfig2.3 KB
references/appellate_structure.mdmarkdown2.0 KB
references/binding_precedents.mdmarkdown2.2 KB
references/brazilian_legal_entities.mdmarkdown3.2 KB
references/chunk_analysis_schema.jsonconfig6.7 KB
references/cpc_prazos.jsonconfig4.4 KB
references/feriados_forenses.jsonconfig2.1 KB
references/output_schema.jsonconfig11.0 KB
references/output_schema_v2.jsonconfig11.0 KB
references/output_schema_v3.jsonconfig5.3 KB
references/piece_type_taxonomy.jsonconfig7.5 KB
references/prompt_templates.mdmarkdown11.8 KB
references/risk_scoring_rubric.mdmarkdown2.4 KB
references/whitelist_fontes.jsonconfig1.8 KB
requirements.txtmanifest250 B
scripts/__init__.pyscript0 B
scripts/agent_io.pyscript12.2 KB
scripts/analyzed_init.pyscript3.3 KB
scripts/audit.pyscript4.8 KB
scripts/cleanup_audit.pyscript2.0 KB
scripts/confidence_rules.pyscript6.4 KB
scripts/content_quality_check.pyscript11.1 KB
scripts/enrich_deterministic.pyscript10.3 KB
scripts/extract_and_chunk.pyscript14.3 KB
scripts/finalize.pyscript10.2 KB
scripts/finalize_legacy.pyscript7.4 KB
scripts/generate_report.pyscript29.8 KB
scripts/instance_tracker.pyscript6.7 KB
scripts/integrity_check.pyscript11.0 KB
scripts/integrity_gate.pyscript4.6 KB
scripts/legacy/__init__.pyscript0 B
scripts/legacy/contradiction_report.pyscript11.9 KB
scripts/legacy/risk_scorer.pyscript10.2 KB
scripts/merge_chunk_analysis.pyscript14.8 KB
scripts/migrate_v2_to_v3.pyscript3.1 KB
scripts/obsidian_export.pyscript28.0 KB
scripts/persist_chunks.pyscript6.2 KB
scripts/prazo_calculator.pyscript14.2 KB
scripts/report_metrics.pyscript8.4 KB
scripts/schema_validator.pyscript5.2 KB
scripts/utils/__init__.pyscript0 B
scripts/utils/cnj.pyscript4.4 KB
scripts/utils/dates.pyscript7.8 KB
scripts/utils/filenames.pyscript2.6 KB
scripts/utils/monetary.pyscript5.2 KB
tests/__init__.pyscript0 B
tests/conftest.pyscript1.1 KB
tests/fixtures/agent_io/echo_invalid_missing_field.jsonconfig45 B
tests/fixtures/agent_io/echo_invalid_wrong_const.jsonconfig70 B
tests/fixtures/agent_io/echo_valid.jsonconfig103 B
tests/fixtures/agent_io/segmenter_valid.jsonconfig359 B
tests/fixtures/sample_analyzed.jsonconfig10.0 KB
tests/fixtures/sample_analyzed_with_prazos.jsonconfig470 B
tests/fixtures/sample_chunk_acordao.txtmarkdown3.4 KB
tests/fixtures/sample_chunk_peticao.txtmarkdown3.4 KB
tests/fixtures/sample_chunk_sentenca.txtmarkdown2.9 KB
tests/fixtures/sample_index.jsonconfig1.6 KB
tests/golden/_pdf_builder.pyscript6.1 KB
tests/golden/processo_01_sintetico_simples/expected_invariants.jsonconfig993 B
tests/golden/processo_01_sintetico_simples/source.txtmarkdown3.3 KB
tests/golden/processo_02_sintetico_art942/expected_art_942.jsonconfig898 B
tests/golden/processo_02_sintetico_art942/expected_invariants.jsonconfig1.3 KB
tests/golden/processo_02_sintetico_art942/source.txtmarkdown7.8 KB
tests/test_agent_io.pyscript4.4 KB
tests/test_analyzed_init.pyscript5.6 KB
tests/test_audit.pyscript4.4 KB
tests/test_cnj.pyscript2.9 KB
tests/test_confidence_rules.pyscript4.8 KB
tests/test_content_quality_check.pyscript14.5 KB
tests/test_contradiction_report.pyscript3.5 KB
tests/test_dates.pyscript5.0 KB
tests/test_enrich_deterministic.pyscript6.3 KB
tests/test_filenames.pyscript2.1 KB
tests/test_finalize.pyscript5.8 KB
tests/test_finalize_legacy.pyscript6.5 KB
tests/test_generate_report.pyscript24.0 KB
tests/test_golden_regression.pyscript6.3 KB
tests/test_instance_tracker.pyscript4.2 KB
tests/test_integrity_check.pyscript4.8 KB
tests/test_integrity_gate.pyscript3.6 KB
tests/test_merge_chunk_analysis.pyscript20.9 KB
tests/test_migrate_v2_to_v3.pyscript4.3 KB
tests/test_monetary.pyscript3.4 KB
tests/test_obsidian_export_v3.pyscript6.9 KB
tests/test_persist_chunks.pyscript6.1 KB
tests/test_prazo_calculator.pyscript14.1 KB
tests/test_report_metrics.pyscript5.3 KB
tests/test_risk_scorer.pyscript5.7 KB
tests/test_whitelist_enforcement.pyscript6.1 KB

scripts/integrity_check.py

View on GitHub
#!/usr/bin/env python3
"""
integrity_check.py — Document integrity and OCR quality verification.

Detects:
- OCR quality issues (garbled text, encoding anomalies)
- Metadata anomalies (missing pieces, date inversions, duplicate labels)
- Page gaps (missing pages based on markers)

Usage:
    python3 integrity_check.py --input ./analysis/
"""

from __future__ import annotations

import argparse
import json
import os
import re
import sys
from pathlib import Path

# Add utils to path
sys.path.insert(0, os.path.dirname(__file__))
from utils.dates import extract_all_dates, validate_chronology

# Portuguese dictionary words for OCR confidence (common legal terms)
_LEGAL_TERMS = {
    'processo', 'autor', 'réu', 'juiz', 'vara', 'sentença', 'acórdão',
    'petição', 'contestação', 'réplica', 'recurso', 'apelação', 'agravo',
    'decisão', 'despacho', 'certidão', 'mandado', 'intimação', 'citação',
    'direito', 'lei', 'artigo', 'código', 'tribunal', 'justiça', 'foro',
    'comarca', 'advogado', 'procurador', 'ministério', 'público', 'federal',
    'estadual', 'civil', 'penal', 'trabalho', 'consumidor', 'constituição',
    'danos', 'morais', 'materiais', 'indenização', 'condenação', 'honorários',
    'custas', 'valor', 'causa', 'pedido', 'prova', 'testemunha', 'perito',
    'laudo', 'parecer', 'audiência', 'julgamento', 'votação', 'relator',
    'ementa', 'voto', 'dispositivo', 'procedente', 'improcedente', 'parcial',
    'prazo', 'dias', 'úteis', 'recurso', 'embargos', 'contrarrazões',
}

# Pattern for consecutive consonants (OCR artifact indicator)
_CONSONANT_CLUSTER = re.compile(r'[bcdfghjklmnpqrstvwxyz]{5,}', re.IGNORECASE)

# Page marker patterns
_PAGE_MARKERS = [
    re.compile(r'(?i)fls?\.\s*(\d+)'),
    re.compile(r'(?i)Página\s+(\d+)\s+de\s+(\d+)'),
    re.compile(r'(?i)pág(?:ina)?\.\s*(\d+)'),
]

# Expected piece ordering for anomaly detection
_EXPECTED_PIECES = [
    'PETIÇÃO INICIAL', 'CONTESTAÇÃO', 'RÉPLICA', 'SENTENÇA',
    'APELAÇÃO', 'CONTRARRAZÕES', 'ACÓRDÃO',
]


def calculate_ocr_confidence(text: str) -> float:
    """Calculate heuristic OCR confidence score (0.0-1.0).

    Factors:
    - Ratio of recognized words vs garbage
    - Presence of expected legal patterns
    - Character encoding anomalies
    - Consecutive consonant clusters (OCR artifacts)
    """
    if not text or len(text) < 50:
        return 0.0

    words = re.findall(r'\b[a-záàâãéèêíïóôõöúçñ]{3,}\b', text.lower())
    if not words:
        return 0.0

    # Factor 1: Legal term density (0-0.3)
    legal_count = sum(1 for w in words if w in _LEGAL_TERMS)
    legal_density = min(legal_count / max(len(words), 1), 0.3)
    legal_score = legal_density / 0.3 * 0.3

    # Factor 2: Vowel presence ratio (0-0.4)
    # Real Portuguese words contain vowels; OCR garbage typically has low vowel ratios
    all_tokens = text.split()
    if not all_tokens:
        return 0.0
    vowel_pattern = re.compile(r'[aeiouáàâãéèêíïóôõöú]', re.IGNORECASE)
    tokens_with_vowels = sum(1 for t in all_tokens if len(t) >= 3 and vowel_pattern.search(t))
    long_tokens = sum(1 for t in all_tokens if len(t) >= 3)
    vowel_ratio = tokens_with_vowels / max(long_tokens, 1)
    word_score = vowel_ratio * 0.4

    # Factor 3: No consonant clusters (0-0.15)
    clusters = _CONSONANT_CLUSTER.findall(text[:5000])
    cluster_penalty = min(len(clusters) * 0.03, 0.15)
    cluster_score = 0.15 - cluster_penalty

    # Factor 4: Encoding quality (0-0.15)
    # Check for replacement characters, null bytes, control chars
    bad_chars = len(re.findall(r'[\x00-\x08\x0b\x0c\x0e-\x1f\ufffd]', text[:5000]))
    encoding_penalty = min(bad_chars * 0.03, 0.15)
    encoding_score = 0.15 - encoding_penalty

    total = legal_score + word_score + cluster_score + encoding_score
    return round(min(max(total, 0.0), 1.0), 3)


def detect_metadata_anomalies(chunks: list[dict]) -> list[dict]:
    """Flag metadata anomalies in the chunk set.

    Checks for:
    - Date chronology violations
    - Missing expected pieces
    - Duplicate piece labels
    - Unusually short/long pieces relative to type
    """
    anomalies = []

    # Date chronology
    chrono_issues = validate_chronology(chunks)
    anomalies.extend(chrono_issues)

    # Missing expected pieces (only flag if we have both petição and sentença)
    labels = [c.get('label', '') for c in chunks]
    has_peticao = 'PETIÇÃO INICIAL' in labels
    has_sentenca = 'SENTENÇA' in labels

    if has_peticao and has_sentenca and 'CONTESTAÇÃO' not in labels:
        anomalies.append({
            'tipo': 'PECA_FALTANTE',
            'descricao': 'Contestação não detectada entre Petição Inicial e Sentença',
            'impacto': 'MÉDIO',
            'recomendacao': 'Verificar se é revelia ou se a contestação não foi detectada pelo chunking',
        })

    # Duplicate labels
    label_counts: dict[str, int] = {}
    for label in labels:
        label_counts[label] = label_counts.get(label, 0) + 1

    for label, count in label_counts.items():
        if count > 1 and label not in ('DESPACHO', 'CERTIDÃO', 'OFÍCIO', 'MANDADO/CARTA'):
            anomalies.append({
                'tipo': 'PECA_DUPLICADA',
                'descricao': f"'{label}' aparece {count} vezes — verificar se são peças distintas ou chunking duplicado",
                'impacto': 'BAIXO',
                'recomendacao': 'Revisar manualmente se são peças distintas (ex: sentença de mérito + sentença de embargos)',
            })

    # Process number changes
    numeros = set()
    for c in chunks:
        n = c.get('processo_number') or c.get('numero_processo')
        if n:
            numeros.add(n)

    if len(numeros) > 1:
        anomalies.append({
            'tipo': 'NUMERO_PROCESSO_DIVERGENTE',
            'descricao': f"Múltiplos números de processo detectados: {', '.join(numeros)}",
            'impacto': 'ALTO',
            'recomendacao': 'Verificar se o PDF contém processos distintos ou se há erro de OCR nos números',
        })

    return anomalies


def detect_page_gaps(full_text: str, pdf_info: dict) -> list[dict]:
    """Flag potential missing pages based on page markers in text."""
    gaps = []

    # Extract page numbers from "fls." markers
    page_numbers: list[int] = []
    for pattern in _PAGE_MARKERS:
        for m in pattern.finditer(full_text):
            try:
                page_numbers.append(int(m.group(1)))
            except (ValueError, IndexError):
                continue

    if len(page_numbers) < 3:
        return gaps

    page_numbers = sorted(set(page_numbers))

    # Find gaps > 5 pages
    for i in range(len(page_numbers) - 1):
        gap = page_numbers[i + 1] - page_numbers[i]
        if gap > 5:
            gaps.append({
                'tipo': 'LACUNA_PAGINAS',
                'descricao': f"Possível lacuna de {gap} páginas entre fls. {page_numbers[i]} e fls. {page_numbers[i+1]}",
                'impacto': 'MÉDIO',
                'recomendacao': 'Verificar se há páginas faltantes ou se a numeração é descontínua',
            })

    # Check against total pages from PDF info
    total_pages = pdf_info.get('pages', 0)
    if total_pages > 0 and page_numbers:
        max_fls = max(page_numbers)
        if max_fls > total_pages * 1.5:
            gaps.append({
                'tipo': 'NUMERACAO_INCOMPATIVEL',
                'descricao': f"Maior número de fls. ({max_fls}) excede total de páginas do PDF ({total_pages})",
                'impacto': 'BAIXO',
                'recomendacao': 'Numeração de fls. dos autos ≠ páginas do PDF — normal em processos digitalizados',
            })

    return gaps


def generate_integrity_report(
    chunks: list[dict],
    full_text: str = '',
    pdf_info: dict | None = None,
) -> dict:
    """Aggregate all integrity checks into a single report."""
    pdf_info = pdf_info or {}

    # OCR confidence per chunk
    ocr_scores = []
    for chunk in chunks:
        text = chunk.get('text', '')
        score = calculate_ocr_confidence(text)
        ocr_scores.append({
            'chunk_index': chunk.get('index', 0),
            'label': chunk.get('label', '?'),
            'score': score,
        })

    overall_confidence = (
        sum(s['score'] for s in ocr_scores) / len(ocr_scores) if ocr_scores else 0.0
    )

    # Metadata anomalies
    anomalies = detect_metadata_anomalies(chunks)

    # Page gaps
    page_gaps = detect_page_gaps(full_text, pdf_info) if full_text else []

    # Low confidence warnings
    low_confidence = [s for s in ocr_scores if s['score'] < 0.7]
    recommendations = []
    if low_confidence:
        recommendations.append(
            f"{len(low_confidence)} chunk(s) com OCR confidence < 0.7 — "
            "considerar re-extração com vision ou OCR de maior qualidade"
        )

    high_impact = [a for a in anomalies if a.get('impacto') == 'ALTO']
    if high_impact:
        recommendations.append(
            f"{len(high_impact)} anomalia(s) de alto impacto detectada(s) — revisar antes de prosseguir"
        )

    return {
        'overall_confidence': round(overall_confidence, 3),
        'ocr_scores': ocr_scores,
        'anomalies': anomalies,
        'page_gaps': page_gaps,
        'recommendations': recommendations,
    }


def main():
    parser = argparse.ArgumentParser(description='Check document integrity and OCR quality')
    parser.add_argument('--input', '-i', required=True, help='Analysis directory (with index.json and chunks/)')
    args = parser.parse_args()

    input_dir = args.input
    index_path = os.path.join(input_dir, 'index.json')

    if not os.path.exists(index_path):
        print(f"[ERROR] index.json not found in {input_dir}", file=sys.stderr)
        sys.exit(1)

    with open(index_path, 'r', encoding='utf-8') as f:
        index = json.load(f)

    # Load chunks with text
    chunks = []
    for chunk_meta in index.get('chunks', []):
        chunk_file = os.path.join(input_dir, chunk_meta.get('chunk_file', ''))
        text = ''
        if os.path.exists(chunk_file):
            with open(chunk_file, 'r', encoding='utf-8') as f:
                text = f.read()
        chunk = {**chunk_meta, 'text': text}
        chunks.append(chunk)

    # Load full text if available
    full_text_path = os.path.join(input_dir, 'full_text.txt')
    full_text = ''
    if os.path.exists(full_text_path):
        with open(full_text_path, 'r', encoding='utf-8') as f:
            full_text = f.read()

    report = generate_integrity_report(
        chunks,
        full_text=full_text,
        pdf_info=index.get('pdf_info', {}),
    )

    # Save report
    output_path = os.path.join(input_dir, 'integrity_report.json')
    with open(output_path, 'w', encoding='utf-8') as f:
        json.dump(report, f, ensure_ascii=False, indent=2)

    print(f"\nIntegrity Report:")
    print(f"  Overall confidence: {report['overall_confidence']:.1%}")
    print(f"  Anomalies: {len(report['anomalies'])}")
    print(f"  Page gaps: {len(report['page_gaps'])}")
    for rec in report['recommendations']:
        print(f"  [!] {rec}")
    print(f"  Output: {output_path}")


if __name__ == '__main__':
    main()
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 198kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 196kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 196kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 196kUpdated Claude CodeCodexVerifiedInstall