Repository navigation
Expand file tree
/
Copy pathgraph_builder.py
More file actions
210 lines (193 loc) · 7.94 KB
/
Copy pathgraph_builder.py
File metadata and controls
210 lines (193 loc) · 7.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
"""
Loads structured extraction output (see extraction.py) into Neo4j as a
connected graph of Vendors, Invoices, Transactions, Documents, and Flags.
Also runs lightweight duplicate detection at load time: if a transaction or
invoice with the same vendor, amount, and date already exists, it raises a
"duplicate" Flag instead of silently creating a second identical node.
"""
import hashlib
import uuid
from neo4j import GraphDatabase
import config
class GraphBuilder:
def __init__(self, driver=None):
self._owns_driver = driver is None
self.driver = driver or GraphDatabase.driver(
config.NEO4J_URI, auth=(config.NEO4J_USER, config.NEO4J_PASSWORD)
)
def close(self):
if self._owns_driver:
self.driver.close()
def __enter__(self):
return self
def __exit__(self, *exc):
self.close()
def already_ingested(self, raw_text: str) -> bool:
"""Return True if a Document with this content hash already exists."""
h = hashlib.sha256(raw_text.encode()).hexdigest()
with self.driver.session() as session:
return session.run(
"MATCH (d:Document {content_hash: $h}) RETURN d LIMIT 1", h=h
).single() is not None
def load_extraction(self, extraction: dict, raw_text: str):
"""Write one document's extracted entities/relationships into the graph,
then populate the context layer (Person, Topic, TimePeriod nodes)."""
from context_graph import ContextBuilder
with self.driver.session() as session:
session.execute_write(self._write_document, extraction, raw_text)
ContextBuilder(self.driver).load_context(extraction, raw_text)
# --- internal write transaction ---
@staticmethod
def _write_document(tx, extraction: dict, raw_text: str):
source_id = extraction["source_id"]
tx.run(
"""
MERGE (d:Document {source_id: $source_id})
SET d.document_type = $document_type,
d.ingested_on = $ingested_on,
d.raw_text = $raw_text,
d.content_hash = $content_hash
""",
source_id=source_id,
document_type=extraction.get("document_type", "other"),
ingested_on=extraction["ingested_on"],
raw_text=raw_text,
content_hash=hashlib.sha256(raw_text.encode()).hexdigest(),
)
for vendor in extraction.get("vendors", []):
tx.run(
"""
MERGE (v:Vendor {name: $name})
WITH v
MATCH (d:Document {source_id: $source_id})
MERGE (d)-[:MENTIONS]->(v)
""",
name=vendor["name"],
source_id=source_id,
)
for inv in extraction.get("invoices", []):
inv_id = inv.get("invoice_id") or str(uuid.uuid4())
tx.run(
"""
MERGE (i:Invoice {invoice_id: $invoice_id})
SET i.amount = $amount,
i.currency = $currency,
i.issue_date = $issue_date,
i.due_date = $due_date,
i.status = $status
WITH i
MATCH (d:Document {source_id: $source_id})
MERGE (d)-[:MENTIONS]->(i)
""",
invoice_id=inv_id,
amount=inv.get("amount"),
currency=inv.get("currency"),
issue_date=inv.get("issue_date"),
due_date=inv.get("due_date"),
status=inv.get("status"),
source_id=source_id,
)
if inv.get("vendor_name"):
tx.run(
"""
MERGE (v:Vendor {name: $vendor_name})
WITH v
MATCH (i:Invoice {invoice_id: $invoice_id})
MERGE (i)-[:BILLED_BY]->(v)
""",
vendor_name=inv["vendor_name"],
invoice_id=inv_id,
)
for txn in extraction.get("transactions", []):
txn_id = txn.get("id") or str(uuid.uuid4())
tx.run(
"""
MERGE (t:Transaction {id: $id})
SET t.description = $description,
t.category = $category,
t.amount = $amount,
t.currency = $currency,
t.date = $date,
t.type = $type
WITH t
MATCH (d:Document {source_id: $source_id})
MERGE (d)-[:MENTIONS]->(t)
""",
id=txn_id,
description=txn.get("description"),
category=txn.get("category"),
amount=txn.get("amount"),
currency=txn.get("currency"),
date=txn.get("date"),
type=txn.get("type"),
source_id=source_id,
)
if txn.get("vendor_name"):
tx.run(
"""
MERGE (v:Vendor {name: $vendor_name})
WITH v
MATCH (t:Transaction {id: $id})
MERGE (t)-[:PAID_TO]->(v)
""",
vendor_name=txn["vendor_name"],
id=txn_id,
)
# Duplicate detection: same vendor + amount + date already in the graph
if txn.get("vendor_name") and txn.get("amount") and txn.get("date"):
dup = tx.run(
"""
MATCH (t:Transaction {date: $date, amount: $amount})-[:PAID_TO]->(v:Vendor {name: $vendor_name})
WHERE t.id <> $id
RETURN t.id AS existing_id
""",
date=txn["date"],
amount=txn["amount"],
vendor_name=txn["vendor_name"],
id=txn_id,
).single()
if dup:
flag_id = str(uuid.uuid4())
tx.run(
"""
CREATE (f:Flag {id: $flag_id, type: 'duplicate',
description: $description})
WITH f
MATCH (t:Transaction {id: $id})
MATCH (d:Document {source_id: $source_id})
MERGE (f)-[:CONCERNS]->(t)
MERGE (d)-[:RAISED]->(f)
""",
flag_id=flag_id,
description=f"Possible duplicate of transaction {dup['existing_id']} "
f"(same vendor, amount, and date).",
id=txn_id,
source_id=source_id,
)
for flag in extraction.get("flags", []):
flag_id = str(uuid.uuid4())
tx.run(
"""
CREATE (f:Flag {id: $flag_id, type: $type, description: $description})
WITH f
MATCH (d:Document {source_id: $source_id})
MERGE (d)-[:RAISED]->(f)
""",
flag_id=flag_id,
type=flag.get("type", "other"),
description=flag.get("description", ""),
source_id=source_id,
)
related = flag.get("related_entity")
if related:
tx.run(
"""
MATCH (f:Flag {id: $flag_id})
OPTIONAL MATCH (i:Invoice {invoice_id: $related})
OPTIONAL MATCH (v:Vendor {name: $related})
FOREACH (_ IN CASE WHEN i IS NOT NULL THEN [1] ELSE [] END | MERGE (f)-[:CONCERNS]->(i))
FOREACH (_ IN CASE WHEN v IS NOT NULL THEN [1] ELSE [] END | MERGE (f)-[:CONCERNS]->(v))
""",
flag_id=flag_id,
related=related,
)