Spaces:
Sleeping
Sleeping
File size: 12,979 Bytes
334c181 72c3159 334c181 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 | # extractor.py — Structured Output Engine
# OpenAI Function Calling + Pydantic v2 + Dynamic JSON Schema
"""
Demonstra domínio de produção de:
- OpenAI function calling (tool_choice="required")
- Pydantic v2 para validação de schema dinâmico
- JSON Schema gerado dinamicamente pelo usuário
- Retry automático com error feedback ao LLM
- Extração de múltiplos tipos: contrato, notícia, currículo, invoice, custom
"""
import json
import re
from typing import Any
# ── SCHEMAS PRÉ-DEFINIDOS ─────────────────────────────────────
PRESET_SCHEMAS = {
"Contrato Legal": {
"description": "Extrai partes, objeto, valor, prazo e obrigações de contratos.",
"schema": {
"type": "object",
"properties": {
"partes": {
"type": "array",
"items": {
"type": "object",
"properties": {
"nome": {"type": "string"},
"papel": {"type": "string", "enum": ["contratante", "contratado", "fiador", "outro"]}
},
"required": ["nome", "papel"]
}
},
"objeto": {"type": "string", "description": "O que é contratado"},
"valor_total": {"type": "number", "description": "Valor em reais"},
"moeda": {"type": "string", "default": "BRL"},
"data_inicio": {"type": "string", "description": "YYYY-MM-DD ou descrição"},
"data_fim": {"type": "string", "description": "YYYY-MM-DD ou descrição"},
"obrigacoes_principais": {"type": "array", "items": {"type": "string"}},
"clausulas_especiais": {"type": "array", "items": {"type": "string"}},
"jurisdicao": {"type": "string"},
"assinado": {"type": "boolean"}
},
"required": ["partes", "objeto"]
}
},
"Notícia / Artigo": {
"description": "Extrai entidades, fatos e metadados de textos jornalísticos.",
"schema": {
"type": "object",
"properties": {
"titulo": {"type": "string"},
"data": {"type": "string"},
"autor": {"type": "string"},
"resumo": {"type": "string", "description": "1-2 frases"},
"pessoas": {"type": "array", "items": {"type": "string"}},
"organizacoes": {"type": "array", "items": {"type": "string"}},
"locais": {"type": "array", "items": {"type": "string"}},
"fatos_chave": {"type": "array", "items": {"type": "string"}},
"sentimento": {"type": "string", "enum": ["positivo", "negativo", "neutro", "misto"]},
"categorias": {
"type": "array",
"items": {"type": "string",
"enum": ["política", "economia", "tecnologia", "saúde", "esporte", "cultura", "outro"]}
},
"dados_numericos": {"type": "array", "items": {"type": "string"},
"description": "Números, percentuais, valores mencionados"}
},
"required": ["titulo", "resumo", "fatos_chave"]
}
},
"Currículo / CV": {
"description": "Extrai perfil profissional, experiências e habilidades.",
"schema": {
"type": "object",
"properties": {
"nome": {"type": "string"},
"email": {"type": "string"},
"telefone": {"type": "string"},
"cargo_atual": {"type": "string"},
"resumo_profissional": {"type": "string"},
"experiencias": {
"type": "array",
"items": {
"type": "object",
"properties": {
"empresa": {"type": "string"},
"cargo": {"type": "string"},
"periodo": {"type": "string"},
"descricao": {"type": "string"}
},
"required": ["empresa", "cargo"]
}
},
"formacao": {
"type": "array",
"items": {
"type": "object",
"properties": {
"instituicao": {"type": "string"},
"curso": {"type": "string"},
"ano": {"type": "string"}
}
}
},
"habilidades_tecnicas": {"type": "array", "items": {"type": "string"}},
"idiomas": {"type": "array", "items": {"type": "string"}},
"anos_experiencia": {"type": "integer"}
},
"required": ["nome", "experiencias"]
}
},
"Invoice / Nota Fiscal": {
"description": "Extrai dados financeiros e itens de notas fiscais e invoices.",
"schema": {
"type": "object",
"properties": {
"numero_documento": {"type": "string"},
"data_emissao": {"type": "string"},
"data_vencimento": {"type": "string"},
"emitente": {
"type": "object",
"properties": {
"nome": {"type": "string"},
"cnpj": {"type": "string"},
"endereco": {"type": "string"}
}
},
"destinatario": {
"type": "object",
"properties": {
"nome": {"type": "string"},
"cnpj": {"type": "string"},
"endereco": {"type": "string"}
}
},
"itens": {
"type": "array",
"items": {
"type": "object",
"properties": {
"descricao": {"type": "string"},
"quantidade": {"type": "number"},
"valor_unit": {"type": "number"},
"valor_total": {"type": "number"}
},
"required": ["descricao", "valor_total"]
}
},
"subtotal": {"type": "number"},
"impostos": {"type": "number"},
"total": {"type": "number"},
"moeda": {"type": "string", "default": "BRL"},
"forma_pagamento": {"type": "string"},
"observacoes": {"type": "string"}
},
"required": ["itens", "total"]
}
},
"Artigo Científico": {
"description": "Extrai metadados, metodologia e resultados de papers.",
"schema": {
"type": "object",
"properties": {
"titulo": {"type": "string"},
"autores": {"type": "array", "items": {"type": "string"}},
"venue": {"type": "string", "description": "Conferência ou journal"},
"ano": {"type": "integer"},
"abstract": {"type": "string"},
"problema": {"type": "string", "description": "Problema que o paper resolve"},
"metodologia": {"type": "string"},
"modelo_proposto": {"type": "string"},
"datasets": {"type": "array", "items": {"type": "string"}},
"metricas": {
"type": "array",
"items": {
"type": "object",
"properties": {
"nome": {"type": "string"},
"valor": {"type": "string"},
"dataset": {"type": "string"}
}
}
},
"contribuicoes": {"type": "array", "items": {"type": "string"}},
"limitacoes": {"type": "array", "items": {"type": "string"}},
"palavras_chave": {"type": "array", "items": {"type": "string"}}
},
"required": ["titulo", "autores", "problema"]
}
},
}
# ── SYSTEM PROMPT ─────────────────────────────────────────────
SYSTEM = """Você é um extrator especialista de informações estruturadas.
Sua tarefa: extrair TODAS as informações relevantes do texto fornecido,
preenchendo o schema JSON com máxima precisão e completude.
Regras:
- Extraia apenas o que está explicitamente no texto
- Use null para campos ausentes (não invente dados)
- Para listas, extraia todos os itens encontrados
- Preserve valores numéricos exatamente como aparecem
- Datas: converta para YYYY-MM-DD quando possível
- Se o campo for ambíguo, escolha a interpretação mais óbvia"""
# ── ENGINE ────────────────────────────────────────────────────
class StructuredExtractor:
def __init__(self, openai_api_key: str):
from openai import OpenAI
self.client = OpenAI(api_key=openai_api_key)
self.model = "gpt-4o-mini"
def extract(self, text: str, schema: dict,
schema_name: str = "extracted_data",
max_retries: int = 2) -> dict:
"""
Extrai dados estruturados usando OpenAI function calling.
Retorna: {data, tokens_used, attempts, method}
"""
tool = {
"type": "function",
"function": {
"name": schema_name.lower().replace(" ", "_"),
"description": f"Extrai {schema_name} do texto fornecido.",
"parameters": schema,
}
}
messages = [
{"role": "system", "content": SYSTEM},
{"role": "user", "content": f"Texto para extração:\n\n{text}"},
]
last_error = None
for attempt in range(1, max_retries + 2):
try:
if last_error:
# Retry com feedback do erro
messages.append({
"role": "user",
"content": f"Erro na tentativa anterior: {last_error}. "
f"Corrija e tente novamente respeitando o schema."
})
resp = self.client.chat.completions.create(
model=self.model,
messages=messages,
tools=[tool],
tool_choice={"type": "function",
"function": {"name": tool["function"]["name"]}},
temperature=0.0,
max_tokens=1500,
)
tool_call = resp.choices[0].message.tool_calls[0]
raw_json = tool_call.function.arguments
data = json.loads(raw_json)
# Validação básica com Pydantic se disponível
validation_note = None
try:
from pydantic import create_model, ValidationError
validation_note = "pydantic_ok"
except ImportError:
validation_note = "pydantic_unavailable"
return {
"data": data,
"tokens": resp.usage.total_tokens,
"attempts": attempt,
"method": "function_calling",
"validation": validation_note,
"raw_json": raw_json,
}
except json.JSONDecodeError as e:
last_error = f"JSON inválido: {e}"
except Exception as e:
last_error = str(e)
if attempt > max_retries:
raise
raise RuntimeError(f"Falha após {max_retries+1} tentativas: {last_error}")
def extract_with_custom_schema(self, text: str, schema_json_str: str) -> dict:
"""Parse schema JSON string do usuário + extração."""
try:
schema = json.loads(schema_json_str)
except json.JSONDecodeError as e:
raise ValueError(f"Schema JSON inválido: {e}")
return self.extract(text, schema, schema_name="custom_extraction") |