Coverage for lode / artefact.py: 100%

86 statements  

« prev     ^ index     » next       coverage.py v7.13.0, created at 2026-11-22 15:54 +0000

1"""Artefact: a semantic artefact read from a source, with everything extracted from it. 

2 

3The Artefact is the hand-over between the reader and everything else: `lode.reader.read_into` 

4writes its fields once, and the viewers, the static builder and the API read only from it. 

5This keeps the Reader/Model/Viewer layers independent. 

6""" 

7from typing import Any, Callable, Optional 

8 

9from rdflib import Graph, URIRef 

10 

11from lode import profiles 

12from lode.helpers.rdf import iri_namespace 

13from lode.profiles import Profile 

14from lode.provenance_graph import ProvenanceGraph 

15 

16# Prefix of the literal entries in the reader's entity cache. Literals are values, 

17# not entities, and must never be listed as such. 

18_LITERAL_PREFIX = "LITERAL::" 

19 

20 

21def _no_provenance(entity) -> Graph: 

22 """Return an empty subgraph: the provenance of an artefact built without a reader.""" 

23 return Graph() 

24 

25 

26class Artefact: 

27 """A semantic artefact after extraction: its entities, its RDF graph and its provenance. 

28 

29 `profile` is the format it was read as (None for an artefact built by hand). The reader 

30 sets the rest: `entities` is the entity cache shared by reference with `reader`, not a 

31 copy, and consumers must treat it as read-only; `reader` is the reader of the format after 

32 extraction, kept for inspection and never used by the viewers; `provenance` is a callable 

33 that returns the subgraph an entity was built from, computed only when asked for because 

34 most entities are never inspected. The annotations below are the contract with the 

35 reader, which writes these fields by name. 

36 """ 

37 

38 profile: Optional[Profile] 

39 entities: dict 

40 graph: Graph 

41 artefact_iri: Optional[URIRef] 

42 imported_uris: set 

43 warnings: list 

44 provenance: Callable[[Any], Graph] 

45 reader: Optional[Any] 

46 

47 def __init__(self, source: str, *, imported: Optional[bool] = None, 

48 closure: Optional[bool] = None, partial_import: Optional[bool] = None, 

49 warnings: bool = False, source_name: Optional[str] = None): 

50 """Read `source` with the format of this class and keep what the extraction produces. 

51 

52 Called on a format class (OwlOntology, SkosVocabulary or a plugin's own), never on 

53 Artefact itself: the class is how the format is chosen, and a caller that only has 

54 the name of a format uses lode.read(source, read_as). `source` is a local path or a 

55 public http(s) URL; the other arguments are those of `lode.reader.read_into`. 

56 Blocking: it may fetch remote documents. 

57 """ 

58 profile = profiles.of(type(self)) 

59 if profile is None: 

60 raise TypeError(f"{type(self).__name__} has no format: read with a format class " 

61 "such as OwlOntology, or with lode.read(source, read_as)") 

62 # Local import on purpose: the reader pulls in the models and the reader of every 

63 # format, which `import lode` and the viewers do not need. It imports nothing from 

64 # this module, so there is no cycle. 

65 from lode.reader import read_into 

66 

67 self._blank(profile) 

68 read_into(self, source, imported=imported, closure=closure, 

69 partial_import=partial_import, warnings=warnings, source_name=source_name) 

70 

71 @classmethod 

72 def from_parts(cls, entities: dict, graph: Graph, artefact_iri: Optional[URIRef] = None, 

73 imported_uris: Optional[set] = None, warnings: Optional[list] = None, 

74 profile: Optional[Profile] = None) -> "Artefact": 

75 """Build an artefact from data already in memory, without reading anything. 

76 

77 For tests and for callers that have the graph and the entities by other means; the 

78 fields not given stay empty. Without `profile`, a format class gets its own. 

79 """ 

80 artefact = cls.__new__(cls) 

81 artefact._blank(profile if profile is not None else profiles.of(cls)) 

82 artefact.entities = entities 

83 artefact.graph = graph 

84 artefact.artefact_iri = artefact_iri 

85 artefact.imported_uris = imported_uris if imported_uris is not None else set() 

86 artefact.warnings = warnings if warnings is not None else [] 

87 return artefact 

