Extract knowledge from raw text

Overview

Extract knowledge from raw text

This repository is a nearly copy-paste of "From Text to Knowledge: The Information Extraction Pipeline" with some cosmetic updates. I made an installable version to evaluate it easily. The original code is available @ trinity-ie. To create some value, I added the Luke model to predict relations between entities. Luke is a transformer (same family as Bert), its particularity is that during its pre-training, it trains parameters dedicated to entities within the attention mechanism. Luke is in fact a very efficient model on entity-related tasks. We use here the version of Luke fine-tuned on the dataset TACRED.

In this blog post, Tomaz Bratanic presents a complete pipeline for extracting triples from raw text. The first step of the pipeline is to resolve the coreferences. The second step of the pipeline is to identify entities using the Wikifier API. Finally, Tomaz Bratanic proposes to use the Opennre library to extract relations between entities within the text.

🔧 Installation

pip install git+https://github.com/raphaelsty/textokb --upgrade

You will have to download spacy en model to do coreference resolution:

pip install spacy==2.1.0 && python -m spacy download en

Quick start

>> device = "cpu" # or device = "cuda" if you do own a gpu. >>> pipeline = pipeline.TextToKnowledge(key="jueidnxsctiurpwykpumtsntlschpx", types=types, device=device) >>> text = """Elon Musk is a business magnate, industrial designer, and engineer. He is the founder, ... CEO, CTO, and chief designer of SpaceX. He is also early investor, CEO, and product architect of ... Tesla, Inc. He is also the founder of The Boring Company and the co-founder of Neuralink. A ... centibillionaire, Musk became the richest person in the world in January 2021, with an estimated ... net worth of $185 billion at the time, surpassing Jeff Bezos. Musk was born to a Canadian mother ... and South African father and raised in Pretoria, South Africa. He briefly attended the University ... of Pretoria before moving to Canada aged 17 to attend Queen's University. He transferred to the ... University of Pennsylvania two years later, where he received dual bachelor's degrees in economics ... and physics. He moved to California in 1995 to attend Stanford University, but decided instead to ... pursue a business career. He went on co-founding a web software company Zip2 with his brother ... Kimbal Musk.""" >>> pipeline.process_sentence(text = text) head relation tail score 0 Tesla, Inc. architect Elon Musk 0.803398 1 Tesla, Inc. field of work The Boring Company 0.733903 2 Elon Musk residence University of Pennsylvania 0.648434 3 Elon Musk field of work The Boring Company 0.592007 4 Elon Musk manufacturer Tesla, Inc. 0.553206 5 The Boring Company manufacturer Tesla, Inc. 0.515352 6 Elon Musk developer Kimbal Musk 0.475639 7 University of Pennsylvania subsidiary Elon Musk 0.435384 8 The Boring Company developer Elon Musk 0.387753 9 SpaceX winner Elon Musk 0.374090 10 Kimbal Musk sibling Elon Musk 0.355944 11 Elon Musk manufacturer SpaceX 0.221294 ">
>>> from textokb import pipeline

# A list of types of entities that I search:
>>> types = [
...   "human", 
...   "person", 
...   "company", 
...   "enterprise", 
...   "business", 
...   "geographic region", 
...   "human settlement", 
...   "geographic entity", 
...   "territorial entity type", 
...   "organization",
... ]

>>> device = "cpu" # or device = "cuda" if you do own a gpu.

>>> pipeline = pipeline.TextToKnowledge(key="jueidnxsctiurpwykpumtsntlschpx", types=types, device=device)

>>> text = """Elon Musk is a business magnate, industrial designer, and engineer. He is the founder, 
... CEO, CTO, and chief designer of SpaceX. He is also early investor, CEO, and product architect of 
... Tesla, Inc. He is also the founder of The Boring Company and the co-founder of Neuralink. A 
... centibillionaire, Musk became the richest person in the world in January 2021, with an estimated 
... net worth of $185 billion at the time, surpassing Jeff Bezos. Musk was born to a Canadian mother 
... and South African father and raised in Pretoria, South Africa. He briefly attended the University 
... of Pretoria before moving to Canada aged 17 to attend Queen's University. He transferred to the 
... University of Pennsylvania two years later, where he received dual bachelor's degrees in economics 
... and physics. He moved to California in 1995 to attend Stanford University, but decided instead to 
... pursue a business career. He went on co-founding a web software company Zip2 with his brother 
... Kimbal Musk."""

>>> pipeline.process_sentence(text = text)
                          head       relation                        tail     score
0                  Tesla, Inc.      architect                   Elon Musk  0.803398
1                  Tesla, Inc.  field of work          The Boring Company  0.733903
2                    Elon Musk      residence  University of Pennsylvania  0.648434
3                    Elon Musk  field of work          The Boring Company  0.592007
4                    Elon Musk   manufacturer                 Tesla, Inc.  0.553206
5           The Boring Company   manufacturer                 Tesla, Inc.  0.515352
6                    Elon Musk      developer                 Kimbal Musk  0.475639
7   University of Pennsylvania     subsidiary                   Elon Musk  0.435384
8           The Boring Company      developer                   Elon Musk  0.387753
9                       SpaceX         winner                   Elon Musk  0.374090
10                 Kimbal Musk        sibling                   Elon Musk  0.355944
11                   Elon Musk   manufacturer                      SpaceX  0.221294

By default the model used is wiki80_cnn_softmax. I also added the model Luke (Language Understanding with Knowledge-based Embeddings) which provide a pre-trained models to do relation extraction. The results of the Luke model seem to be of better quality but the number of predicted relationships is smaller.

Here is how to use LUKE

>> device = "cpu" # or device = "cuda" if you do own a gpu. >>> pipeline = pipeline.TextToKnowledge(key="jueidnxsctiurpwykpumtsntlschpx", types=types, device=device, luke=True) >>> text = """Elon Musk is a business magnate, industrial designer, and engineer. He is the founder, ... CEO, CTO, and chief designer of SpaceX. He is also early investor, CEO, and product architect of ... Tesla, Inc. He is also the founder of The Boring Company and the co-founder of Neuralink. A ... centibillionaire, Musk became the richest person in the world in January 2021, with an estimated ... net worth of $185 billion at the time, surpassing Jeff Bezos. Musk was born to a Canadian mother ... and South African father and raised in Pretoria, South Africa. He briefly attended the University ... of Pretoria before moving to Canada aged 17 to attend Queen's University. He transferred to the ... University of Pennsylvania two years later, where he received dual bachelor's degrees in economics ... and physics. He moved to California in 1995 to attend Stanford University, but decided instead to ... pursue a business career. He went on co-founding a web software company Zip2 with his brother ... Kimbal Musk.""" >>> pipeline.process_sentence(text = text) head relation tail score 0 Elon Musk per:siblings Kimbal Musk 10.436224 1 Kimbal Musk per:siblings Elon Musk 10.040980 2 Elon Musk per:schools_attended University of Pennsylvania 9.808870 3 The Boring Company org:founded_by Elon Musk 8.823962 4 Elon Musk per:employee_of Tesla, Inc. 8.245111 5 SpaceX org:founded_by Elon Musk 7.795369 6 Elon Musk per:employee_of SpaceX 7.765485 7 Elon Musk per:employee_of The Boring Company 7.217330 8 Tesla, Inc. org:founded_by Elon Musk 7.002990 ">
>>> from textokb import pipeline

# A list of types of entities that I search:
>>> types = [
...   "human", 
...   "person", 
...   "company", 
...   "enterprise", 
...   "business", 
...   "geographic region", 
...   "human settlement", 
...   "geographic entity", 
...   "territorial entity type", 
...   "organization",
... ]

>>> device = "cpu" # or device = "cuda" if you do own a gpu.

>>> pipeline = pipeline.TextToKnowledge(key="jueidnxsctiurpwykpumtsntlschpx", types=types, device=device, luke=True)

>>> text = """Elon Musk is a business magnate, industrial designer, and engineer. He is the founder, 
... CEO, CTO, and chief designer of SpaceX. He is also early investor, CEO, and product architect of 
... Tesla, Inc. He is also the founder of The Boring Company and the co-founder of Neuralink. A 
... centibillionaire, Musk became the richest person in the world in January 2021, with an estimated 
... net worth of $185 billion at the time, surpassing Jeff Bezos. Musk was born to a Canadian mother 
... and South African father and raised in Pretoria, South Africa. He briefly attended the University 
... of Pretoria before moving to Canada aged 17 to attend Queen's University. He transferred to the 
... University of Pennsylvania two years later, where he received dual bachelor's degrees in economics 
... and physics. He moved to California in 1995 to attend Stanford University, but decided instead to 
... pursue a business career. He went on co-founding a web software company Zip2 with his brother 
... Kimbal Musk."""

>>> pipeline.process_sentence(text = text)
                 head              relation                        tail      score
0           Elon Musk          per:siblings                 Kimbal Musk  10.436224
1         Kimbal Musk          per:siblings                   Elon Musk  10.040980
2           Elon Musk  per:schools_attended  University of Pennsylvania   9.808870
3  The Boring Company        org:founded_by                   Elon Musk   8.823962
4           Elon Musk       per:employee_of                 Tesla, Inc.   8.245111
5              SpaceX        org:founded_by                   Elon Musk   7.795369
6           Elon Musk       per:employee_of                      SpaceX   7.765485
7           Elon Musk       per:employee_of          The Boring Company   7.217330
8         Tesla, Inc.        org:founded_by                   Elon Musk   7.002990

