File size: 21,387 Bytes
c5880fb |
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 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 |
"""
Dataset Loader Module (Refactored)
Generic dataset loading supporting multiple formats:
- OBO (Open Biomedical Ontologies)
- CSV/TSV
- JSON/JSON-LD
- Custom adapters
Configuration-driven to support any domain, not just medical.
"""
import os
import re
import json
import csv
import logging
import hashlib
import urllib.request
from pathlib import Path
from abc import ABC, abstractmethod
from datetime import datetime
from typing import Dict, List, Optional, Tuple, Any, Type
from dataclasses import dataclass, field
from .knowledge_graph import Entity, EntityCategory, KnowledgeGraph
from .config import DatasetConfig, get_config
logger = logging.getLogger(__name__)
@dataclass
class OntologyTerm:
"""Generic ontology term representation."""
id: str
name: str
definition: str = ""
synonyms: List[str] = field(default_factory=list)
xrefs: Dict[str, str] = field(default_factory=dict)
is_a: List[str] = field(default_factory=list)
relationships: List[Tuple[str, str]] = field(default_factory=list)
namespace: str = ""
is_obsolete: bool = False
def to_entity(self, category: EntityCategory) -> Entity:
"""Convert to Entity."""
return Entity(
id=self.id,
name=self.name,
category=category,
description=self.definition,
synonyms=self.synonyms,
xrefs=self.xrefs,
properties={"is_a": self.is_a, "namespace": self.namespace}
)
class DatasetAdapter(ABC):
"""Abstract base class for dataset adapters."""
@abstractmethod
def parse(self, content: str) -> Dict[str, OntologyTerm]:
"""Parse content and return dictionary of terms."""
pass
@abstractmethod
def can_handle(self, source_type: str) -> bool:
"""Check if this adapter can handle the source type."""
pass
class OBOAdapter(DatasetAdapter):
"""Parser for OBO (Open Biomedical Ontologies) format."""
def can_handle(self, source_type: str) -> bool:
return source_type.lower() == "obo"
def parse(self, content: str) -> Dict[str, OntologyTerm]:
"""Parse OBO format content."""
terms = {}
# Split into stanzas
stanzas = re.split(r'\n\[', content)
for stanza in stanzas[1:]: # Skip header
if stanza.startswith('Term]'):
term = self._parse_term(stanza[5:])
if term and not term.is_obsolete:
terms[term.id] = term
logger.info(f"Parsed {len(terms)} terms from OBO content")
return terms
def _parse_term(self, stanza: str) -> Optional[OntologyTerm]:
"""Parse a single term stanza."""
data = {
"id": "", "name": "", "definition": "",
"synonyms": [], "xrefs": {}, "is_a": [],
"relationships": [], "namespace": "", "is_obsolete": False
}
for line in stanza.split('\n'):
line = line.strip()
if not line or line.startswith('!') or ':' not in line:
continue
tag, _, value = line.partition(':')
tag, value = tag.strip(), value.strip()
if tag == 'id':
data['id'] = value
elif tag == 'name':
data['name'] = value
elif tag == 'def':
match = re.match(r'"([^"]*)"', value)
if match:
data['definition'] = match.group(1)
elif tag == 'synonym':
match = re.match(r'"([^"]*)"', value)
if match:
data['synonyms'].append(match.group(1))
elif tag == 'xref':
if ':' in value:
xref_ns, _, xref_id = value.partition(':')
xref_id = xref_id.split()[0] if ' ' in xref_id else xref_id
data['xrefs'][xref_ns.strip()] = xref_id.strip()
elif tag == 'is_a':
parent_id = value.split('!')[0].strip()
data['is_a'].append(parent_id)
elif tag == 'relationship':
parts = value.split()
if len(parts) >= 2:
data['relationships'].append((parts[0], parts[1]))
elif tag == 'is_obsolete':
data['is_obsolete'] = value.lower() == 'true'
elif tag == 'namespace':
data['namespace'] = value
if data['id'] and data['name']:
return OntologyTerm(**data)
return None
class CSVAdapter(DatasetAdapter):
"""Parser for CSV/TSV format datasets."""
# Default column mappings
DEFAULT_MAPPINGS = {
"id": ["id", "ID", "identifier", "code"],
"name": ["name", "Name", "label", "Label", "title"],
"definition": ["definition", "description", "Description", "desc"],
"synonyms": ["synonyms", "aliases", "alt_names"],
}
def __init__(self, column_mappings: Optional[Dict[str, str]] = None):
self.column_mappings = column_mappings or {}
def can_handle(self, source_type: str) -> bool:
return source_type.lower() in ["csv", "tsv"]
def parse(self, content: str) -> Dict[str, OntologyTerm]:
"""Parse CSV content."""
terms = {}
# Detect delimiter
dialect = csv.Sniffer().sniff(content[:1024])
reader = csv.DictReader(content.splitlines(), dialect=dialect)
# Map columns
col_map = self._map_columns(reader.fieldnames or [])
for row in reader:
term = self._row_to_term(row, col_map)
if term:
terms[term.id] = term
logger.info(f"Parsed {len(terms)} terms from CSV content")
return terms
def _map_columns(self, fieldnames: List[str]) -> Dict[str, str]:
"""Map fieldnames to standard term fields."""
col_map = {}
for field, possible_names in self.DEFAULT_MAPPINGS.items():
# Check explicit mappings first
if field in self.column_mappings:
col_map[field] = self.column_mappings[field]
else:
# Try to auto-detect
for name in possible_names:
if name in fieldnames:
col_map[field] = name
break
return col_map
def _row_to_term(self, row: Dict, col_map: Dict[str, str]) -> Optional[OntologyTerm]:
"""Convert CSV row to OntologyTerm."""
term_id = row.get(col_map.get("id", ""), "")
name = row.get(col_map.get("name", ""), "")
if not term_id or not name:
return None
definition = row.get(col_map.get("definition", ""), "")
# Parse synonyms (comma-separated or JSON array)
synonyms_raw = row.get(col_map.get("synonyms", ""), "")
if synonyms_raw.startswith("["):
try:
synonyms = json.loads(synonyms_raw)
except json.JSONDecodeError:
synonyms = []
else:
synonyms = [s.strip() for s in synonyms_raw.split(",") if s.strip()]
return OntologyTerm(
id=term_id,
name=name,
definition=definition,
synonyms=synonyms
)
class JSONAdapter(DatasetAdapter):
"""Parser for JSON format datasets."""
def __init__(self, terms_path: str = "terms", id_field: str = "id", name_field: str = "name"):
self.terms_path = terms_path
self.id_field = id_field
self.name_field = name_field
def can_handle(self, source_type: str) -> bool:
return source_type.lower() in ["json", "json-ld"]
def parse(self, content: str) -> Dict[str, OntologyTerm]:
"""Parse JSON content."""
terms = {}
data = json.loads(content)
# Navigate to terms array
items = data
if self.terms_path:
for key in self.terms_path.split("."):
if isinstance(items, dict):
items = items.get(key, [])
else:
break
if not isinstance(items, list):
items = [items] if isinstance(items, dict) else []
for item in items:
term = self._item_to_term(item)
if term:
terms[term.id] = term
logger.info(f"Parsed {len(terms)} terms from JSON content")
return terms
def _item_to_term(self, item: Dict) -> Optional[OntologyTerm]:
"""Convert JSON item to OntologyTerm."""
term_id = item.get(self.id_field, "")
name = item.get(self.name_field, "")
if not term_id or not name:
return None
return OntologyTerm(
id=term_id,
name=name,
definition=item.get("definition", item.get("description", "")),
synonyms=item.get("synonyms", item.get("aliases", [])),
xrefs=item.get("xrefs", {}),
is_a=item.get("is_a", item.get("parents", [])),
)
class DatasetLoader:
"""
Main dataset loader supporting multiple formats and sources.
Usage:
loader = DatasetLoader()
loader.load_dataset(config) # Single dataset
loader.load_all_datasets() # From config
"""
def __init__(self, cache_dir: Optional[str] = None):
self.cache_dir = Path(cache_dir or get_config().cache_dir)
self.cache_dir.mkdir(parents=True, exist_ok=True)
# Register adapters
self.adapters: List[DatasetAdapter] = [
OBOAdapter(),
CSVAdapter(),
JSONAdapter(),
]
# Loaded data
self.datasets: Dict[str, Dict[str, OntologyTerm]] = {}
def register_adapter(self, adapter: DatasetAdapter):
"""Register a custom adapter."""
self.adapters.insert(0, adapter) # Custom adapters take priority
def get_adapter(self, source_type: str) -> Optional[DatasetAdapter]:
"""Get adapter for source type."""
for adapter in self.adapters:
if adapter.can_handle(source_type):
return adapter
return None
def load_dataset(self, config: DatasetConfig) -> Dict[str, OntologyTerm]:
"""Load a single dataset based on configuration."""
logger.info(f"Loading dataset: {config.name}")
# Check cache
if config.cache_enabled:
cached = self._load_from_cache(config)
if cached:
self.datasets[config.name] = cached
return cached
# Get content
content = self._get_content(config)
if not content:
logger.warning(f"No content for dataset: {config.name}")
return {}
# Parse with appropriate adapter
adapter = self.get_adapter(config.source_type)
if not adapter:
logger.error(f"No adapter for source type: {config.source_type}")
return {}
terms = adapter.parse(content)
# Cache results
if config.cache_enabled:
self._save_to_cache(config, terms)
self.datasets[config.name] = terms
return terms
def load_all_datasets(self) -> Dict[str, Dict[str, OntologyTerm]]:
"""Load all datasets from configuration."""
config = get_config()
for dataset_config in config.datasets:
self.load_dataset(dataset_config)
return self.datasets
def _get_content(self, config: DatasetConfig) -> Optional[str]:
"""Get content from URL or file path."""
# Try URL first
if config.source_url:
try:
logger.info(f"Downloading from: {config.source_url}")
req = urllib.request.Request(
config.source_url,
headers={'User-Agent': 'HITL-KG/1.0'}
)
with urllib.request.urlopen(req, timeout=60) as response:
return response.read().decode('utf-8')
except Exception as e:
logger.warning(f"Download failed: {e}")
# Try local file
if config.source_path:
path = Path(config.source_path)
if path.exists():
return path.read_text(encoding='utf-8')
return None
def _cache_path(self, config: DatasetConfig) -> Path:
"""Get cache file path for a dataset."""
return self.cache_dir / f"{config.name}_cache.json"
def _load_from_cache(self, config: DatasetConfig) -> Optional[Dict[str, OntologyTerm]]:
"""Load dataset from cache if valid."""
cache_path = self._cache_path(config)
if not cache_path.exists():
return None
# Check age
mtime = datetime.fromtimestamp(cache_path.stat().st_mtime)
age_days = (datetime.now() - mtime).days
if age_days > config.cache_max_age_days:
return None
try:
with open(cache_path) as f:
data = json.load(f)
terms = {}
for term_id, term_data in data.get("terms", {}).items():
terms[term_id] = OntologyTerm(
id=term_data["id"],
name=term_data["name"],
definition=term_data.get("definition", ""),
synonyms=term_data.get("synonyms", []),
xrefs=term_data.get("xrefs", {}),
is_a=term_data.get("is_a", []),
relationships=term_data.get("relationships", []),
namespace=term_data.get("namespace", ""),
)
logger.info(f"Loaded {len(terms)} terms from cache: {config.name}")
return terms
except Exception as e:
logger.warning(f"Cache load failed: {e}")
return None
def _save_to_cache(self, config: DatasetConfig, terms: Dict[str, OntologyTerm]):
"""Save dataset to cache."""
try:
cache_path = self._cache_path(config)
data = {
"name": config.name,
"source_type": config.source_type,
"timestamp": datetime.now().isoformat(),
"terms": {
tid: {
"id": t.id,
"name": t.name,
"definition": t.definition,
"synonyms": t.synonyms,
"xrefs": t.xrefs,
"is_a": t.is_a,
"relationships": t.relationships,
"namespace": t.namespace,
}
for tid, t in terms.items()
}
}
with open(cache_path, 'w') as f:
json.dump(data, f)
logger.info(f"Cached {len(terms)} terms for: {config.name}")
except Exception as e:
logger.warning(f"Cache save failed: {e}")
def build_knowledge_graph(loader: DatasetLoader) -> KnowledgeGraph:
"""
Build a KnowledgeGraph from loaded datasets.
This function:
1. Converts OntologyTerms to Entities
2. Creates relationships between entities
3. Indexes entities for semantic search
"""
kg = KnowledgeGraph()
config = get_config()
# Map dataset names to categories
category_map = {
ds.name: EntityCategory(ds.entity_category)
for ds in config.datasets
if ds.entity_category in [c.value for c in EntityCategory]
}
# Add entities from each dataset
for dataset_name, terms in loader.datasets.items():
category = category_map.get(dataset_name, EntityCategory.FINDING)
for term_id, term in terms.items():
entity = term.to_entity(category)
kg.add_entity(entity)
# Build relationships based on ontology structure
_build_relationships(kg, loader)
logger.info(f"Built KG with {len(kg.entities)} entities")
return kg
def _build_relationships(kg: KnowledgeGraph, loader: DatasetLoader):
"""Build relationships between entities."""
# Disease-symptom associations (curated mappings)
disease_symptom_mappings = _get_disease_symptom_mappings()
for disease_id, symptom_mappings in disease_symptom_mappings.items():
if disease_id not in kg.entities:
continue
for symptom_name, confidence in symptom_mappings:
# Find symptom entity by name
symptom_entity = None
for entity in kg.entities.values():
if entity.category == EntityCategory.SYMPTOM:
if (entity.name.lower() == symptom_name.lower() or
symptom_name.lower() in [s.lower() for s in entity.synonyms]):
symptom_entity = entity
break
if symptom_entity:
kg.add_relation(disease_id, symptom_entity.id, "causes", confidence)
# Add treatment relations
_add_treatment_entities(kg)
def _get_disease_symptom_mappings() -> Dict[str, List[Tuple[str, float]]]:
"""
Get curated disease-symptom mappings.
These are based on medical literature and provide high-quality
associations that may not be present in the raw ontologies.
"""
return {
"DOID:8469": [ # Influenza
("fever", 0.95), ("cough", 0.85), ("fatigue", 0.90),
("body aches", 0.85), ("headache", 0.80), ("chills", 0.75),
],
"DOID:0080600": [ # COVID-19
("fever", 0.80), ("cough", 0.85), ("fatigue", 0.90),
("shortness of breath", 0.70), ("headache", 0.60),
("loss of taste", 0.50), ("loss of smell", 0.50),
],
"DOID:10459": [ # Common cold
("runny nose", 0.95), ("sore throat", 0.80), ("cough", 0.75),
("nasal congestion", 0.85), ("sneezing", 0.80),
],
"DOID:552": [ # Pneumonia
("fever", 0.90), ("cough", 0.95), ("shortness of breath", 0.85),
("chest pain", 0.70), ("fatigue", 0.80),
],
"DOID:6132": [ # Bronchitis
("cough", 0.95), ("fatigue", 0.60),
("shortness of breath", 0.50),
],
"DOID:10534": [ # Strep throat
("sore throat", 0.98), ("fever", 0.80), ("headache", 0.50),
],
"DOID:13084": [ # Sinusitis
("headache", 0.85), ("nasal congestion", 0.90),
("runny nose", 0.80),
],
"DOID:8893": [ # Migraine
("headache", 0.99), ("nausea", 0.70),
],
}
def _add_treatment_entities(kg: KnowledgeGraph):
"""Add treatment entities and relationships."""
treatments = [
Entity("tx_rest", "Rest", EntityCategory.TREATMENT,
"Physical and mental rest", ["bed rest"]),
Entity("tx_fluids", "Fluid Intake", EntityCategory.TREATMENT,
"Increased hydration", ["hydration"]),
Entity("tx_acetaminophen", "Acetaminophen", EntityCategory.MEDICATION,
"Pain and fever reducer", ["paracetamol", "Tylenol"]),
Entity("tx_ibuprofen", "Ibuprofen", EntityCategory.MEDICATION,
"NSAID for pain and inflammation", ["Advil", "Motrin"]),
Entity("tx_antiviral", "Antiviral Medication", EntityCategory.MEDICATION,
"Medications for viral infections", ["oseltamivir", "Tamiflu"]),
Entity("tx_decongestant", "Decongestants", EntityCategory.MEDICATION,
"Nasal congestion relief", ["pseudoephedrine"]),
]
for tx in treatments:
kg.add_entity(tx)
# Treatment relationships
treatment_map = {
"DOID:8469": ["tx_rest", "tx_fluids", "tx_acetaminophen", "tx_antiviral"],
"DOID:0080600": ["tx_rest", "tx_fluids", "tx_acetaminophen"],
"DOID:10459": ["tx_rest", "tx_fluids", "tx_decongestant"],
"DOID:552": ["tx_rest"],
}
for disease_id, treatment_ids in treatment_map.items():
if disease_id in kg.entities:
for tx_id in treatment_ids:
if tx_id in kg.entities:
kg.add_relation(tx_id, disease_id, "treats", 0.8)
def load_knowledge_graph(use_embeddings: bool = True) -> KnowledgeGraph:
"""
Main entry point: Load datasets and build knowledge graph.
Args:
use_embeddings: If True, also index entities for semantic search
"""
loader = DatasetLoader()
loader.load_all_datasets()
kg = build_knowledge_graph(loader)
if use_embeddings:
try:
from .embedding_service import get_embedding_service
embedding_service = get_embedding_service()
embedding_service.index_entities(kg.get_entity_dict_for_embedding())
except Exception as e:
logger.warning(f"Failed to initialize embeddings: {e}")
return kg
|