|
| 1 | +"""Extraction preview and ingest helpers for the knowledge graph CLI.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import hashlib |
| 6 | +import json |
| 7 | +import logging |
| 8 | +from dataclasses import asdict, is_dataclass |
| 9 | +from pathlib import Path |
| 10 | +from typing import TYPE_CHECKING, Any, Callable, Mapping |
| 11 | + |
| 12 | +from .. import extraction as kg_extraction |
| 13 | + |
| 14 | +if TYPE_CHECKING: |
| 15 | + from ..embeddings import EmbeddingGenerator |
| 16 | + from ..service import LanceKnowledgeGraph |
| 17 | + |
| 18 | +LOGGER = logging.getLogger(__name__) |
| 19 | + |
| 20 | + |
| 21 | +def preview_extraction(source: str, extractor: kg_extraction.BaseExtractor) -> None: |
| 22 | + """Preview extracted knowledge from a text source or inline text.""" |
| 23 | + text = _resolve_text_input(source) |
| 24 | + result = kg_extraction.preview_extraction(text, extractor=extractor) |
| 25 | + print(json.dumps(_result_to_dict(result), indent=2)) |
| 26 | + |
| 27 | + |
| 28 | +def extract_and_add( |
| 29 | + source: str, |
| 30 | + service: LanceKnowledgeGraph, |
| 31 | + extractor: kg_extraction.BaseExtractor, |
| 32 | + *, |
| 33 | + embedding_generator: EmbeddingGenerator | None = None, |
| 34 | +) -> None: |
| 35 | + """Extract knowledge and append it to the backing graph.""" |
| 36 | + import pyarrow as pa |
| 37 | + |
| 38 | + text = _resolve_text_input(source) |
| 39 | + result = kg_extraction.preview_extraction(text, extractor=extractor) |
| 40 | + entity_rows, name_to_id = _prepare_entity_rows( |
| 41 | + result.entities, embedding_generator=embedding_generator |
| 42 | + ) |
| 43 | + relationships = result.relationships |
| 44 | + |
| 45 | + if not entity_rows and not relationships: |
| 46 | + print("No candidate entities or relationships detected.") |
| 47 | + return |
| 48 | + |
| 49 | + if entity_rows: |
| 50 | + entity_table = pa.Table.from_pylist(entity_rows) |
| 51 | + service.upsert_table("Entity", entity_table, merge=True) |
| 52 | + message = f"Upserted {entity_table.num_rows} entity rows into dataset 'Entity'." |
| 53 | + print(message) |
| 54 | + |
| 55 | + relationship_rows = _prepare_relationship_rows( |
| 56 | + relationships, |
| 57 | + name_to_id, |
| 58 | + embedding_generator=embedding_generator, |
| 59 | + ) |
| 60 | + if relationship_rows: |
| 61 | + rel_table = pa.Table.from_pylist(relationship_rows) |
| 62 | + service.upsert_table("RELATIONSHIP", rel_table, merge=True) |
| 63 | + message = ( |
| 64 | + "Upserted " |
| 65 | + f"{rel_table.num_rows} relationship rows into dataset " |
| 66 | + "'RELATIONSHIP'." |
| 67 | + ) |
| 68 | + print(message) |
| 69 | + |
| 70 | + |
| 71 | +def _resolve_text_input(raw: str) -> str: |
| 72 | + """Load text from a file if it exists, otherwise treat the string as content.""" |
| 73 | + candidate = Path(raw) |
| 74 | + if candidate.exists(): |
| 75 | + if candidate.is_dir(): |
| 76 | + raise IsADirectoryError(f"Expected text file, got directory: {candidate}") |
| 77 | + return candidate.read_text(encoding="utf-8") |
| 78 | + return raw |
| 79 | + |
| 80 | + |
| 81 | +def _ensure_dict(item: object) -> dict: |
| 82 | + if is_dataclass(item): |
| 83 | + return asdict(item) # type: ignore[arg-type] |
| 84 | + if isinstance(item, dict): |
| 85 | + return item |
| 86 | + raise TypeError(f"Unsupported extraction item type: {type(item)!r}") |
| 87 | + |
| 88 | + |
| 89 | +def _result_to_dict(result: "kg_extraction.ExtractionResult") -> dict[str, list[dict]]: |
| 90 | + return { |
| 91 | + "entities": [asdict(entity) for entity in result.entities], |
| 92 | + "relationships": [asdict(rel) for rel in result.relationships], |
| 93 | + } |
| 94 | + |
| 95 | + |
| 96 | +def _prepare_entity_rows( |
| 97 | + entities: list[Any], |
| 98 | + *, |
| 99 | + embedding_generator: EmbeddingGenerator | None = None, |
| 100 | +) -> tuple[list[dict[str, Any]], dict[str, str]]: |
| 101 | + rows: list[dict[str, Any]] = [] |
| 102 | + name_to_id: dict[str, str] = {} |
| 103 | + for entity in entities: |
| 104 | + payload = _ensure_dict(entity) |
| 105 | + name = str(payload.get("name", "")).strip() |
| 106 | + entity_type = str( |
| 107 | + payload.get("entity_type") or payload.get("type") or "" |
| 108 | + ).strip() |
| 109 | + if not name: |
| 110 | + continue |
| 111 | + base = f"{name}|{entity_type}".encode("utf-8") |
| 112 | + entity_id = hashlib.md5(base).hexdigest() |
| 113 | + payload["entity_id"] = entity_id |
| 114 | + payload["entity_type"] = entity_type or "UNKNOWN" |
| 115 | + payload["name_lower"] = name.lower() |
| 116 | + rows.append(payload) |
| 117 | + name_to_id.setdefault(name.lower(), entity_id) |
| 118 | + if embedding_generator and rows: |
| 119 | + _assign_embeddings( |
| 120 | + rows, |
| 121 | + embedding_generator, |
| 122 | + _format_entity_embedding_input, |
| 123 | + ) |
| 124 | + return rows, name_to_id |
| 125 | + |
| 126 | + |
| 127 | +def _prepare_relationship_rows( |
| 128 | + relationships: list[Any], |
| 129 | + name_to_id: dict[str, str], |
| 130 | + *, |
| 131 | + embedding_generator: EmbeddingGenerator | None = None, |
| 132 | +) -> list[dict[str, Any]]: |
| 133 | + rows: list[dict[str, Any]] = [] |
| 134 | + for relation in relationships: |
| 135 | + payload = _ensure_dict(relation) |
| 136 | + source_name = str( |
| 137 | + payload.get("source_entity_name") or payload.get("source") or "" |
| 138 | + ).strip() |
| 139 | + target_name = str( |
| 140 | + payload.get("target_entity_name") or payload.get("target") or "" |
| 141 | + ).strip() |
| 142 | + source_id = name_to_id.get(source_name.lower()) |
| 143 | + target_id = name_to_id.get(target_name.lower()) |
| 144 | + if not (source_id and target_id): |
| 145 | + continue |
| 146 | + payload["source_entity_id"] = source_id |
| 147 | + payload["target_entity_id"] = target_id |
| 148 | + payload["relationship_type"] = ( |
| 149 | + payload.get("relationship_type") or payload.get("type") or "RELATED_TO" |
| 150 | + ) |
| 151 | + payload.setdefault("source_entity_name", source_name) |
| 152 | + payload.setdefault("target_entity_name", target_name) |
| 153 | + rows.append(payload) |
| 154 | + if embedding_generator and rows: |
| 155 | + _assign_embeddings( |
| 156 | + rows, |
| 157 | + embedding_generator, |
| 158 | + _format_relationship_embedding_input, |
| 159 | + ) |
| 160 | + return rows |
| 161 | + |
| 162 | + |
| 163 | +def _assign_embeddings( |
| 164 | + rows: list[dict[str, Any]], |
| 165 | + embedding_generator: EmbeddingGenerator, |
| 166 | + formatter: Callable[[Mapping[str, Any]], str], |
| 167 | +) -> None: |
| 168 | + texts: list[str] = [] |
| 169 | + indices: list[int] = [] |
| 170 | + for idx, row in enumerate(rows): |
| 171 | + text = formatter(row) |
| 172 | + if text: |
| 173 | + texts.append(text) |
| 174 | + indices.append(idx) |
| 175 | + if not texts: |
| 176 | + return |
| 177 | + try: |
| 178 | + vectors = embedding_generator.embed(texts) |
| 179 | + except Exception as exc: # pragma: no cover - defensive logging path |
| 180 | + LOGGER.warning("Failed to generate embeddings: %s", exc) |
| 181 | + return |
| 182 | + if len(vectors) != len(indices): |
| 183 | + LOGGER.warning( |
| 184 | + "Mismatch between embedding count and row count: expected %s, got %s", |
| 185 | + len(indices), |
| 186 | + len(vectors), |
| 187 | + ) |
| 188 | + return |
| 189 | + for idx, vector in zip(indices, vectors): |
| 190 | + rows[idx]["embedding"] = vector |
| 191 | + |
| 192 | + |
| 193 | +def _format_entity_embedding_input(row: Mapping[str, Any]) -> str: |
| 194 | + name = str(row.get("name", "")).strip() |
| 195 | + entity_type = str(row.get("entity_type", "")).strip() |
| 196 | + context = str(row.get("context", "")).strip() |
| 197 | + pieces = [] |
| 198 | + if name: |
| 199 | + pieces.append(name) |
| 200 | + if entity_type: |
| 201 | + pieces.append(f"Type: {entity_type}") |
| 202 | + if context: |
| 203 | + pieces.append(f"Context: {context}") |
| 204 | + return " | ".join(pieces) |
| 205 | + |
| 206 | + |
| 207 | +def _format_relationship_embedding_input(row: Mapping[str, Any]) -> str: |
| 208 | + source = str(row.get("source_entity_name") or row.get("source") or "").strip() |
| 209 | + target = str(row.get("target_entity_name") or row.get("target") or "").strip() |
| 210 | + relationship_type = str(row.get("relationship_type", "")).strip() |
| 211 | + description = str(row.get("description", "")).strip() |
| 212 | + core: list[str] = [] |
| 213 | + if source or target: |
| 214 | + if relationship_type: |
| 215 | + core.append(f"{source} -[{relationship_type}]-> {target}".strip()) |
| 216 | + else: |
| 217 | + core.append(f"{source} -> {target}".strip()) |
| 218 | + if description: |
| 219 | + core.append(f"Description: {description}") |
| 220 | + return " | ".join(part for part in core if part) |
0 commit comments