Blackstone es un modelo y una biblioteca de Spacy para procesar texto legal no estructurado de forma larga. Blackstone es un proyecto de investigación experimental del Informe de Informes del Consejo de Derecho de Inglaterra para el Laboratorio de Investigación de Inglaterra y Gales, ICLR & D. Blackstone fue escrito por Daniel Hoadley.
¿Por qué estamos construyendo Blackstone?
¿Qué tiene de especial Blackstone?
Observaciones y otras cosas que vale la pena señalar
Instalación
Instalar la biblioteca
Instale el modelo Blackstone
Sobre el modelo
La tubería
Reconocedor de la entidad nombrada
Categorizador de texto
Uso
Aplicando el modelo NER
Visualización de entidades
Aplicar el modelo de categorizador de texto
Extensiones de tuberías personalizadas
Abreviatura y resolución de definición de formato largo
Detecciones de referencia de casos compuestos
Enlazador de legislación
Segmento de oraciones
Los últimos años han visto un aumento en la actividad en la intersección de la ley y la tecnología. Sin embargo, en el Reino Unido, la gran variedad de esa actividad ha tenido lugar en firmas de abogados y otros contextos comerciales. La consecuencia de esto es que a pesar de la ráfaga de desarrollo interminable en el espacio de información legal, casi ninguna de las investigaciones se pone a disposición de forma abierta.
Además, la mayoritería de la investigación en el dominio de información legal del Reino Unido (ya sea abierta o cerrada) se ha centrado en el desarrollo de aplicaciones de PNL para automatizar contratos y otros documentos legales que son de naturaleza transaccional. Esto es comprensible, porque los principales benefactores de la investigación legal de la PNL en el Reino Unido son las firmas de abogados y las firmas de abogados tienden a no ser difícil obtener una documentación transaccional que pueda aprovecharse como datos de capacitación.
El problema, como lo vemos, es que la investigación legal de PNL en el Reino Unido se ha concentrado en exceso en aplicaciones comerciales y que vale la pena hacer la inversión en el desarrollo de la investigación legal de la PNL disponible con respecto a otros textos legales, como juicios, artículos académicos, argumentos de esqueletos y suplicaciones.
¡Nota! ¡Se recomienda encarecidamente que instale Blackstone en un entorno virtual! Vea aquí para obtener más información sobre entornos virtuales. Blackstone debe compatible con Python 3.6 y superior.
Para instalar Blackstone, siga estos pasos:
El primer paso es instalar la biblioteca, que en la actualidad contiene un puñado de componentes de Spacy personalizados. Instale la biblioteca así:
pip install blackstone
El segundo paso es instalar el modelo Spacy. Instale el modelo como así:
pip install https://blackstone-model.s3-eu-west-1.amazonaws.com/en_blackstone_proto-0.0.1.tar.gz
Si está desarrollando Blackstone, puede instalar desde la fuente así:
pip install --editable .
pip install -r dev-requirements.txt
Esta es la primera versión de Blackstone y el modelo se ve mejor como un prototipo ; Es duro alrededor de los bordes y representa el primer paso en un programa continuo más grande de investigación de código abierto sobre PNL sobre textos legales que llevan a cabo ICLR & D.
Con eso fuera del camino, aquí hay un breve resumen de lo que está sucediendo en el modelo Proto.
El modelo Proto incluido en esta versión tiene los siguientes elementos en su tubería:
Debido a una escasez de datos etiquetados de capacitación en parte de voz y dependencia para texto legal, los componentes de la tubería de tokenizer , tagger y parser se han tomado del modelo en_core_web_sm de Spacy. En general, estos componentes parecen hacer un trabajo decente, pero sería bueno volver a visitar estos componentes con datos de capacitación personalizados en algún momento en el futuro.
Los componentes ner y textcat son componentes personalizados capacitados, especialmente para Blackstone.
El componente NER del modelo Blackstone ha sido entrenado para detectar los siguientes tipos de entidad:
| Enterarse | Nombre | Ejemplos |
|---|---|---|
| Juego de caseño | Nombres de casos | por ejemplo, Smith v Jones , en re Jones , en el caso de Jones |
| CITACIÓN | Citas (identificadores únicos para casos reportados y no reportados) | EG (2002) 2 Cr App R 123 |
| INSTRUMENTO | Instrumentos legales escritos | por ejemplo, la Ley de robo de 1968, Convención Europea de Derechos Humanos, RCP |
| DISPOSICIÓN | Unidad dentro de un instrumento legal escrito | por ejemplo, Sección 1, Art 2 (3) |
| CORTE | Tribunal o tribunal | Por ejemplo, la Corte de Apelaciones, Tribunal Superior |
| JUEZ | Referencias a los jueces | por ejemplo, Eady J, Lord Bingham de Cornhill |
Esta versión de Blackstone también viene con un categorizador de texto. En contraste con el componente NER (que ha sido capacitado para identificar tokens y series de tokens de interés), el categorizador de texto clasifica los tramos más largos de texto, como las oraciones.
El categorizador de texto ha sido entrenado para clasificar el texto de acuerdo con una de las cinco categorías mutuamente excluyentes, que son las siguientes:
| Gato | Descripción |
|---|---|
| AXIOMA | El texto parece postular un principio bien establecido |
| CONCLUSIÓN | El texto parece hacer un hallazgo, retención, determinación o conclusión |
| ASUNTO | El texto parece discutir un tema o pregunta |
| Legal_test | La prueba parece discutir una prueba legal |
| Noble | El texto no cae en una de las cuatro categorías anteriores |
Aquí hay un ejemplo de cómo se aplica el modelo a algún texto tomado del párrafo 31 de la sentencia del Tribunal Divisional en R (Miller) v Secretario de Estado para salir de la Unión Europea (Birnie Intervening) [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 Spacy se envía con un excelente conjunto de visualizadores, incluido un visualizador de predicciones NER. Blackstone viene con una paleta de colores personalizada que se puede usar para facilitar las entidades distopiares en el texto de la fuente cuando se usa la desplazamiento.
"""
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 produce algo que se ve así:
El categorizador de texto de Blackstone genera una categorización prevista para un doc . El componente de la tubería textcat se ha diseñado para aplicarse a oraciones individuales en lugar de un solo documento que consiste en muchas oraciones.
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 )Además del modelo central, esta versión Proto de Blackstone viene con tres componentes personalizados:
AbbreviationDetector() en [Scispacy] y resuelve una forma abreviada a su larga definición de la forma, por ejemplo, ECtHR European Court of Human Rights .CASENAME y CITATION que permiten la fusión de una CITATION a su CASENAME principal.No es raro que los autores de documentos legales abreviaran los términos de largo aliento que se utilizarán en lugar de la forma larga a través del resto del documento. Por ejemplo,
El Tribunal Europeo de Derechos Humanos ("TEDH") es el tribunal responsable en última instancia de aplicar la Convención Europea de Derechos Humanos ("CEDH").
El componente de detección de abreviación en Blackstone busca abordar esto implementando una versión muy ligeramente modificada de AbbreviationDetector() (que es una implementación del enfoque establecido en este documento: https://psb.stanford.edu/psb-online/proceptings/Psb03/schwartz.pdf). Nuestra implementación todavía tiene algunos problemas, pero un ejemplo de su uso es el siguiente:
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 El componente de detección de referencia de caso compuesto en Blackstone está diseñado para casarse con entidades CITATION con sus entidades CASENAME matriz.
Las jurisdicciones de derecho consuetudinario generalmente se relacionan con las referencias de casos a través de un acoplamiento de un nombre (generalmente derivado de los nombres de las partes en el caso) y alguna cita única para identificar dónde se ha informado el caso, así:
Regina v Horncastle [2010] 2 AC 373
El modelo NER de Blackstone intenta identificar las entidades de CASENAME y CITATION . Sin embargo, es potencialmente útil (particularmente en el contexto de la extracción de información) extraer estas entidades como pares.
CompoundCases() aplica una tubería personalizada después del NER e identifica los pares de CASENAME / CITATION en dos escenarios:
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 El enlazador de la legislación de Blackstone intenta acoplar una referencia a una PROVISION a su INSTRUMENT principal utilizando el modelo NER para identificar la presencia de un INSTRUMENT y luego navegar por el árbol de dependencia para identificar la disposición del niño.
Una vez que Blackstone haya identificado una PROVISION : par INSTRUMENT , intentará generar URL objetivo tanto para la disposición como en el instrumento en Legislation.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 / contentsBlackstone se envía con un segmento de oraciones basado en reglas personalizado que aborda una variedad de características inherentes a los textos legales que tienden a desconcertar reglas de segmentación de oraciones listas para usar.
Este comportamiento se puede extender al pasar opcionalmente una lista de patrones de matcher de estilo Spacy que evitará explícitamente la detección de límites de oraciones dentro de los partidos.
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 )Nos gustaría agradecer a las siguientes personas/organizaciones que nos han ayudado (directa o indirectamente) a construir este prototipo.