Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
Merge upstream/main into metadata-passthrough
Fabio Rovaid06434ae3172
diff --cc semantica/export/rdf_exporter.pyindex af5a21c3,71d12f71..6f07d619--- a/semantica/export/rdf_exporter.py+++ b/semantica/export/rdf_exporter.py@@@ -578,25 -465,20 +648,33 @@@ class RDFSerializerentity_type = entity.get("type", 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))- lines.append(f"<{entity_id}> a <{entity_type}> ;")+ clauses = [+ f"a <{entity_type}>",+ f'semantica:text "{text}"',- f"semantica:confidence {confidence}",+ ]+ 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"+ )- lines.append(f' semantica:text "{text}" .')+ else:- lines.append(f' semantica:text "{text}" ;')- lines.append(- f' semantica:confidence "{confidence}"^^<{CONFIDENCE_DATATYPE}> .'++ clauses.append(++ f'semantica:confidence "{confidence}"^^<{CONFIDENCE_DATATYPE}>'++ )+ clauses.extend(+ _turtle_metadata_clauses(+ _metadata_statements(+ entity.get("metadata"), metadata_terms, self.logger+ ))+ )++ lines.append(f"<{entity_id}> {clauses[0]} ;")+ for clause in clauses[1:-1]:+ lines.append(f" {clause} ;")+ lines.append(f" {clauses[-1]} .")lines.append("")# Convert relationships to RDF triplets@@@ -611,34 -493,59 +689,83 @@@if include_temporal:owl_lines = self._owl_time_triples_for_rel(rel, idx, time_axis)if owl_lines:+ # The interval hangs off the relationship's own IRI, and a+ # relationship written as a single triple has no such node+ # in the graph. Without this the timestamps are well formed+ # and unreachable: no query can get from the edge to its+ # validity interval (#1106). The shape matches the JSON-LD+ # export, and every term is declared in the vocabulary.+ lines.extend(+ self._reified_relationship_triples(+ rel, idx, source_id, target_id, rel_type+ )+ )lines.extend(owl_lines)+ # Graph-level metadata needs a subject, and this serializer has never+ # minted a document node. Rather than invent one here, it is written+ # only when the caller names the graph; issue #1147 is where the+ # default subject comes from once that lands.+ graph_clauses = (+ _turtle_metadata_clauses(+ _metadata_statements(+ rdf_data.get("metadata"), metadata_terms, self.logger+ )+ )+ if graph_uri+ else []+ )+ if graph_clauses:+ lines.append("")+ lines.append(+ f"<{graph_uri}> {graph_clauses[0]} "+ + (";" if len(graph_clauses) > 1 else ".")+ )+ for clause in graph_clauses[1:-1]:+ lines.append(f" {clause} ;")+ if len(graph_clauses) > 1:+ lines.append(f" {graph_clauses[-1]} .")+return "\n".join(lines)+ def _reified_relationship_triples(+ self,+ rel: Dict[str, Any],+ idx: int,+ source_id: str,+ target_id: str,+ rel_type: str,+ ) -> List[str]:+ """+ Emit the reified relationship node that OWL-Time triples hang off.++ The direct triple stays. This adds a subject the interval can attach+ to, using the same sem:Relationship shape the JSON-LD export already+ writes, so the two serializations describe relationships the same way.+ """+ rel_id = rel.get("id") or mint_relationship_iri(idx, source_id or "", target_id or "")++ # The full predicate, not its local name. Truncating to the fragment+ # made https://a.example/ns#employs and https://b.example/ns#employs the+ # same literal, so the temporal node no longer said which predicate it+ # described, and it disagreed with the direct triple beside it.+ escaped = (+ str(rel_type)+ .replace("\\", "\\\\")+ .replace('"', '\\"')+ .replace("\n", "\\n")+ .replace("\r", "\\r")+ )++ predicates = [f"a semantica:Relationship"]+ if source_id:+ predicates.append(f"semantica:source <{source_id}>")+ if target_id:+ predicates.append(f"semantica:target <{target_id}>")+ predicates.append(f'semantica:type "{escaped}"')++ return ["", f"<{rel_id}> " + " ;\n ".join(predicates) + " ."]+def _owl_time_triples_for_rel(self, rel: Dict[str, Any], idx: int, time_axis: str) -> List[str]:@@@ -757,17 -661,16 +884,24 @@@lines.append(f' <rdf:Description rdf:about="{entity_id}">')lines.append(f' <rdf:type rdf:resource="{entity_type}"/>')lines.append(f" <semantica:text>{text}</semantica:text>")- lines.append(- f" <semantica:confidence>{confidence}</semantica:confidence>"- )+ 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+ ),+ " ",+ )+ )lines.append(" </rdf:Description>")lines.append("")@@@ -863,15 -747,20 +997,27 @@@"@id": entity_id,"@type": entity.get("type", "semantica:Entity"),"semantica:text": entity.get("text") or entity.get("label", ""),- "semantica:confidence": entity.get("confidence", 1.0),}+ confidence = normalize_confidence(entity.get("confidence", 1.0))+ 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:+ # A native JSON number becomes xsd:double once expanded, so the+ # value is written as a typed literal instead.+ node["semantica:confidence"] = {+ "@value": confidence,+ "@type": CONFIDENCE_DATATYPE,+ }+ node.update(+ _jsonld_metadata_entries(+ _metadata_statements(+ entity.get("metadata"), metadata_terms, self.logger+ )+ )+ )jsonld["@graph"].append(node)# Convert relationships to JSON-LD@@@ -969,22 -843,22 +1115,31 @@@f'{subject} {expand_uri("semantica:text")} "{safe_text}" .')- # Confidence property- confidence = entity.get("confidence")- if confidence is not None:+ # Confidence property. The default matches the other serializers,+ # which have always written one; omitting it here was half of why+ # Turtle and N-Triples of one KG were different graphs (#1100).+ raw_confidence = entity.get("confidence", 1.0)+ confidence = normalize_confidence(raw_confidence)+ if confidence is None:+ self.logger.warning(+ f"Entity {entity.get('id')} has a confidence that is not a "+ f"number ({raw_confidence!r}), so no confidence is written"+ )+ else:lines.append(- f'{subject} {expand_uri("semantica:confidence")} "{confidence}"^^<http://www.w3.org/2001/XMLSchema#float> .'+ f'{subject} {expand_uri("semantica:confidence")} '+ f'"{confidence}"^^<{CONFIDENCE_DATATYPE}> .')+ lines.extend(+ _ntriples_metadata_lines(+ subject.strip("<>"),+ _metadata_statements(+ entity.get("metadata"), metadata_terms, self.logger+ ),+ )+ )+# Convert relationshipsrelationships = rdf_data.get("relationships", [])for rel in relationships: