Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

Merge remote-tracking branch 'origin/main' into pr-1113-work

KaifAhmad1b2dc63379602
diff --cc semantica/export/rdf_exporter.py
index 762759ef,7a290b0c..318ccd39
--- a/semantica/export/rdf_exporter.py
+++ b/semantica/export/rdf_exporter.py
@@@ -277,61 -642,6 +642,37 @@@ class RDFSerializer
self.logger.debug("RDF serializer initialized")
- @staticmethod
- def _escape_turtle_literal(value: str) -> str:
- """Escape a string for use inside a Turtle/N-Triples double-quoted literal.
-
- Follows the RDF 1.1 Turtle grammar for STRING_LITERAL_QUOTE: backslash
- must be escaped first, then the double quote and the recognized control
- characters. This prevents literal breakout and injection.
- """
- return (
- value.replace("\\", "\\\\")
- .replace('"', '\\"')
- .replace("\r", "\\r")
- .replace("\n", "\\n")
- .replace("\t", "\\t")
- )
-
- @staticmethod
- def _escape_xml_text(value: str) -> str:
- """Escape a string for safe inclusion in RDF/XML character data."""
- from xml.sax.saxutils import escape
-
- # escape() handles &, <, > by default; add quotes for attribute safety.
- return escape(value, {'"': "&quot;", "'": "&apos;"})
-
+ @staticmethod
+ def _local_name_from_id(identifier: str) -> str:
+ """Derive a human-readable local name from an entity identifier.
+
+ Handles HTTP(S)/IRI identifiers (path segments and fragments, tolerating
+ trailing slashes) as well as compact/CURIE and URN-style identifiers.
+ """
+ raw = str(identifier).strip()
+ if not raw:
+ return ""
+
+ # Prefer a fragment if present (e.g. http://ex.org/onto#acme -> acme).
+ if "#" in raw:
+ candidate = raw.rsplit("#", 1)[-1]
+ if candidate:
+ return candidate
+
+ # For IRIs/paths, take the last non-empty path segment.
+ if "/" in raw:
+ segment = raw.rstrip("/").rsplit("/", 1)[-1]
+ if segment:
+ return segment
+
+ # Fall back to the tail of a CURIE/URN (e.g. urn:x:acme, semantica:acme).
+ if ":" in raw:
+ candidate = raw.rsplit(":", 1)[-1]
+ if candidate:
+ return candidate
+
+ return raw
+
def convert_kg_to_rdf(self, knowledge_graph: Dict[str, Any]) -> Dict[str, Any]:
"""
Convert knowledge graph to RDF data structure.
@@@ -585,18 -1076,41 +1110,44 @@@
entity_text = entity.get("text", "")
entity_id = mint_entity_iri(entity_text)
- entity_type = entity.get("type", DEFAULT_ENTITY_TYPE)
+ entity_type = entity.get("type") or DEFAULT_ENTITY_TYPE
text = entity.get("text") or entity.get("label", "")
- confidence = entity.get("confidence", 1.0)
+ confidence = normalize_confidence(entity.get("confidence", 1.0))
# RDF/XML syntax: rdf:Description with rdf:about
- lines.append(f' <rdf:Description rdf:about="{entity_id}">')
- lines.append(f' <rdf:type rdf:resource="{entity_type}"/>')
- lines.append(
- f" <semantica:text>{self._escape_xml_text(text)}</semantica:text>"
+ # Attribute values are delimited by quotes, and both of these
- # are caller input. Element text is left alone deliberately: that
- # is #1098, and it is being fixed on its own path.
++ # are caller input. Element text (semantica:text) is caller input
++ # too, so it needs the same escaping to avoid injecting markup
++ # or breaking out of the element (#1097 / #1113).
+ entity_iri = xml_escape(
+ self._as_turtle_iri(entity_id, namespaces), quote=True
)
+ entity_type_iri = xml_escape(
+ self._as_turtle_iri(entity_type, namespaces), quote=True
+ )
+ lines.append(f' <rdf:Description rdf:about="{entity_iri}">')
+ lines.append(f' <rdf:type rdf:resource="{entity_type_iri}"/>')
- lines.append(f" <semantica:text>{text}</semantica:text>")
+ lines.append(
- f" <semantica:confidence>{confidence}</semantica:confidence>"
++ f" <semantica:text>{xml_escape(text)}</semantica:text>"
++ )
+ if confidence is None:
+ self.logger.warning(
+ f"Entity {entity_id} has a confidence that is not a number "
+ f"({entity.get('confidence')!r}), so no confidence is written"
+ )
+ else:
+ lines.append(
+ f' <semantica:confidence rdf:datatype="{CONFIDENCE_DATATYPE}">'
+ f"{confidence}</semantica:confidence>"
+ )
+ lines.extend(
+ _rdfxml_metadata_lines(
+ _metadata_statements(
+ entity.get("metadata"), metadata_terms, self.logger
+ ),
+ " ",
+ self.logger,
+ )
)
lines.append(" </rdf:Description>")
lines.append("")