Build a python script that will take a pdf document, extract it's text chunk it, using semantic chunking with a max size of 600 tokens per chunk, extract entities and relationships per chunk and put them in neo4j
Assistant
Sure! Below is a Python script that takes a PDF document, extracts its text, chunks it using semantic chunking with a maximum size of 600 tokens per chunk, extracts entities and relationships per chunk, and inserts them into Neo4j.
Please make sure to install the required Python packages before running the script:
import spacy
from pdfminer.high_level import extract_text
from neo4j import GraphDatabase
# Load spaCy model once
nlp = spacy.load('en_core_web_sm')
nlp.add_pipe('sentencizer')
def extract_pdf_text(pdf_path):
"""
Extract text from a PDF file.
"""
return extract_text(pdf_path)
def chunk_text(text, max_tokens=600):
"""
Chunk text into semantically coherent chunks with a maximum of max_tokens tokens per chunk.
"""
doc = nlp(text)
sentences = [sent.text for sent in doc.sents]
chunks = []
current_chunk = ""
current_tokens = 0
for sentence in sentences:
sent_doc = nlp(sentence)
num_tokens = len(sent_doc)
# If adding the current sentence exceeds the max token limit, start a new chunk
if current_tokens + num_tokens > max_tokens:
if current_chunk:
chunks.append(current_chunk.strip())
current_chunk = sentence
current_tokens = num_tokens
else:
current_chunk += ' ' + sentence
current_tokens += num_tokens
# Add the last chunk
if current_chunk:
chunks.append(current_chunk.strip())
return chunks
def extract_entities_relationships(chunk):
"""
Extract entities and relationships from a text chunk.
"""
doc = nlp(chunk)
entities = set()
relationships = []
# Extract entities
for ent in doc.ents:
entities.add((ent.text, ent.label_))
# Extract relationships using dependency parsing
for sent in doc.sents:
for token in sent:
if token.dep_ == 'ROOT':
subject = [w.text for w in token.lefts if w.dep_ in ['nsubj', 'nsubjpass']]
obj = [w.text for w in token.rights if w.dep_ in ['dobj', 'attr', 'pobj']]
if subject and obj:
relationships.append((subject[0], token.lemma_, obj[0]))
return entities, relationships
def insert_entities_relationships(entities, relationships, neo4j_uri, neo4j_user, neo4j_password):
"""
Insert entities and relationships into Neo4j.
"""
driver = GraphDatabase.driver(neo4j_uri, auth=(neo4j_user, neo4j_password))
with driver.session() as session:
# Insert entities into Neo4j
for name, label in entities:
query = """
MERGE (e:Entity {name: $name})
SET e.label = $label
"""
session.run(query, name=name, label=label)
# Insert relationships into Neo4j
for subj, verb, obj in relationships:
query = """
MATCH (a:Entity {name: $subj})
MATCH (b:Entity {name: $obj})
MERGE (a)-[r:RELATION {type: $verb}]->(b)
"""
session.run(query, subj=subj, verb=verb, obj=obj)
driver.close()
def main(pdf_path, neo4j_uri, neo4j_user, neo4j_password):
"""
Main function to process the PDF and interact with Neo4j.
"""
# Extract text from the PDF
print("Extracting text from PDF...")
text = extract_pdf_text(pdf_path)
# Chunk the text
print("Chunking text...")
chunks = chunk_text(text, max_tokens=600)
# Process each chunk
for i, chunk in enumerate(chunks, 1):
print(f"Processing chunk {i}/{len(chunks)}...")
entities, relationships = extract_entities_relationships(chunk)
insert_entities_relationships(entities, relationships, neo4j_uri, neo4j_user, neo4j_password)
print("Data insertion into Neo4j completed.")
if __name__ == '__main__':
# Replace the placeholders with your actual PDF path and Neo4j credentials
pdf_path = 'path/to/your/document.pdf' # Replace with your PDF file path
neo4j_uri = 'bolt://localhost:7687' # Replace with your Neo4j URI
neo4j_user = 'neo4j' # Replace with your Neo4j username
neo4j_password = 'your_neo4j_password' # Replace with your Neo4j password
main(pdf_path, neo4j_uri, neo4j_user, neo4j_password)
How the Script Works:
Extract Text from PDF:
Uses pdfminer.six to extract text content from the PDF file.
Chunk the Text:
Splits the text into sentences using spaCy's Sentencizer.
Groups sentences into chunks, ensuring that each chunk has a semantic coherence and does not exceed 600 tokens.
Extract Entities and Relationships:
For each chunk, uses spaCy's NER to extract entities.
Uses dependency parsing to extract basic subject-verb-object relationships.
Insert into Neo4j:
Connects to a Neo4j database using the Bolt protocol.
Inserts entities as nodes and relationships as edges into the graph database.
Replace the placeholders in the if __name__ == '__main__': block with your actual PDF file path and Neo4j credentials.
Run the script using Python.
bash
python your_script_name.py
Notes:
Entity Uniqueness: The script assumes that entities are uniquely identified by their names. In cases where entity names are not unique, you may need to include additional properties to distinguish them.
Relationship Extraction: The relationship extraction in this script is basic and may not capture complex relationships. For more advanced extraction, consider integrating a more sophisticated NLP model or pipeline.
Error Handling: For production use, consider adding error handling, logging, and possibly multithreading or multiprocessing for performance improvements.
Neo4j Constraints: Ensure that your Neo4j database allows the creation of nodes and relationships as modeled in this script. You might need to set up appropriate indexes or constraints.
Example Output in Neo4j:
After running the script, you can visualize the entities and relationships using Neo4j Browser or any other Neo4j visualization tool.