triple_export.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. """Serialize resolved Atlas entities to Turtle for inspection or write-path preparation."""
  2. from __future__ import annotations
  3. from app.models import AtlasEntity, AtlasProvenance
  4. PREFIXES = """@prefix atlas: <http://world.eu.org/atlas_ontology#> .
  5. @prefix atlas_data: <http://world.eu.org/atlas_data#> .
  6. @prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
  7. @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
  8. """
  9. def _safe_fragment(value: str) -> str:
  10. value = (value or "").strip().lower()
  11. out = []
  12. for ch in value:
  13. if ch.isalnum() or ch in ["_", "-"]:
  14. out.append(ch)
  15. else:
  16. out.append("_")
  17. frag = "".join(out).strip("_")
  18. return frag or "entity"
  19. def _entity_node(entity: AtlasEntity) -> str:
  20. return f"atlas_data:entity_{_safe_fragment(entity.atlas_id)}"
  21. def _alias_node(alias_label: str) -> str:
  22. return f"atlas_data:alias_{_safe_fragment(alias_label)}"
  23. def _identifier_node(identifier_value: str) -> str:
  24. return f"atlas_data:ident_{_safe_fragment(identifier_value)}"
  25. def _provenance_node(source: str, retrieved_at: str | None, retrieval_method: str) -> str:
  26. parts = [source, retrieval_method, retrieved_at or ""]
  27. return f"atlas_data:prov_{_safe_fragment('_'.join(parts))}"
  28. def _type_assertion_node(entity: AtlasEntity, source: str) -> str:
  29. return f"atlas_data:typeassert_{_safe_fragment(entity.atlas_id)}_{_safe_fragment(source)}"
  30. def _literal(text: str) -> str:
  31. return text.replace("\\", "\\\\").replace('"', '\\"')
  32. def _identifier_type_resource(identifier_type: str) -> str:
  33. kind = _safe_fragment(identifier_type)
  34. if kind == "mid":
  35. return "atlas:Mid"
  36. if kind in {"qid", "wikidata_qid", "wikidataqid"}:
  37. return "atlas:WikidataQID"
  38. return f"atlas:{kind.capitalize()}"
  39. def _pick_provenance(entity: AtlasEntity, source_hint: str | None = None, method_hint: str | None = None) -> AtlasProvenance | None:
  40. if not entity.provenance:
  41. return None
  42. if method_hint:
  43. for p in entity.provenance:
  44. if p.retrieval_method == method_hint:
  45. return p
  46. if source_hint:
  47. for p in entity.provenance:
  48. if p.source == source_hint:
  49. return p
  50. return entity.provenance[0]
  51. def entity_to_turtle(entity: AtlasEntity) -> str:
  52. lines: list[str] = [PREFIXES]
  53. subject = _entity_node(entity)
  54. claim_nodes = [f"atlas_data:claim_ident_{_safe_fragment(i.value)}" for i in entity.identifiers]
  55. if entity.entity_type and entity.entity_type != "unknown":
  56. claim_nodes.append(f"atlas_data:claim_type_{_safe_fragment(entity.atlas_id)}")
  57. lines.append(f"{subject} a atlas:Entity ;")
  58. lines.append(f' atlas:canonicalLabel "{_literal(entity.canonical_label)}" ;')
  59. if entity.canonical_description:
  60. lines.append(f' atlas:canonicalDescription "{_literal(entity.canonical_description)}" ;')
  61. if entity.entity_type and entity.entity_type != "unknown":
  62. lines.append(f" atlas:hasCanonicalType atlas:{_safe_fragment(entity.entity_type).capitalize()} ;")
  63. for alias in entity.aliases:
  64. lines.append(f" atlas:hasAlias {_alias_node(alias.label)} ;")
  65. for ident in entity.identifiers:
  66. lines.append(f" atlas:hasIdentifier {_identifier_node(ident.value)} ;")
  67. for claim_node in claim_nodes:
  68. lines.append(f" atlas:hasClaim {claim_node} ;")
  69. lines.append(f" atlas:needsCuration {'true' if entity.needs_curation else 'false'} .")
  70. lines.append("")
  71. for alias in entity.aliases:
  72. alias_node = _alias_node(alias.label)
  73. lines.append(f"{alias_node} a atlas:Alias ;")
  74. lines.append(f' atlas:aliasLabel "{_literal(alias.label)}" ;')
  75. lines.append(f" atlas:resolvedTo {subject} .")
  76. lines.append("")
  77. for ident in entity.identifiers:
  78. ident_node = _identifier_node(ident.value)
  79. lines.append(f"{ident_node} a atlas:Identifier ;")
  80. lines.append(f' atlas:identifierValue "{_literal(ident.value)}" ;')
  81. lines.append(f' atlas:identifierSource "{_literal(ident.source)}" ;')
  82. lines.append(f" atlas:identifierType {_identifier_type_resource(ident.identifier_type)} ;")
  83. prov = _pick_provenance(entity, source_hint=ident.source)
  84. if prov:
  85. lines.append(f" atlas:hasIdentifierProvenance {_provenance_node(prov.source, prov.retrieved_at, prov.retrieval_method)} .")
  86. else:
  87. lines[-1] = lines[-1].rstrip(" ;") + " ."
  88. lines.append("")
  89. for prov in entity.provenance:
  90. prov_node = _provenance_node(prov.source, prov.retrieved_at, prov.retrieval_method)
  91. lines.append(f"{prov_node} a atlas:Provenance ;")
  92. lines.append(f' atlas:provenanceSource "{_literal(prov.source)}" ;')
  93. lines.append(f' atlas:retrievalMethod "{_literal(prov.retrieval_method)}" ;')
  94. lines.append(f' atlas:confidence "{prov.confidence}"^^xsd:decimal ;')
  95. if prov.retrieved_at:
  96. lines.append(f' atlas:retrievedAt "{_literal(prov.retrieved_at)}"^^xsd:dateTime .')
  97. else:
  98. lines[-1] = lines[-1].rstrip(" ;") + " ."
  99. lines.append("")
  100. wd = entity.raw_payload.get("wikidata") or {}
  101. if wd.get("status") == "ok":
  102. typeassert_node = _type_assertion_node(entity, "wikidata")
  103. lines.append(f"{typeassert_node} a atlas:TypeAssertion ;")
  104. lines.append(" atlas:assertedType atlas:WikidataType_Q5 ;")
  105. prov = _pick_provenance(entity, source_hint="wikidata")
  106. if prov:
  107. lines.append(f" atlas:hasAssertionProvenance {_provenance_node(prov.source, prov.retrieved_at, prov.retrieval_method)} ;")
  108. lines.append(' atlas:assertionReason "wikidata instance-of" .')
  109. lines.append("")
  110. if entity.entity_type and entity.entity_type != "unknown":
  111. typeassert_node = _type_assertion_node(entity, "canonical")
  112. lines.append(f"{typeassert_node} a atlas:TypeAssertion ;")
  113. lines.append(f" atlas:assertedType atlas:{_safe_fragment(entity.entity_type).capitalize()} ;")
  114. prov = _pick_provenance(entity, method_hint="type-classification")
  115. if prov:
  116. lines.append(f" atlas:hasAssertionProvenance {_provenance_node(prov.source, prov.retrieved_at, prov.retrieval_method)} ;")
  117. lines.append(' atlas:assertionReason "canonical type adjudication" .')
  118. lines.append("")
  119. # Claim nodes with explicit claim-object semantics
  120. for ident in entity.identifiers:
  121. claim_node = f"atlas_data:claim_ident_{_safe_fragment(ident.value)}"
  122. ident_node = _identifier_node(ident.value)
  123. prov = _pick_provenance(entity, source_hint=ident.source)
  124. lines.append(f"{claim_node} a atlas:Claim ;")
  125. lines.append(f" atlas:claimSubjectIri {subject} ;")
  126. lines.append(' atlas:claimPredicate "atlas:hasIdentifier" ;')
  127. lines.append(f" atlas:claimObjectIri {ident_node} ;")
  128. lines.append(' atlas:claimLayer "raw" ;')
  129. lines.append(' atlas:claimStatus "active" ;')
  130. if prov:
  131. lines.append(f" atlas:hasProvenance {_provenance_node(prov.source, prov.retrieved_at, prov.retrieval_method)} .")
  132. else:
  133. lines[-1] = lines[-1].rstrip(" ;") + " ."
  134. lines.append("")
  135. if entity.entity_type and entity.entity_type != "unknown":
  136. claim_node = f"atlas_data:claim_type_{_safe_fragment(entity.atlas_id)}"
  137. prov = _pick_provenance(entity, method_hint="type-classification")
  138. lines.append(f"{claim_node} a atlas:Claim ;")
  139. lines.append(f" atlas:claimSubjectIri {subject} ;")
  140. lines.append(' atlas:claimPredicate "atlas:hasCanonicalType" ;')
  141. lines.append(f" atlas:claimObjectIri atlas:{_safe_fragment(entity.entity_type).capitalize()} ;")
  142. lines.append(' atlas:claimLayer "derived" ;')
  143. lines.append(' atlas:claimStatus "active" ;')
  144. if prov:
  145. lines.append(f" atlas:hasProvenance {_provenance_node(prov.source, prov.retrieved_at, prov.retrieval_method)} .")
  146. else:
  147. lines[-1] = lines[-1].rstrip(" ;") + " ."
  148. lines.append("")
  149. return "\n".join(lines).strip() + "\n"