2024-07-10 23:20:06 +01:00
|
|
|
|
|
|
|
|
"""
|
2024-12-30 12:53:19 +00:00
|
|
|
Simple decoder, accepts text chunks input, applies entity
|
2024-07-12 15:12:40 +01:00
|
|
|
relationship analysis to get entity relationship edges which are output as
|
|
|
|
|
graph edges.
|
2024-07-10 23:20:06 +01:00
|
|
|
"""
|
|
|
|
|
|
2025-04-22 20:21:38 +01:00
|
|
|
import json
|
2025-07-30 23:18:38 +01:00
|
|
|
import logging
|
2024-07-10 23:20:06 +01:00
|
|
|
import urllib.parse
|
|
|
|
|
|
2025-07-30 23:18:38 +01:00
|
|
|
# Module logger
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
2024-12-30 12:53:19 +00:00
|
|
|
from .... schema import Chunk, Triple, Triples
|
2026-01-27 13:48:08 +00:00
|
|
|
from .... schema import Metadata, Term, IRI, LITERAL
|
2025-04-22 20:21:38 +01:00
|
|
|
from .... schema import PromptRequest, PromptResponse
|
2024-10-23 18:04:04 +01:00
|
|
|
from .... rdf import RDF_LABEL, TRUSTGRAPH_ENTITIES, SUBJECT_OF
|
2025-04-22 20:21:38 +01:00
|
|
|
|
|
|
|
|
from .... base import FlowProcessor, ConsumerSpec, ProducerSpec
|
|
|
|
|
from .... base import PromptClientSpec
|
2024-07-10 23:20:06 +01:00
|
|
|
|
2026-01-27 13:48:08 +00:00
|
|
|
RDF_LABEL_VALUE = Term(type=IRI, iri=RDF_LABEL)
|
|
|
|
|
SUBJECT_OF_VALUE = Term(type=IRI, iri=SUBJECT_OF)
|
2024-07-10 23:20:06 +01:00
|
|
|
|
2025-04-22 20:21:38 +01:00
|
|
|
default_ident = "kg-extract-relationships"
|
2025-06-04 11:45:21 +01:00
|
|
|
default_concurrency = 1
|
2026-02-16 17:38:03 +00:00
|
|
|
default_triples_batch_size = 50
|
2024-07-15 17:17:04 +01:00
|
|
|
|
2025-04-22 20:21:38 +01:00
|
|
|
class Processor(FlowProcessor):
|
2024-07-10 23:20:06 +01:00
|
|
|
|
2024-07-18 17:20:42 +01:00
|
|
|
def __init__(self, **params):
|
|
|
|
|
|
2025-04-22 20:21:38 +01:00
|
|
|
id = params.get("id")
|
2025-06-04 11:45:21 +01:00
|
|
|
concurrency = params.get("concurrency", 1)
|
2026-02-16 17:38:03 +00:00
|
|
|
self.triples_batch_size = params.get("triples_batch_size", default_triples_batch_size)
|
2024-07-10 23:20:06 +01:00
|
|
|
|
2024-07-17 16:56:47 +01:00
|
|
|
super(Processor, self).__init__(
|
2024-07-18 17:20:42 +01:00
|
|
|
**params | {
|
2025-04-22 20:21:38 +01:00
|
|
|
"id": id,
|
2025-06-04 11:45:21 +01:00
|
|
|
"concurrency": concurrency,
|
2024-07-18 17:20:42 +01:00
|
|
|
}
|
2024-07-10 23:20:06 +01:00
|
|
|
)
|
|
|
|
|
|
2025-04-22 20:21:38 +01:00
|
|
|
self.register_specification(
|
|
|
|
|
ConsumerSpec(
|
|
|
|
|
name = "input",
|
|
|
|
|
schema = Chunk,
|
2025-06-04 11:45:21 +01:00
|
|
|
handler = self.on_message,
|
|
|
|
|
concurrency = concurrency,
|
2025-04-22 20:21:38 +01:00
|
|
|
)
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
self.register_specification(
|
|
|
|
|
PromptClientSpec(
|
|
|
|
|
request_name = "prompt-request",
|
|
|
|
|
response_name = "prompt-response",
|
|
|
|
|
)
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
self.register_specification(
|
|
|
|
|
ProducerSpec(
|
|
|
|
|
name = "triples",
|
|
|
|
|
schema = Triples
|
|
|
|
|
)
|
2024-07-23 23:02:09 +01:00
|
|
|
)
|
2024-07-10 23:20:06 +01:00
|
|
|
|
|
|
|
|
def to_uri(self, text):
|
|
|
|
|
|
|
|
|
|
part = text.replace(" ", "-").lower().encode("utf-8")
|
|
|
|
|
quoted = urllib.parse.quote(part)
|
|
|
|
|
uri = TRUSTGRAPH_ENTITIES + quoted
|
|
|
|
|
|
|
|
|
|
return uri
|
|
|
|
|
|
2025-04-22 20:21:38 +01:00
|
|
|
async def emit_triples(self, pub, metadata, triples):
|
2024-07-10 23:20:06 +01:00
|
|
|
|
2024-10-23 18:04:04 +01:00
|
|
|
t = Triples(
|
|
|
|
|
metadata=metadata,
|
|
|
|
|
triples=triples,
|
|
|
|
|
)
|
2025-04-22 20:21:38 +01:00
|
|
|
await pub.send(t)
|
2024-07-10 23:20:06 +01:00
|
|
|
|
2025-04-22 20:21:38 +01:00
|
|
|
async def on_message(self, msg, consumer, flow):
|
2024-07-10 23:20:06 +01:00
|
|
|
|
2024-07-17 16:56:47 +01:00
|
|
|
v = msg.value()
|
2025-07-30 23:18:38 +01:00
|
|
|
logger.info(f"Extracting relationships from {v.metadata.id}...")
|
2024-07-10 23:20:06 +01:00
|
|
|
|
2024-07-17 16:56:47 +01:00
|
|
|
chunk = v.chunk.decode("utf-8")
|
2024-07-10 23:20:06 +01:00
|
|
|
|
2025-07-30 23:18:38 +01:00
|
|
|
logger.debug(f"Processing chunk: {chunk[:100]}..." if len(chunk) > 100 else f"Processing chunk: {chunk}")
|
2025-04-22 20:21:38 +01:00
|
|
|
|
2024-07-17 16:56:47 +01:00
|
|
|
try:
|
2024-07-10 23:20:06 +01:00
|
|
|
|
2025-04-22 20:21:38 +01:00
|
|
|
try:
|
|
|
|
|
|
|
|
|
|
rels = await flow("prompt-request").extract_relationships(
|
|
|
|
|
text = chunk
|
|
|
|
|
)
|
|
|
|
|
|
2025-07-30 23:18:38 +01:00
|
|
|
logger.debug(f"Prompt response: {rels}")
|
2025-04-22 20:21:38 +01:00
|
|
|
|
|
|
|
|
if type(rels) != list:
|
|
|
|
|
raise RuntimeError("Expecting array in prompt response")
|
|
|
|
|
|
|
|
|
|
except Exception as e:
|
2025-07-30 23:18:38 +01:00
|
|
|
logger.error(f"Prompt exception: {e}", exc_info=True)
|
2025-04-22 20:21:38 +01:00
|
|
|
raise e
|
2024-07-17 16:56:47 +01:00
|
|
|
|
2024-10-23 18:04:04 +01:00
|
|
|
triples = []
|
|
|
|
|
|
2026-03-05 18:36:10 +00:00
|
|
|
# Get chunk document ID for provenance linking
|
|
|
|
|
chunk_doc_id = v.document_id if v.document_id else v.metadata.id
|
|
|
|
|
chunk_uri = v.metadata.id # The URI form for the chunk
|
|
|
|
|
|
|
|
|
|
# Note: Document metadata is now emitted once by librarian at processing
|
|
|
|
|
# initiation, so we don't need to duplicate it here.
|
2024-10-23 18:04:04 +01:00
|
|
|
|
2024-07-17 16:56:47 +01:00
|
|
|
for rel in rels:
|
|
|
|
|
|
2025-04-22 20:21:38 +01:00
|
|
|
s = rel["subject"]
|
|
|
|
|
p = rel["predicate"]
|
|
|
|
|
o = rel["object"]
|
2024-07-17 16:56:47 +01:00
|
|
|
|
2024-07-25 22:44:51 +01:00
|
|
|
if s == "": continue
|
|
|
|
|
if p == "": continue
|
|
|
|
|
if o == "": continue
|
|
|
|
|
|
2024-08-26 10:52:39 +01:00
|
|
|
if s is None: continue
|
|
|
|
|
if p is None: continue
|
|
|
|
|
if o is None: continue
|
|
|
|
|
|
2024-07-17 16:56:47 +01:00
|
|
|
s_uri = self.to_uri(s)
|
2026-01-27 13:48:08 +00:00
|
|
|
s_value = Term(type=IRI, iri=str(s_uri))
|
2024-07-17 16:56:47 +01:00
|
|
|
|
|
|
|
|
p_uri = self.to_uri(p)
|
2026-01-27 13:48:08 +00:00
|
|
|
p_value = Term(type=IRI, iri=str(p_uri))
|
2024-07-17 16:56:47 +01:00
|
|
|
|
2026-01-27 13:48:08 +00:00
|
|
|
if rel["object-entity"]:
|
2024-07-17 16:56:47 +01:00
|
|
|
o_uri = self.to_uri(o)
|
2026-01-27 13:48:08 +00:00
|
|
|
o_value = Term(type=IRI, iri=str(o_uri))
|
2024-07-17 16:56:47 +01:00
|
|
|
else:
|
2026-01-27 13:48:08 +00:00
|
|
|
o_value = Term(type=LITERAL, value=str(o))
|
2024-07-17 16:56:47 +01:00
|
|
|
|
2024-10-23 18:04:04 +01:00
|
|
|
triples.append(Triple(
|
|
|
|
|
s=s_value,
|
|
|
|
|
p=p_value,
|
|
|
|
|
o=o_value
|
|
|
|
|
))
|
2024-07-17 16:56:47 +01:00
|
|
|
|
|
|
|
|
# Label for s
|
2024-10-23 18:04:04 +01:00
|
|
|
triples.append(Triple(
|
|
|
|
|
s=s_value,
|
|
|
|
|
p=RDF_LABEL_VALUE,
|
2026-01-27 13:48:08 +00:00
|
|
|
o=Term(type=LITERAL, value=str(s))
|
2024-10-23 18:04:04 +01:00
|
|
|
))
|
2024-07-17 16:56:47 +01:00
|
|
|
|
|
|
|
|
# Label for p
|
2024-10-23 18:04:04 +01:00
|
|
|
triples.append(Triple(
|
|
|
|
|
s=p_value,
|
|
|
|
|
p=RDF_LABEL_VALUE,
|
2026-01-27 13:48:08 +00:00
|
|
|
o=Term(type=LITERAL, value=str(p))
|
2024-10-23 18:04:04 +01:00
|
|
|
))
|
2024-07-17 16:56:47 +01:00
|
|
|
|
2025-04-22 20:21:38 +01:00
|
|
|
if rel["object-entity"]:
|
2024-07-17 16:56:47 +01:00
|
|
|
# Label for o
|
2024-10-23 18:04:04 +01:00
|
|
|
triples.append(Triple(
|
|
|
|
|
s=o_value,
|
|
|
|
|
p=RDF_LABEL_VALUE,
|
2026-01-27 13:48:08 +00:00
|
|
|
o=Term(type=LITERAL, value=str(o))
|
2024-10-23 18:04:04 +01:00
|
|
|
))
|
|
|
|
|
|
2026-03-05 18:36:10 +00:00
|
|
|
# Link entity to chunk (not top-level document)
|
2024-10-23 18:04:04 +01:00
|
|
|
triples.append(Triple(
|
|
|
|
|
s=s_value,
|
|
|
|
|
p=SUBJECT_OF_VALUE,
|
2026-03-05 18:36:10 +00:00
|
|
|
o=Term(type=IRI, iri=chunk_uri)
|
2024-10-23 18:04:04 +01:00
|
|
|
))
|
|
|
|
|
|
2025-04-22 20:21:38 +01:00
|
|
|
if rel["object-entity"]:
|
2026-03-05 18:36:10 +00:00
|
|
|
# Link object entity to chunk
|
2024-10-23 18:04:04 +01:00
|
|
|
triples.append(Triple(
|
|
|
|
|
s=o_value,
|
2024-10-29 21:18:02 +00:00
|
|
|
p=SUBJECT_OF_VALUE,
|
2026-03-05 18:36:10 +00:00
|
|
|
o=Term(type=IRI, iri=chunk_uri)
|
2024-10-23 18:04:04 +01:00
|
|
|
))
|
2024-07-17 16:56:47 +01:00
|
|
|
|
2026-02-16 17:38:03 +00:00
|
|
|
# Send triples in batches
|
|
|
|
|
for i in range(0, len(triples), self.triples_batch_size):
|
|
|
|
|
batch = triples[i:i + self.triples_batch_size]
|
2026-02-09 14:57:36 +00:00
|
|
|
await self.emit_triples(
|
|
|
|
|
flow("triples"),
|
|
|
|
|
Metadata(
|
|
|
|
|
id=v.metadata.id,
|
|
|
|
|
metadata=[],
|
|
|
|
|
user=v.metadata.user,
|
|
|
|
|
collection=v.metadata.collection,
|
|
|
|
|
),
|
2026-02-16 17:38:03 +00:00
|
|
|
batch
|
2026-02-09 14:57:36 +00:00
|
|
|
)
|
2024-10-23 18:04:04 +01:00
|
|
|
|
2024-07-17 16:56:47 +01:00
|
|
|
except Exception as e:
|
2025-07-30 23:18:38 +01:00
|
|
|
logger.error(f"Relationship extraction exception: {e}", exc_info=True)
|
2024-07-10 23:20:06 +01:00
|
|
|
|
2025-07-30 23:18:38 +01:00
|
|
|
logger.debug("Relationship extraction complete")
|
2024-07-10 23:20:06 +01:00
|
|
|
|
2024-07-17 16:56:47 +01:00
|
|
|
@staticmethod
|
|
|
|
|
def add_args(parser):
|
2024-07-10 23:20:06 +01:00
|
|
|
|
2025-06-04 11:45:21 +01:00
|
|
|
parser.add_argument(
|
|
|
|
|
'-c', '--concurrency',
|
|
|
|
|
type=int,
|
|
|
|
|
default=default_concurrency,
|
|
|
|
|
help=f'Concurrent processing threads (default: {default_concurrency})'
|
|
|
|
|
)
|
|
|
|
|
|
2026-02-16 17:38:03 +00:00
|
|
|
parser.add_argument(
|
|
|
|
|
'--triples-batch-size',
|
|
|
|
|
type=int,
|
|
|
|
|
default=default_triples_batch_size,
|
|
|
|
|
help=f'Maximum triples per output message (default: {default_triples_batch_size})'
|
|
|
|
|
)
|
|
|
|
|
|
2025-04-22 20:21:38 +01:00
|
|
|
FlowProcessor.add_args(parser)
|
2024-08-05 22:10:18 +01:00
|
|
|
|
2024-07-10 23:20:06 +01:00
|
|
|
def run():
|
|
|
|
|
|
2025-04-22 20:21:38 +01:00
|
|
|
Processor.launch(default_ident, __doc__)
|
2024-07-10 23:20:06 +01:00
|
|
|
|