O Blackstone é um modelo e biblioteca Spacy para processar um texto legal não estruturado e de formato longo. Blackstone é um projeto de pesquisa experimental do Conselho Incorporado de Relatórios de Direito para o Laboratório de Pesquisa da Inglaterra e do País de Gales, ICLR & D. Blackstone foi escrito por Daniel Hoadley.
Por que estamos construindo Blackstone?
O que há de especial em Blackstone?
Observações e outras coisas que valem a pena notar
Instalação
Instale a biblioteca
Instale o modelo Blackstone
Sobre o modelo
O pipeline
Reconhecedor de entidade nomeada
Categorizador de texto
Uso
Aplicando o modelo NER
Visualizando entidades
Aplicando o modelo de categoriser de texto
Extensões de pipeline personalizadas
Abreviação e resolução de definição de forma longa
Detecções de referência de casos compostos
Legislação Linker
Segmento de frases
Nos últimos anos, houve um aumento na atividade na interseção da lei e da tecnologia. No entanto, no Reino Unido, a grande quantidade dessa atividade ocorreu em escritórios de advocacia e outros contextos comerciais. A conseqüência disso é que, apesar da enxurrada interminável de desenvolvimento no espaço legal-informático, quase nenhuma das pesquisas é disponibilizada em uma base de código aberto.
Além disso, a majoritria da pesquisa no domínio da Informática Legal do Reino Unido (aberta ou fechada) se concentrou no desenvolvimento de pedidos de PNL para automatizar contratos e outros documentos legais que são de natureza transacional. Isso é compreensível, porque os principais benfeitores da pesquisa jurídica na PNL no Reino Unido são escritórios de advocacia e escritórios de advocacia tendem a não achar difícil obter as mãos na documentação transacional que pode ser aproveitada como dados de treinamento.
O problema, como o vemos, é que a pesquisa legal da PNL no Reino Unido se concentrou demais em aplicações comerciais e que vale a pena tornar o investimento no desenvolvimento de pesquisas legais de PNL disponível em relação a outros textos legais, como julgamentos, artigos acadêmicos, argumentos de esqueletos e alegações.
Observação! É fortemente recomendado que você instale o Blackstone em um ambiente virtual! Veja aqui para saber mais sobre ambientes virtuais. Blackstone deve ser compatível com o Python 3.6 e superior.
Para instalar o Blackstone, siga estas etapas:
A primeira etapa é instalar a biblioteca, que atualmente contém um punhado de componentes espaciais personalizados. Instale a biblioteca como assim:
pip install blackstone
A segunda etapa é instalar o modelo Spacy. Instale o modelo como assim:
pip install https://blackstone-model.s3-eu-west-1.amazonaws.com/en_blackstone_proto-0.0.1.tar.gz
Se você estiver desenvolvendo Blackstone, pode instalar a partir da fonte como assim:
pip install --editable .
pip install -r dev-requirements.txt
Este é o primeiro lançamento de Blackstone e o modelo é melhor visto como um protótipo ; É difícil nas bordas e representa a primeira etapa em um programa maior de pesquisa de código aberto sobre a PNL sobre textos legais que estão sendo realizados pela ICLR & D.
Com isso fora do caminho, aqui está um breve resumo do que está acontecendo no modelo Proto.
O modelo Proto incluído nesta versão tem os seguintes elementos em seu pipeline:
Devido a uma escassez de dados de treinamento de parte de fala e dependência rotulados para texto legal, os componentes do pipeline de tokenizer , tagger e parser foram retirados do modelo en_core_web_sm de Spacy. Em geral, esses componentes parecem fazer um trabalho decente, mas seria bom revisitar esses componentes com dados de treinamento personalizados em algum momento no futuro.
Os componentes ner e textcat são componentes personalizados treinados especialmente para Blackstone.
O componente NER do modelo Blackstone foi treinado para detectar os seguintes tipos de entidade:
| Ent | Nome | Exemplos |
|---|---|---|
| Casename | Nomes de casos | Por exemplo, Smith v Jones , em Re Jones , no caso de Jones |
| CITAÇÃO | Citações (identificadores únicos para casos relatados e não relatados) | Por exemplo (2002) 2 Cr App R 123 |
| INSTRUMENTO | Instrumentos legais escritos | Por exemplo, Lei de Roubo de 1968, Convenção Europeia sobre Direitos Humanos, RCP |
| Provisão | Unidade dentro de um instrumento legal por escrito | Por exemplo, Seção 1, Art 2 (3) |
| TRIBUNAL | Tribunal ou Tribunal | por exemplo, Tribunal de Apelação, Tribunal Superior |
| JUIZ | Referências a juízes | Por exemplo, Eady J, Lord Bingham de Cornhill |
Este lançamento da Blackstone também vem com um categorizador de texto. Em contraste com o componente NER (que foi treinado para identificar tokens e séries de tokens de interesse), o categorizador de texto classifica vãos mais longos de texto, como frases.
O categoriser de texto foi treinado para classificar o texto de acordo com uma das cinco categorias mutuamente exclusivas, que são as seguintes:
| Gato | Descrição |
|---|---|
| AXIOMA | O texto parece postular um princípio bem estabelecido |
| CONCLUSÃO | O texto parece fazer uma descoberta, retenção, determinação ou conclusão |
| EMITIR | O texto parece discutir um problema ou pergunta |
| Legal_test | O teste parece discutir um teste legal |
| Uncat | O texto não se enquadra em uma das quatro categorias acima |
Aqui está um exemplo de como o modelo é aplicado a algum texto retirado do parágrafo 31 do julgamento do Tribunal de Divisão em R (Miller) v Secretário de Estado por sair da União Europeia (Birnie interveniente) [2017] UKSC 5; [2018] AC 61:
import spacy
# Load the model
nlp = spacy . load ( "en_blackstone_proto" )
text = """ 31 As we shall explain in more detail in examining the submission of the Secretary of State (see paras 77 and following), it is the Secretary of State’s case that nothing has been done by Parliament in the European Communities Act 1972 or any other statute to remove the prerogative power of the Crown, in the conduct of the international relations of the UK, to take steps to remove the UK from the EU by giving notice under article 50EU for the UK to withdraw from the EU Treaty and other relevant EU Treaties. The Secretary of State relies in particular on Attorney General v De Keyser’s Royal Hotel Ltd [1920] AC 508 and R v Secretary of State for Foreign and Commonwealth Affairs, Ex p Rees-Mogg [1994] QB 552; he contends that the Crown’s prerogative power to cause the UK to withdraw from the EU by giving notice under article 50EU could only have been removed by primary legislation using express words to that effect, alternatively by legislation which has that effect by necessary implication. The Secretary of State contends that neither the ECA 1972 nor any of the other Acts of Parliament referred to have abrogated this aspect of the Crown’s prerogative, either by express words or by necessary implication.
"""
# Apply the model to the text
doc = nlp ( text )
# Iterate through the entities identified by the model
for ent in doc . ents :
print ( ent . text , ent . label_ )
> >> European Communities Act 1972 INSTRUMENT
> >> article 50 EU PROVISION
>> > EU Treaty INSTRUMENT
> >> Attorney General v De Keyser ’ s Royal Hotel Ltd CASENAME
> >> [ 1920 ] AC 508 CITATION
>> > R v Secretary of State for Foreign and Commonwealth Affairs , Ex p Rees - Mogg CASENAME
>> > [ 1994 ] QB 552 CITATION
> >> article 50 EU PROVISION Navios espaciais com um excelente conjunto de visualizadores, incluindo um visualizador para NER prevê. O Blackstone vem com uma paleta de cores personalizada que pode ser usada para facilitar a distigui entidades no texto de origem ao usar o Despotamento.
"""
Visualise entities using spaCy's displacy visualiser.
Blackstone has a custom colour palette: `from blackstone.displacy_palette import ner_displacy options`
"""
import spacy
from spacy import displacy
from blackstone . displacy_palette import ner_displacy_options
nlp = spacy . load ( "en_blackstone_proto" )
text = """
The applicant must satisfy a high standard. This is a case where the action is to be tried by a judge with a jury. The standard is set out in Jameel v Wall Street Journal Europe Sprl [2004] EMLR 89, para 14:
“But every time a meaning is shut out (including any holding that the words complained of either are, or are not, capable of bearing a defamatory meaning) it must be remembered that the judge is taking it upon himself to rule in effect that any jury would be perverse to take a different view on the question. It is a high threshold of exclusion. Ever since Fox’s Act 1792 (32 Geo 3, c 60) the meaning of words in civil as well as criminal libel proceedings has been constitutionally a matter for the jury. The judge’s function is no more and no less than to pre-empt perversity. That being clearly the position with regard to whether or not words are capable of being understood as defamatory or, as the case may be, non-defamatory, I see no basis on which it could sensibly be otherwise with regard to differing levels of defamatory meaning. Often the question whether words are defamatory at all and, if so, what level of defamatory meaning they bear will overlap.”
18 In Berezovsky v Forbes Inc [2001] EMLR 1030, para 16 Sedley LJ had stated the test this way:
“The real question in the present case is how the courts ought to go about ascertaining the range of legitimate meanings. Eady J regarded it as a matter of impression. That is all right, it seems to us, provided that the impression is not of what the words mean but of what a jury could sensibly think they meant. Such an exercise is an exercise in generosity, not in parsimony.”
"""
doc = nlp ( text )
# Call displacy and pass `ner_displacy_options` into the option parameter`
displacy . serve ( doc , style = "ent" , options = ner_displacy_options )Que produz algo que se parece com o seguinte:
A categoriser de texto de Blackstone gera uma categorização prevista para um doc . O componente do pipeline textcat foi projetado para ser aplicado a frases individuais, em vez de um único documento que consiste em muitas frases.
import spacy
# Load the model
nlp = spacy . load ( "en_blackstone_proto" )
def get_top_cat ( doc ):
"""
Function to identify the highest scoring category
prediction generated by the text categoriser.
"""
cats = doc . cats
max_score = max ( cats . values ())
max_cats = [ k for k , v in cats . items () if v == max_score ]
max_cat = max_cats [ 0 ]
return ( max_cat , max_score )
text = """
It is a well-established principle of law that the transactions of independent states between each other are governed by other laws than those which municipal courts administer.
It is, however, in my judgment, insufficient to react to the danger of over-formalisation and “judicialisation” simply by emphasising flexibility and context-sensitivity.
The question is whether on the facts found by the judge, the (or a) proximate cause of the loss of the rig was “inherent vice or nature of the subject matter insured” within the meaning of clause 4.4 of the Institute Cargo Clauses (A).
"""
# Apply the model to the text
doc = nlp ( text )
# Get the sentences in the passage of text
sentences = [ sent . text for sent in doc . sents ]
# Print the sentence and the corresponding predicted category.
for sentence in sentences :
doc = nlp ( sentence )
top_category = get_top_cat ( doc )
print ( f" " { sentence } " { top_category } n " )
> >> "In my judgment, it is patently obvious that cats are a type of dog." ( 'CONCLUSION' , 0.9990500807762146 )
> >> "It is a well settled principle that theft is wrong." ( 'AXIOM' , 0.556410014629364 )
> >> "The question is whether on the facts found by the judge, the (or a) proximate cause of the loss of the rig was “inherent vice or nature of the subject matter insured” within the meaning of clause 4.4 of the Institute Cargo Clauses (A)." ( 'ISSUE' , 0.5040785074234009 )Além do modelo principal, esta versão proto da Blackstone vem com três componentes personalizados:
AbbreviationDetector() em [Scispacy] e resolve uma forma abreviada para sua definição de forma longa, por exemplo, ECtHR European Court of Human Rights .CASENAME e CITATION , permitindo a fusão de uma CITATION ao seu CASENAME pai.Não é incomum que os autores de documentos legais abreviam termos longos que serão usados em vez da forma longa durante o restante do documento. Por exemplo,
O Tribunal Europeu de Direitos Humanos ("ECTHR") é o tribunal responsável por aplicar a Convenção Europeia sobre Direitos Humanos ("ECHR").
The abbreviation detection component in Blackstone seeks to address this by implementing an ever so slightly modified version of scispaCy's AbbreviationDetector() (which is itself an implementation of the approach set out in this paper: https://psb.stanford.edu/psb-online/proceedings/psb03/schwartz.pdf). Nossa implementação ainda tem alguns problemas, mas um exemplo de seu uso é o seguinte:
import spacy
from blackstone . pipeline . abbreviations import AbbreviationDetector
nlp = spacy . load ( "en_blackstone_proto" )
# Add the abbreviation pipe to the spacy pipeline.
abbreviation_pipe = AbbreviationDetector ( nlp )
nlp . add_pipe ( abbreviation_pipe )
doc = nlp ( 'The European Court of Human Rights ("ECtHR") is the court ultimately responsible for applying the European Convention on Human Rights ("ECHR").' )
print ( "Abbreviation" , " t " , "Definition" )
for abrv in doc . _ . abbreviations :
print ( f" { abrv } t ( { abrv . start } , { abrv . end } ) { abrv . _ . long_form } " )
> >> "ECtHR" ( 7 , 10 ) European Court of Human Rights
>> > "ECHR" ( 25 , 28 ) European Convention on Human Rights O componente de detecção de referência de casos compostos em Blackstone foi projetado para se casar com entidades CITATION com suas entidades de CASENAME .
As jurisdições do direito comum normalmente se relacionam com as referências de casos através de um acoplamento de um nome (normalmente derivado dos nomes das partes no caso) e alguma citação única para identificar onde o caso foi relatado, assim:
Regina v Horncastle [2010] 2 AC 373
O modelo NER de Blackstone tenta separadamente identificar as entidades CASENAME e CITATION . No entanto, é potencialmente útil (particularmente no contexto da extração de informações) extrair essas entidades como pares.
CompoundCases() aplica um tubo personalizado após o NER e identifica pares de CASENAME / CITATION em dois cenários:
import spacy
from blackstone . pipeline . compound_cases import CompoundCases
nlp = spacy . load ( "en_blackstone_proto" )
compound_pipe = CompoundCases ( nlp )
nlp . add_pipe ( compound_pipe )
text = "As I have indicated, this was the central issue before the judge. On this issue the defendants relied (successfully below) on the decision of the High Court in Gelmini v Moriggia [1913] 2 KB 549. In Jones' case [1915] 1 KB 45, the defendant wore a hat."
doc = nlp ( text )
for compound_ref in doc . _ . compound_cases :
print ( compound_ref )
> >> Gelmini v Moriggia [ 1913 ] 2 KB 549
>> > Jones ' case [ 1915 ] 1 KB 45 A legislação de Blackstone tenta acoplar uma referência a uma PROVISION ao seu INSTRUMENT pai usando o modelo NER para identificar a presença de um INSTRUMENT e depois navegar na árvore de dependência para identificar a provisão infantil.
Depois que a Blackstone identificar uma PROVISION : par INSTRUMENT , tentará gerar URLs de destino para a disposição e o instrumento na legislação.gov.uk.
import spacy
from blackstone . utils . legislation_linker import extract_legislation_relations
nlp = spacy . load ( "en_blackstone_proto" )
text = "The Secretary of State was at pains to emphasise that, if a withdrawal agreement is made, it is very likely to be a treaty requiring ratification and as such would have to be submitted for review by Parliament, acting separately, under the negative resolution procedure set out in section 20 of the Constitutional Reform and Governance Act 2010. Theft is defined in section 1 of the Theft Act 1968"
doc = nlp ( text )
relations = extract_legislation_relations ( doc )
for provision , provision_url , instrument , instrument_url in relations :
print ( f" n { provision } t { provision_url } t { instrument } t { instrument_url } " )
> >> section 20 http : // www . legislation . gov . uk / ukpga / 2010 / 25 / section / 20 Constitutional Reform and Governance Act 2010 http : // www . legislation . gov . uk / ukpga / 2010 / 25 / contents
> >> section 1 http : // www . legislation . gov . uk / ukpga / 1968 / 60 / section / 1 Theft Act 1968 http : // www . legislation . gov . uk / ukpga / 1968 / 60 / contentsA Blackstone envia com um segmento de sentença baseado em regras personalizado que aborda uma série de características inerentes aos textos legais que tendem a desconcertar as regras de segmentação de sentenças prontas para uso.
Esse comportamento pode ser estendido, opcionalmente, passando uma lista de padrões de combinadores de estilo Spacy que impedirão explicitamente a detecção de limites das sentenças.
import spacy
from blackstone . pipeline . sentence_segmenter import SentenceSegmenter
from blackstone . rules import CITATION_PATTERNS
nlp = spacy . load ( "en_blackstone_proto" )
# add the Blackstone sentence_segmenter to the pipeline before the parser
sentence_segmenter = SentenceSegmenter ( nlp . vocab , CITATION_PATTERNS )
nlp . add_pipe ( sentence_segmenter , before = "parser" )
doc = nlp (
"""
The courts in this jurisdiction will enforce those commitments when it is legally possible and necessary to do so (see, most recently, R. (on the application of ClientEarth) v Secretary of State for the Environment, Food and Rural Affairs (No.2) [2017] P.T.S.R. 203 and R. (on the application of ClientEarth) v Secretary of State for Environment, Food and Rural Affairs (No.3) [2018] Env. L.R. 21). The central question in this case arises against that background.
"""
)
for sent in doc . sents :
print ( sent . text )Gostaríamos de agradecer às seguintes pessoas/organizações que nos ajudaram (direta ou indiretamente) a construir esse protótipo.