File size: 16,127 Bytes
2cc87ec 86277c0 2cc87ec 86277c0 2cc87ec efae5be 86277c0 efae5be 2cc87ec 86277c0 1681237 86277c0 2cc87ec efae5be 2cc87ec 1681237 2cc87ec efae5be 1681237 86277c0 2cc87ec 86277c0 efae5be 86277c0 1681237 fed112f 86277c0 1681237 86277c0 fed112f 86277c0 1681237 fed112f 1681237 86277c0 2cc87ec 1681237 86277c0 1681237 86277c0 1681237 86277c0 fed112f 86277c0 fed112f 86277c0 2cc87ec 1681237 2cc87ec 1681237 2cc87ec fed112f 2cc87ec fed112f 2cc87ec fed112f 1681237 2cc87ec |
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 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 |
import json
import logging
from typing import Iterable, Optional, Sequence, Union
import gradio as gr
import pandas as pd
from pie_datasets import Dataset, IterableDataset, load_dataset
from pie_modules.document.processing import RegexPartitioner, SpansViaRelationMerger
from pytorch_ie import Pipeline
from pytorch_ie.annotations import LabeledSpan
from pytorch_ie.auto import AutoPipeline
from pytorch_ie.documents import (
TextDocumentWithLabeledMultiSpansBinaryRelationsAndLabeledPartitions,
TextDocumentWithLabeledSpansBinaryRelationsAndLabeledPartitions,
)
from typing_extensions import Protocol
from src.langchain_modules import DocumentAwareSpanRetriever
from src.langchain_modules.span_retriever import (
DocumentAwareSpanRetrieverWithRelations,
_parse_config,
)
logger = logging.getLogger(__name__)
def annotate_document(
document: TextDocumentWithLabeledSpansBinaryRelationsAndLabeledPartitions,
argumentation_model: Pipeline,
handle_parts_of_same: bool = False,
) -> Union[
TextDocumentWithLabeledSpansBinaryRelationsAndLabeledPartitions,
TextDocumentWithLabeledMultiSpansBinaryRelationsAndLabeledPartitions,
]:
"""Annotate a document with the provided pipeline.
Args:
document: The document to annotate.
argumentation_model: The pipeline to use for annotation.
handle_parts_of_same: Whether to merge spans that are part of the same entity into a single multi span.
"""
# execute prediction pipeline
argumentation_model(document)
if handle_parts_of_same:
merger = SpansViaRelationMerger(
relation_layer="binary_relations",
link_relation_label="parts_of_same",
create_multi_spans=True,
result_document_type=TextDocumentWithLabeledMultiSpansBinaryRelationsAndLabeledPartitions,
result_field_mapping={
"labeled_spans": "labeled_multi_spans",
"binary_relations": "binary_relations",
"labeled_partitions": "labeled_partitions",
},
)
document = merger(document)
return document
def create_document(
text: str, doc_id: str, split_regex: Optional[str] = None
) -> TextDocumentWithLabeledSpansBinaryRelationsAndLabeledPartitions:
"""Create a TextDocumentWithLabeledSpansBinaryRelationsAndLabeledPartitions from the provided
text.
Parameters:
text: The text to process.
doc_id: The ID of the document.
split_regex: A regular expression pattern to use for splitting the text into partitions.
Returns:
The processed document.
"""
document = TextDocumentWithLabeledSpansBinaryRelationsAndLabeledPartitions(
id=doc_id, text=text, metadata={}
)
if split_regex is not None:
partitioner = RegexPartitioner(
pattern=split_regex, partition_layer_name="labeled_partitions"
)
document = partitioner(document)
else:
# add single partition from the whole text (the model only considers text in partitions)
document.labeled_partitions.append(LabeledSpan(start=0, end=len(text), label="text"))
return document
def add_annotated_pie_documents(
retriever: DocumentAwareSpanRetriever,
pie_documents: Sequence[TextDocumentWithLabeledMultiSpansBinaryRelationsAndLabeledPartitions],
use_predicted_annotations: bool,
verbose: bool = False,
) -> None:
if verbose:
gr.Info(f"Create span embeddings for {len(pie_documents)} documents...")
num_docs_before = len(retriever.docstore)
retriever.add_pie_documents(pie_documents, use_predicted_annotations=use_predicted_annotations)
# number of documents that were overwritten
num_overwritten_docs = num_docs_before + len(pie_documents) - len(retriever.docstore)
# warn if documents were overwritten
if num_overwritten_docs > 0:
gr.Warning(f"{num_overwritten_docs} documents were overwritten.")
def process_texts(
texts: Iterable[str],
doc_ids: Iterable[str],
argumentation_model: Pipeline,
retriever: DocumentAwareSpanRetriever,
split_regex_escaped: Optional[str],
handle_parts_of_same: bool = False,
verbose: bool = False,
) -> None:
# check that doc_ids are unique
if len(set(doc_ids)) != len(list(doc_ids)):
raise gr.Error("Document IDs must be unique.")
pie_documents = [
create_document(text=text, doc_id=doc_id, split_regex=split_regex_escaped)
for text, doc_id in zip(texts, doc_ids)
]
if verbose:
gr.Info(f"Annotate {len(pie_documents)} documents...")
pie_documents = [
annotate_document(
document=pie_document,
argumentation_model=argumentation_model,
handle_parts_of_same=handle_parts_of_same,
)
for pie_document in pie_documents
]
add_annotated_pie_documents(
retriever=retriever,
pie_documents=pie_documents,
use_predicted_annotations=True,
verbose=verbose,
)
def add_annotated_pie_documents_from_dataset(
retriever: DocumentAwareSpanRetriever, verbose: bool = False, **load_dataset_kwargs
) -> None:
try:
gr.Info(
"Loading PIE dataset with parameters:\n" + json.dumps(load_dataset_kwargs, indent=2)
)
dataset = load_dataset(**load_dataset_kwargs)
if not isinstance(dataset, (Dataset, IterableDataset)):
raise gr.Error("Loaded dataset is not of type PIE (Iterable)Dataset.")
dataset_converted = dataset.to_document_type(
TextDocumentWithLabeledMultiSpansBinaryRelationsAndLabeledPartitions
)
add_annotated_pie_documents(
retriever=retriever,
pie_documents=dataset_converted,
use_predicted_annotations=False,
verbose=verbose,
)
except Exception as e:
raise gr.Error(f"Failed to load dataset: {e}")
def load_argumentation_model(
model_name: str,
revision: Optional[str] = None,
device: str = "cpu",
) -> Pipeline:
try:
# the Pipeline class expects an integer for the device
if device == "cuda":
pipeline_device = 0
elif device.startswith("cuda:"):
pipeline_device = int(device.split(":")[1])
elif device == "cpu":
pipeline_device = -1
else:
raise gr.Error(f"Invalid device: {device}")
model = AutoPipeline.from_pretrained(
model_name,
device=pipeline_device,
num_workers=0,
taskmodule_kwargs=dict(revision=revision),
model_kwargs=dict(revision=revision),
)
gr.Info(
f"Loaded argumentation model: model_name={model_name}, revision={revision}, device={device}"
)
except Exception as e:
raise gr.Error(f"Failed to load argumentation model: {e}")
return model
def load_retriever(
retriever_config: str,
config_format: str,
device: str = "cpu",
previous_retriever: Optional[DocumentAwareSpanRetrieverWithRelations] = None,
) -> DocumentAwareSpanRetrieverWithRelations:
try:
retriever_config = _parse_config(retriever_config, format=config_format)
# set device for the embeddings pipeline
retriever_config["vectorstore"]["embedding"]["pipeline_kwargs"]["device"] = device
result = DocumentAwareSpanRetrieverWithRelations.instantiate_from_config(retriever_config)
# if a previous retriever is provided, load all documents and vectors from the previous retriever
if previous_retriever is not None:
# documents
all_doc_ids = list(previous_retriever.docstore.yield_keys())
gr.Info(f"Storing {len(all_doc_ids)} documents from previous retriever...")
all_docs = previous_retriever.docstore.mget(all_doc_ids)
result.docstore.mset([(doc.id, doc) for doc in all_docs])
# spans (with vectors)
all_span_ids = list(previous_retriever.vectorstore.yield_keys())
all_spans = previous_retriever.vectorstore.mget(all_span_ids)
result.vectorstore.mset([(span.id, span) for span in all_spans])
gr.Info("Retriever loaded successfully.")
return result
except Exception as e:
raise gr.Error(f"Failed to load retriever: {e}")
def retrieve_similar_spans(
retriever: DocumentAwareSpanRetriever,
query_span_id: str,
**kwargs,
) -> pd.DataFrame:
if not query_span_id.strip():
raise gr.Error("No query span selected.")
try:
retrieval_result = retriever.invoke(input=query_span_id, **kwargs)
records = []
for similar_span_doc in retrieval_result:
pie_doc, metadata = retriever.docstore.unwrap_with_metadata(similar_span_doc)
span_ann = metadata["attached_span"]
records.append(
{
"doc_id": pie_doc.id,
"span_id": similar_span_doc.id,
"score": metadata["relevance_score"],
"label": span_ann.label,
"text": str(span_ann),
}
)
return (
pd.DataFrame(records, columns=["doc_id", "score", "label", "text", "span_id"])
.sort_values(by="score", ascending=False)
.round(3)
)
except Exception as e:
raise gr.Error(f"Failed to retrieve similar ADUs: {e}")
def retrieve_relevant_spans(
retriever: DocumentAwareSpanRetriever,
query_span_id: str,
relation_label_mapping: Optional[dict[str, str]] = None,
**kwargs,
) -> pd.DataFrame:
if not query_span_id.strip():
raise gr.Error("No query span selected.")
try:
relation_label_mapping = relation_label_mapping or {}
retrieval_result = retriever.invoke(input=query_span_id, return_related=True, **kwargs)
records = []
for relevant_span_doc in retrieval_result:
pie_doc, metadata = retriever.docstore.unwrap_with_metadata(relevant_span_doc)
span_ann = metadata["attached_span"]
tail_span_ann = metadata["attached_tail_span"]
mapped_relation_label = relation_label_mapping.get(
metadata["relation_label"], metadata["relation_label"]
)
records.append(
{
"doc_id": pie_doc.id,
"type": mapped_relation_label,
"rel_score": metadata["relation_score"],
"text": str(tail_span_ann),
"span_id": relevant_span_doc.id,
"label": tail_span_ann.label,
"ref_score": metadata["relevance_score"],
"ref_label": span_ann.label,
"ref_text": str(span_ann),
"ref_span_id": metadata["head_id"],
}
)
return (
pd.DataFrame(
records,
columns=[
"type",
# omitted for now, we get no valid relation scores for the generative model
# "rel_score",
"ref_score",
"label",
"text",
"ref_label",
"ref_text",
"doc_id",
"span_id",
"ref_span_id",
],
)
.sort_values(by=["ref_score"], ascending=False)
.round(3)
)
except Exception as e:
raise gr.Error(f"Failed to retrieve relevant ADUs: {e}")
class RetrieverCallable(Protocol):
def __call__(
self,
retriever: DocumentAwareSpanRetriever,
query_span_id: str,
**kwargs,
) -> Optional[pd.DataFrame]:
pass
def _retrieve_for_all_spans(
retriever: DocumentAwareSpanRetriever,
query_doc_id: str,
retrieve_func: RetrieverCallable,
query_span_id_column: str = "query_span_id",
**kwargs,
) -> Optional[pd.DataFrame]:
if not query_doc_id.strip():
raise gr.Error("No query document selected.")
try:
span_id2idx = retriever.get_span_id2idx_from_doc(query_doc_id)
gr.Info(f"Retrieving results for {len(span_id2idx)} ADUs in document {query_doc_id}...")
span_results = {
query_span_id: retrieve_func(
retriever=retriever,
query_span_id=query_span_id,
**kwargs,
)
for query_span_id in span_id2idx.keys()
}
span_results_not_empty = {
query_span_id: df
for query_span_id, df in span_results.items()
if df is not None and not df.empty
}
# add column with query_span_id
for query_span_id, query_span_result in span_results_not_empty.items():
query_span_result[query_span_id_column] = query_span_id
if len(span_results_not_empty) == 0:
gr.Info(f"No results found for any ADU in document {query_doc_id}.")
return None
else:
result = pd.concat(span_results_not_empty.values(), ignore_index=True)
gr.Info(f"Retrieved {len(result)} ADUs for document {query_doc_id}.")
return result
except Exception as e:
raise gr.Error(
f'Failed to retrieve results for all ADUs in document "{query_doc_id}": {e}'
)
def retrieve_all_similar_spans(
retriever: DocumentAwareSpanRetriever,
query_doc_id: str,
**kwargs,
) -> Optional[pd.DataFrame]:
return _retrieve_for_all_spans(
retriever=retriever,
query_doc_id=query_doc_id,
retrieve_func=retrieve_similar_spans,
**kwargs,
)
def retrieve_all_relevant_spans(
retriever: DocumentAwareSpanRetriever,
query_doc_id: str,
**kwargs,
) -> Optional[pd.DataFrame]:
return _retrieve_for_all_spans(
retriever=retriever,
query_doc_id=query_doc_id,
retrieve_func=retrieve_relevant_spans,
**kwargs,
)
class RetrieverForAllSpansCallable(Protocol):
def __call__(
self,
retriever: DocumentAwareSpanRetriever,
query_doc_id: str,
**kwargs,
) -> Optional[pd.DataFrame]:
pass
def _retrieve_for_all_documents(
retriever: DocumentAwareSpanRetriever,
retrieve_func: RetrieverForAllSpansCallable,
query_doc_id_column: str = "query_doc_id",
**kwargs,
) -> Optional[pd.DataFrame]:
try:
all_doc_ids = list(retriever.docstore.yield_keys())
gr.Info(f"Retrieving results for {len(all_doc_ids)} documents...")
doc_results = {
doc_id: retrieve_func(retriever=retriever, query_doc_id=doc_id, **kwargs)
for doc_id in all_doc_ids
}
doc_results_not_empty = {
doc_id: df for doc_id, df in doc_results.items() if df is not None and not df.empty
}
# add column with query_doc_id
for doc_id, doc_result in doc_results_not_empty.items():
doc_result[query_doc_id_column] = doc_id
if len(doc_results_not_empty) == 0:
gr.Info("No results found for any document.")
return None
else:
result = pd.concat(doc_results_not_empty, ignore_index=True)
gr.Info(f"Retrieved {len(result)} ADUs for all documents.")
return result
except Exception as e:
raise gr.Error(f"Failed to retrieve results for all documents: {e}")
def retrieve_all_similar_spans_for_all_documents(
retriever: DocumentAwareSpanRetriever,
**kwargs,
) -> Optional[pd.DataFrame]:
return _retrieve_for_all_documents(
retriever=retriever,
retrieve_func=retrieve_all_similar_spans,
**kwargs,
)
def retrieve_all_relevant_spans_for_all_documents(
retriever: DocumentAwareSpanRetriever,
**kwargs,
) -> Optional[pd.DataFrame]:
return _retrieve_for_all_documents(
retriever=retriever,
retrieve_func=retrieve_all_relevant_spans,
**kwargs,
)
|