Spaces:
Sleeping
Sleeping
Delete app_ner.py
Browse files- app_ner.py +0 -99
app_ner.py
DELETED
|
@@ -1,99 +0,0 @@
|
|
| 1 |
-
import gradio as gr
|
| 2 |
-
from docling.document_converter import DocumentConverter
|
| 3 |
-
from transformers import AutoModelForTokenClassification, AutoTokenizer
|
| 4 |
-
import torch
|
| 5 |
-
import spacy
|
| 6 |
-
import logging
|
| 7 |
-
|
| 8 |
-
# Configuração do logger
|
| 9 |
-
logging.basicConfig(level=logging.DEBUG)
|
| 10 |
-
logger = logging.getLogger(__name__)
|
| 11 |
-
|
| 12 |
-
# Carregar o modelo e o tokenizador
|
| 13 |
-
model_name = "dominguesm/ner-legal-bert-base-cased-ptbr"
|
| 14 |
-
logger.info(f"Carregando o modelo: {model_name}")
|
| 15 |
-
model = AutoModelForTokenClassification.from_pretrained(model_name)
|
| 16 |
-
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 17 |
-
logger.info("Modelo e tokenizador carregados com sucesso.")
|
| 18 |
-
|
| 19 |
-
# Carrega modelo de NLP pt-br
|
| 20 |
-
#nlp = spacy.load("pt_core_news_sm")
|
| 21 |
-
|
| 22 |
-
# Função para realizar a inferência com o modelo de NER
|
| 23 |
-
def extract_entities(text):
|
| 24 |
-
logger.debug(f"Iniciando extração de entidades para o texto: {text[:50]}...")
|
| 25 |
-
# Tokenize o texto
|
| 26 |
-
inputs = tokenizer(text, max_length=512, truncation=True, return_tensors="pt")
|
| 27 |
-
tokens = inputs.tokens()
|
| 28 |
-
|
| 29 |
-
logger.debug("Obtendo previsões do modelo.")
|
| 30 |
-
# Obtenha as previsões do modelo
|
| 31 |
-
with torch.no_grad():
|
| 32 |
-
outputs = model(**inputs).logits
|
| 33 |
-
predictions = torch.argmax(outputs, dim=2)
|
| 34 |
-
|
| 35 |
-
# Extrair as entidades reconhecidas
|
| 36 |
-
entities = []
|
| 37 |
-
logger.debug("Extraindo entidades.")
|
| 38 |
-
for token, prediction in zip(tokens, predictions[0].numpy()):
|
| 39 |
-
entity_label = model.config.id2label[prediction]
|
| 40 |
-
if entity_label != "O": # "O" significa que não é uma entidade
|
| 41 |
-
entities.append((token, entity_label))
|
| 42 |
-
|
| 43 |
-
logger.info(f"Entidades extraídas: {entities}")
|
| 44 |
-
return entities
|
| 45 |
-
|
| 46 |
-
# Função para extrais os representantes legais
|
| 47 |
-
def extract_representatives(entities):
|
| 48 |
-
logger.debug("Iniciando extração de representantes legais.")
|
| 49 |
-
representatives = []
|
| 50 |
-
|
| 51 |
-
current_person = ""
|
| 52 |
-
current_organization = ""
|
| 53 |
-
|
| 54 |
-
for token, label in entities:
|
| 55 |
-
if label == "B-PESSOA" or label == "I-PESSOA":
|
| 56 |
-
# Concatenando os tokens da pessoa
|
| 57 |
-
current_person += token.replace("##", "") # Remover o "##" das partes do token
|
| 58 |
-
else:
|
| 59 |
-
if current_person:
|
| 60 |
-
representatives.append(current_person)
|
| 61 |
-
current_person = "" # Resetar para a próxima pessoa
|
| 62 |
-
|
| 63 |
-
if label == "B-ORGANIZACAO" or label == "I-ORGANIZACAO":
|
| 64 |
-
# Concatenando os tokens da organização
|
| 65 |
-
current_organization += token.replace("##", "")
|
| 66 |
-
else:
|
| 67 |
-
if current_organization:
|
| 68 |
-
representatives.append(current_organization)
|
| 69 |
-
current_organization = "" # Resetar para a próxima organização
|
| 70 |
-
|
| 71 |
-
# Adicionar a última pessoa ou organização, caso o texto termine sem delimitadores
|
| 72 |
-
if current_person:
|
| 73 |
-
representatives.append(current_person)
|
| 74 |
-
if current_organization:
|
| 75 |
-
representatives.append(current_organization)
|
| 76 |
-
|
| 77 |
-
logger.info(f"Representantes extraídos: {representatives}")
|
| 78 |
-
return representatives
|
| 79 |
-
|
| 80 |
-
# Função para converter o documento e extrair as entidades jurídicas
|
| 81 |
-
def convert_document(file):
|
| 82 |
-
logger.debug("Iniciando conversão do documento.")
|
| 83 |
-
converter = DocumentConverter()
|
| 84 |
-
logger.info(f"Convertendo o documento: {file.name}")
|
| 85 |
-
result = converter.convert(file.name)
|
| 86 |
-
document_text = result.document.export_to_text()
|
| 87 |
-
|
| 88 |
-
# Extrair as entidades jurídicas do texto convertido
|
| 89 |
-
entities = extract_entities(document_text)
|
| 90 |
-
|
| 91 |
-
# Extrair representantes legais
|
| 92 |
-
legal_representatives = extract_representatives(entities)
|
| 93 |
-
|
| 94 |
-
return document_text, legal_representatives
|
| 95 |
-
|
| 96 |
-
# Interface do Gradio
|
| 97 |
-
demo = gr.Interface(fn=convert_document, inputs="file", outputs=["text", "json"])
|
| 98 |
-
logger.info("Iniciando a interface Gradio.")
|
| 99 |
-
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|