88 

89 def _blank(self, profile: Optional[Profile]) -> None: 

90 """Give every field its empty value, so that the reader only has to overwrite them.""" 

91 self.profile = profile 

92 self.entities = {} 

93 self.graph = Graph() 

94 self.artefact_iri = None 

95 self.imported_uris = set() 

96 self.warnings = [] 

97 self.provenance = _no_provenance 

98 self.reader = None 

99 self._all = None 

100 self._viewer = None 

101 

102 @property 

103 def read_as(self) -> Optional[str]: 

104 """Return the name of the format the artefact was read as, or None when unknown.""" 

105 return self.profile.name if self.profile else None 

106 

107 @property 

108 def artefact_base_iri(self) -> Optional[URIRef]: 

109 """Return the namespace of the artefact IRI, derived on demand, or None without an IRI.""" 

110 return URIRef(iri_namespace(self.artefact_iri)) if self.artefact_iri else None 

111 

112 @property 

113 def viewer(self): 

114 """Return the viewer of this artefact's format, created on first use and then reused. 

115 

116 Its profile gives it its configuration, so the page data, the exports and the 

117 templates all come from here; an artefact without a profile gets the generic viewer. 

118 """ 

119 if self._viewer is None: 

120 # Local import: the viewers pull in the YAML configuration, which reading does 

121 # not need. The viewer package imports nothing from this module, so no cycle. 

122 from lode.viewer import get_viewer 

123 

124 self._viewer = get_viewer(self) 

125 return self._viewer 

126 

127 def get_entities(self, cls: Optional[type] = None) -> list: 

128 """Return the extracted entities, optionally only those of one model class. 

129 

130 `cls` is a model class (Concept, Relation): its subclasses are included, as 

131 with isinstance, so Resource gives every entity. Literals are not entities 

132 and are never returned. Passing anything that is not a class, such as the 

133 class name, raises TypeError. The full list is built once and reused, because 

134 a static build asks for it on every page: `entities` must not change after the 

135 artefact is built. 

136 """ 

137 if self._all is None: 

138 self._all = [ 

139 entity 

140 for key, group in self.entities.items() 

141 if not (isinstance(key, str) and key.startswith(_LITERAL_PREFIX)) 

142 for entity in (group if isinstance(group, set) else [group]) 

143 ] 

144 if cls is None: 

145 return list(self._all) 

146 return [i for i in self._all if isinstance(i, cls)] 

147 

148 def get_entities_by_iri(self, iri: str) -> Optional[set]: 

149 """Return the entities registered under an IRI, or None when it is unknown. 

150 

151 More than one entity comes back for a punned IRI (same IRI used as a 

152 class and as an individual). The lookup scans the keys because they are 

153 rdflib terms, which do not compare equal to a plain string. 

154 """ 

155 for key, group in self.entities.items(): 

156 if str(key) == iri: 

157 return group 

158 return None 

159 

160 def main_graph(self) -> Graph: 

161 """Return the triples of the loaded artefact only, as a plain Graph view. 

162 

163 Imported and partially imported ontologies are left out: this is what 

164 exports and content negotiation must return. Without modules it is the 

165 loaded graph itself. 

166 """ 

167 if isinstance(self.graph, ProvenanceGraph): 

168 return self.graph.graph(self.artefact_iri) 

169 return self.graph 

170 

171 def with_provenance(self, sub: Graph) -> ProvenanceGraph: 

172 """Return `sub` as quads, each triple in the named graph(s) it comes from. 

173 

174 With modules active the graphs are the ones of the source ontologies; 

175 without, every triple goes in the graph of the loaded artefact. It lives 

176 here and not in a viewer because it only needs the graph: the viewer just 

177 asks for the result. 

178 """ 

179 ds = self.graph 

180 out = ProvenanceGraph() 

181 for prefix, ns in ds.namespaces(): 

182 out.bind(prefix, ns) 

183 if isinstance(ds, ProvenanceGraph): 

184 for s, p, o in sub: 

185 for *_, c in ds.quads((s, p, o, None)): 

186 out.graph(c).add((s, p, o)) 

187 else: 

188 main = out.graph(self.artefact_iri) 

189 for t in sub: 

190 main.add(t) 

191 return out