Here is the list of available relations using Luke studio-ousia/luke-large-finetuned-tacred:

[
    'no_relation',
    'org:alternate_names',
    'org:city_of_headquarters',
    'org:country_of_headquarters',
    'org:dissolved',
    'org:founded',
    'org:founded_by',
    'org:member_of',
    'org:members',
    'org:number_of_employees/members',
    'org:parents',
    'org:political/religious_affiliation',
    'org:shareholders',
    'org:stateorprovince_of_headquarters',
    'org:subsidiaries',
    'org:top_members/employees',
    'org:website',
    'per:age',
    'per:alternate_names',
    'per:cause_of_death',
    'per:charges',
    'per:children',
    'per:cities_of_residence',
    'per:city_of_birth',
    'per:city_of_death',
    'per:countries_of_residence',
    'per:country_of_birth',
    'per:country_of_death',
    'per:date_of_birth',
    'per:date_of_death',
    'per:employee_of',
    'per:origin',
    'per:other_family',
    'per:parents',
    'per:religion',
    'per:schools_attended',
    'per:siblings',
    'per:spouse',
    'per:stateorprovince_of_birth',
    'per:stateorprovince_of_death',
    'per:stateorprovinces_of_residence',
    'per:title'
]

Notes

The first time you initialize the model with Opennre or Luke, you may have to wait a few minutes for the model to download. Since we use the Wikifier API to track entities (NEL), it is necessary that your computer is connected to the internet. You can create your own credential for the API here: Wikifier API registration. Tomaz Bratanic mentions the possibility to replace Wikifier with BLINK however this library is very RAM intensive.

♻️ Work in progress

I failed to use the wiki80_bert_softmax model from Opennre due to a pre-trained model loading error (i.e. Tensorflow errors on Mac M1). I used the lighter model wiki80_cnn_softmax when reproducing Tomaz Bratanic's blog post. It would be interesting to be able to easily add different models and especially transformers. The API I used are not optimized for batch predictions. There are a lot of room for improvement by simply updating Opennre and Luke APIs.

You might also like...
Fixes mojibake and other glitches in Unicode text, after the fact.

ftfy: fixes text for you print(fix_encoding("(ง'⌣')ง")) (ง'⌣')ง Full documentation: https://ftfy.readthedocs.org Testimonials “My life is li

Paranoid text spacing in Python

pangu.py Paranoid text spacing for good readability, to automatically insert whitespace between CJK (Chinese, Japanese, Korean) and half-width charact

Markup is an online annotation tool that can be used to transform unstructured documents into structured formats for NLP and ML tasks, such as named-entity recognition. Markup learns as you annotate in order to predict and suggest complex annotations. Markup also provides integrated access to existing and custom ontologies, enabling the prediction and suggestion of ontology mappings based on the text you're annotating.
Markup is an online annotation tool that can be used to transform unstructured documents into structured formats for NLP and ML tasks, such as named-entity recognition. Markup learns as you annotate in order to predict and suggest complex annotations. Markup also provides integrated access to existing and custom ontologies, enabling the prediction and suggestion of ontology mappings based on the text you're annotating.

Markup is an online annotation tool that can be used to transform unstructured documents into structured formats for NLP and ML tasks, such as named-entity recognition. Markup learns as you annotate in order to predict and suggest complex annotations. Markup also provides integrated access to existing and custom ontologies, enabling the prediction and suggestion of ontology mappings based on the text you're annotating.

🐸   Identify anything. pyWhat easily lets you identify emails, IP addresses, and more. Feed it a .pcap file or some text and it'll tell you what it is! 🧙‍♀️
🐸 Identify anything. pyWhat easily lets you identify emails, IP addresses, and more. Feed it a .pcap file or some text and it'll tell you what it is! 🧙‍♀️

🐸 Identify anything. pyWhat easily lets you identify emails, IP addresses, and more. Feed it a .pcap file or some text and it'll tell you what it is! 🧙‍♀️

box is a text-based visual programming language inspired by Unreal Engine Blueprint function graphs.
box is a text-based visual programming language inspired by Unreal Engine Blueprint function graphs.

Box is a text-based visual programming language inspired by Unreal Engine blueprint function graphs. $ cat factorial.box ┌─ƒ(Factorial)───┐

Export solved codewars kata challenges to a text file.

Codewars Kata Exporter Note:this is not totally my work.i've edited the project to make more easier and faster for me.you can find the original work h

AnnIE - Annotation Platform, tool for open information extraction annotations using text files.
AnnIE - Annotation Platform, tool for open information extraction annotations using text files.

AnnIE - Annotation Platform, tool for open information extraction annotations using text files.

py-trans is a Free Python library for translate text into different languages.

Free Python library to translate text into different languages.

A production-ready pipeline for text mining and subject indexing

A production-ready pipeline for text mining and subject indexing

Releases(0.0.1)
Owner
Raphael Sourty
PhD Student @ IRIT and Renault
Raphael Sourty
The Levenshtein Python C extension module contains functions for fast computation of Levenshtein distance and string similarity

Contents Maintainer wanted Introduction Installation Documentation License History Source code Authors Maintainer wanted I am looking for a new mainta

Antti Haapala 1.2k Dec 16, 2022
An online markdown resume template project, based on pywebio

An online markdown resume template project, based on pywebio

极简XksA 5 Nov 10, 2022
Parse Any Text With Python

ParseAnyText A small package to parse strings. What is the work of it? Well It's a module to creates parser that helps to parse a text easily with les

Sayam Goswami 1 Jan 11, 2022
PyNews 📰 Simple newsletter made with python 🐍🗞️

PyNews 📰 Simple newsletter made with python Install dependencies This project has some dependencies (see requirements.txt) that are not included in t

Luciano Felix 4 Aug 21, 2022
Repository containing the code for An-Gocair text normaliser

Scottish Gaelic Text Normaliser The following project contains the code and resources for the Scottish Gaelic text normalisation project. The repo can

3 Jun 28, 2022
Add your new words to a text file and get them randomly.

Memorize-New-Words In this very very very little project, I've wrote a code to memorize new english words. Therefore you can add the words and their m

Mostafa 2 Jul 04, 2022
A Python3 script that simulates the user typing a text on their keyboard.

A Python3 script that simulates the user typing a text on their keyboard. (control the speed, randomness, rate of typos and more!)

Jose Gracia Berenguer 3 Feb 22, 2022
Little python script + dictionary to help solve Wordle puzzles

Wordle Solver Little python script + dictionary to help solve Wordle puzzles Usage Usage: ./wordlesolver.py [letters in word] [letters not in word] [p

Luke Stephens (hakluke) 4 Jul 24, 2022
This script has been created in order to find what are the most common demanded technologies in Data Engineering field.

This is a Python script that given a whole corpus of job descriptions and a file with keywords it extracts the number of number of ocurrences of these keywords and write it to a file. This script it

Antonio Bri Pérez 0 Jul 17, 2022
一个可以可以统计群组用户发言,并且能将聊天内容生成词云的机器人

当前版本 v2.2 更新维护日志 更新维护日志 有问题请加群组反馈 Telegram 交流反馈群组 点击加入 演示 配置要求 内存:1G以上 安装方法 使用 Docker 安装 Docker官方安装

机器人总动员 117 Dec 29, 2022
ChirpText is a collection of text processing tools for Python 3.

ChirpText is a collection of text processing tools for Python 3. It is not meant to be a powerful tank like the popular NTLK but a small package which

Le Tuan Anh 5 Nov 30, 2022
Returns unicode slugs

Python Slugify A Python slugify application that handles unicode. Overview Best attempt to create slugs from unicode strings while keeping it DRY. Not

Val Neekman 1.3k Jan 04, 2023
A Python package to facilitate research on building and evaluating automated scoring models.

Rater Scoring Modeling Tool Introduction Automated scoring of written and spoken test responses is a growing field in educational natural language pro

ETS 59 Oct 10, 2022
This is REST-API for Indonesian Text Summarization using Non-Negative Matrix Factorization for the algorithm to summarize documents and FastAPI for the framework.

Indonesian Text Summarization Using FastAPI This is REST-API for Indonesian Text Summarization using Non-Negative Matrix Factorization for the algorit

Viqi Nurhaqiqi 2 Nov 03, 2022
Maiden & Spell community player ranking based on tournament data.

MnSRank Maiden & Spell community player ranking based on tournament data. Why? 2021 just ended and this seemed like a cool idea. Elo doesn't work well

Jonathan Lee 1 Apr 20, 2022
Meeting, rendezvous, confluence (Finnish kohtaaminen) mark up, down, and up again.

kohtaaminen Meeting, rendezvous, confluence (Finnish kohtaaminen) mark up, down, and up again. Given a zip file containing a tree of html and media fi

Stefan Hagen 2 Dec 14, 2022
🍋 A Python package to process food

Pyfood is a simple Python package to process food, in different languages. Pyfood's ambition is to be the go-to library to deal with food, recipes, on

Local Seasonal 8 Apr 04, 2022
Convert text to morse code and play morse code sound.

Convert text(english) to morse codes and play morse sound!

Mohammad Dori 5 Jul 15, 2022
Fuzzy String Matching in Python

FuzzyWuzzy Fuzzy string matching like a boss. It uses Levenshtein Distance to calculate the differences between sequences in a simple-to-use package.

SeatGeek 8.8k Jan 08, 2023
Adventura is an open source Python Text Adventure Engine

Adventura Adventura is an open source Python Text Adventure Engine, Not yet uplo

5 Oct 02, 2022