spacyfishing
repository·main·Indexed 41 days ago
https://github.com/lucaterre/spacyfishingA spaCy extension that integrates the entity-fishing tool into spaCy pipelines to perform named entity recognition (NER), linking, and disambiguation against the Wikidata knowledge base. It provides custom spaCy extensions on Doc and Span objects to access Wikidata QIDs, URLs, NERD scores, and additional metadata.
What's inside spacyfishing
- spacyfishing is a spaCy wrapper for entity-fishing. It functions as a spaCy pipeline component that enables named entity recognition (NER), linking, and disambiguation against the Wikidata knowledge base (KB). It works with both custom and pretrained spaCy NER models.
Install spacyfishing
mainYou can install
spacyfishingvia pip for standard usage, or clone the repository for development purposes.# Normal installation pip install spacyfishing # Development installation git clone https://github.com/Lucaterre/spacyfishing.git virtualenv --python=/usr/bin/python3.8 venv source venv/bin/activate pip install -r requirements_dev.txtInstall a spaCy language model for NER
mainBefore using
spacyfishing, you must install a pre-trained spaCy language model for the Named Entity Recognition (NER) task. You can use standard models likeen_core_web_smor your own custom NER models.python -m spacy download en_core_web_smConfigure the entity-fishing API endpoint
mainBy default,
spacyfishinguses the Science-Miner demo server. To avoid query limitations or to use a local/specific instance of the entity-fishing API (e.g., one running a more recent Wikidata dump), specify theapi_ef_baseparameter in the pipeline configuration.To install your own instance of the underlying entity-fishing service, refer to the entity-fishing build documentation.
nlp.add_pipe("entityfishing", config={"api_ef_base": "<api-endpoint>"})Use non-English languages with entity-fishing
mainBy default, the disambiguation model uses English. To process text in another language, specify the appropriate language code using the
languageparameter in theentityfishingcomponent configuration.Supported languages are documented in the NERD documentation.
import spacy text_fr = "La bataille d'El-Alamein en Égypte oppose la 8e armée britannique..." nlp_model_fr = spacy.load("fr_core_news_sm") # Specify the language code in the config nlp_model_fr.add_pipe("entityfishing", config={"language": "fr"}) doc_fr = nlp_model_fr(text_fr) for ent in doc_fr.ents: # Access Wikidata URL via ent._.url_wikidata print((ent.text, ent.label_, ent._.kb_qid, ent._.url_wikidata))Filter entity identifiers in configuration
mainYou can filter specific external identifiers (like Library of Congress or VIAF) to make the output more readable. To do this, set
extra_infotoTrueand provide a list of desired property IDs in thefilter_statementsparameter within theentityfishingcomponent configuration.Access the filtered identifiers via the
ent._.other_idsattribute on the spaCy entity object.import spacy text_en = "Victor Hugo and Honoré Balzac are French writers who lived in Paris." nlp_model_en = spacy.load("en_core_web_sm") # Configure to include extra info and filter for specific property IDs nlp_model_en.add_pipe("entityfishing", config={ "extra_info": True, "filter_statements": ['P214', 'P244'] }) doc_en = nlp_model_en(text_en) for ent in doc_en.ents: # ent._.other_ids contains the filtered identifiers print((ent.text, ent.label_, ent._.kb_qid, ent._.other_ids))Access Wikidata descriptions and metadata via ent._ attributes
mainWhen using
spacyfishing, you can access enriched metadata for entities using custom spaCy extensions on theSpanobject (theentindoc.ents).The following attributes are available on an entity via the
._underscore accessor:ent._.kb_qid: The Wikidata QID.ent._.normal_term: The normalized term.ent._.description: The description retrieved from Wikidata.ent._.src_description: The source description.ent._.other_ids: Other associated identifiers.
Example of iterating through entities to print this metadata:
for ent in doc_en.ents: print((ent.text, ent.label_, ent._.kb_qid, ent._.normal_term, ent._.description, ent._.src_description, ent._.other_ids))Use spacyfishing in a simple pipeline
mainTo use
spacyfishing, load a spaCy model and add theentityfishingcomponent to the pipeline usingnlp.add_pipe("entityfishing"). Once processed, you can access Wikidata-related metadata on each entity via custom spaCy extensions on theSpanobject.import spacy text_en = "Victor Hugo and Honoré de Balzac are French writers who lived in Paris." nlp_model_en = spacy.load("en_core_web_sm") nlp_model_en.add_pipe("entityfishing") doc_en = nlp_model_en(text_en) for ent in doc_en.ents: print((ent.text, ent.label_, ent._.kb_qid, ent._.url_wikidata, ent._.nerd_score))Process multiple documents using batching
mainFor better performance when processing multiple texts, use the
nlp.pipemethod. You can control the number of documents processed at once by setting thebatch_sizeparameter.import spacy texts_en = [ "Victor Hugo and Honoré de Balzac are French writers who lived in Paris.", "Momofuko Ando is Taiwanese Japanese Business Magnate that invented instant ramen." ] nlp_model_en = spacy.load("en_core_web_sm") nlp_model_en.add_pipe("entityfishing") # set number of documents to be processed at once via batch_size docs_en = nlp_model_en.pipe(texts_en, batch_size=128) for doc_en in docs_en: for ent in doc_en.ents: print((ent.text, ent.label_, ent._.kb_qid, ent._.url_wikidata, ent._.nerd_score))Visualize entity-fishing results with displaCy
mainYou can visualize named entities and their associated Wikidata links using spaCy's
displacy.servewith themanual=Trueoption. This requires constructing aparamsdictionary containing the text, entity metadata (includingkb_idandkb_url), and display options.import spacy text_fr = "La bataille d'El-Alamein en Égypte oppose la 8e armée britannique dirigée par Bernard Montgomery aux divisions d'Erwin Rommel." nlp_model_fr = spacy.load("fr_core_news_sm") nlp_model_fr.add_pipe("entityfishing", config={"language": "fr"}) doc_fr = nlp_model_fr(text_fr) options = { "ents": ["MISC", "LOC", "PER"], "colors": {"LOC": "#82e0aa", "PER": "#85c1e9", "MISC": "#f0b27a"} } params = {"text": doc_fr.text, "ents": [{"start": ent.start_char, "end": ent.end_char, "label": ent.label_, "kb_id": ent._.kb_qid, "kb_url": ent._.url_wikidata} for ent in doc_fr.ents], "title": None} spacy.displacy.serve(params, style="ent", manual=True, options=options)Access API metadata via doc._.metadata
mainYou can check the status of the entity-fishing API requests (e.g., status codes and success flags for both the disambiguation text and terms services) using the
._.metadataattribute on the spaCyDocobject.# Access metadata regarding the API service status metadata = doc._.metadataAccess raw entity-fishing API responses via doc._.annotations
mainThe full, raw JSON response from the entity-fishing API (including disambiguation text and terms services) is available on the spaCy
Docobject through the._.annotationsattribute.# Access the raw API response dictionary annotations = doc._.annotations