You can download this code by clicking the button below.
This code is now available for download.
This function uses Flair's relation extraction model to extract relations from a given text. It first loads the pre-trained relation extraction model, then creates a Sentence object from the text, and performs relation extraction on the sentence. Finally, it extracts and prints out the relations.
Technology Stack : Flair, Relation Extraction Model
Code Type : Function
Code Difficulty : Intermediate
import random
import flair
import flair.models
import flair.data
import flair.data.relation_extraction
def extract_relations(text):
"""
Extracts relations from a given text using Flair's relation extraction model.
"""
# Load the pre-trained relation extraction model
relation_model = flair.models.relation_extraction.relation_extraction_model('en')
# Create a Sentence object from the text
sentence = flair.data.Sentence(text)
# Perform relation extraction on the sentence
relation_model.predict(sentence)
# Extract and print the relations
relations = [(rel.relation, rel.head, rel.dep, rel.dep_head) for rel in sentence.relations]
for rel in relations:
print(f"Relation: {rel[0]}, Head: {rel[1]}, Dep: {rel[2]}, Dep Head: {rel[3]}")
return relations