Coverage for target/native-coverage/profiles/11fb979bfcf049d7ab666c331dc8db2a/project/.venv/lib/python3.13/site-packages/pyshacl_turbo/rdf.py: 100%

330 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-30 14:51 +0000

1"""RDF I/O only. Parsing and lexical term preservation use the native parser.""" 

2 

3import sys 

4from dataclasses import dataclass, field 

5from decimal import localcontext 

6from io import StringIO 

7from pathlib import Path 

8from urllib.parse import urlparse 

9from urllib.request import Request, url2pathname, urlopen 

10 

11from rdflib import BNode, Literal, URIRef 

12from rdflib.graph import ConjunctiveGraph, Dataset, Graph 

13from rdflib.namespace import OWL, NamespaceManager 

14from rdflib.plugins.parsers.nquads import NQuadsParser 

15from rdflib.plugins.parsers.ntriples import ( 

16 ParseError, 

17 W3CNTriplesParser, 

18 r_literal, 

19 r_tail, 

20 r_wspace, 

21 unquote, 

22 uriquote, 

23) 

24from rdflib.util import guess_format 

25 

26from . import _native 

27from .term_input import _TermBatch 

28 

29 

30class _Parser(NQuadsParser): 

31 def literal(self): 

32 if not self.peek('"'): 

33 return False 

34 lexical, language, datatype = self.eat(r_literal).groups() 

35 datatype = URIRef(uriquote(unquote(datatype))) if datatype else None 

36 return Literal(unquote(lexical), language or None, datatype, normalize=False) 

37 

38 def parseline(self, bnode_context=None): 

39 self.eat(r_wspace) 

40 if not self.line or self.line.startswith("#"): 

41 return 

42 subject = self.subject(bnode_context) 

43 self.eat(r_wspace) 

44 predicate = self.predicate() 

45 self.eat(r_wspace) 

46 value = self.object(bnode_context) 

47 self.eat(r_wspace) 

48 context = self.uriref() or self.nodeid(bnode_context) 

49 self.eat(r_tail) 

50 if self.line: 

51 raise ParseError("Trailing content in native RDF output") 

52 graph = self.sink.graph(context) if context else self.sink.default_graph 

53 graph.add((subject, predicate, value)) 

54 

55 

56class _NativeBlankNodes(dict): 

57 def get(self, key, default=None): 

58 return self.setdefault(key, BNode(key)) 

59 

60 

61def _decoded_dataset(bind_namespaces): 

62 result = Dataset(default_union=True) 

63 if bind_namespaces != "rdflib": 

64 result.namespace_manager = NamespaceManager(result, bind_namespaces) 

65 result.default_graph.namespace_manager = result.namespace_manager 

66 return result 

67 

68 

69def decode( 

70 source, 

71 blank_nodes=None, 

72 multigraph=False, 

73 preserve_ids=False, 

74 identifier=None, 

75 *, 

76 report=False, 

77 normalize=None, 

78 _report_conforms=None, 

79 _bind_namespaces="rdflib", 

80): 

81 if report: 

82 from .report_decode import decode_report 

83 

84 return decode_report( 

85 source, 

86 blank_nodes, 

87 multigraph, 

88 preserve_ids, 

89 identifier, 

90 normalize, 

91 conforms=_report_conforms, 

92 ) 

93 if _report_conforms is not None: 

94 raise ValueError("Native conformance context requires report decoding") 

95 if not isinstance(source, str): 

96 return _decode_terms( 

97 source, 

98 blank_nodes, 

99 multigraph, 

100 preserve_ids, 

101 identifier, 

102 _bind_namespaces=_bind_namespaces, 

103 ) 

104 dataset = _decoded_dataset(_bind_namespaces) 

105 parser = _Parser() 

106 parser.sink = dataset 

107 nodes = blank_nodes if blank_nodes is not None else {} 

108 if preserve_ids: 

109 nodes = _NativeBlankNodes(nodes) 

110 W3CNTriplesParser.parse(parser, StringIO(source), bnode_context=nodes) 

111 named = any(g.identifier != dataset.default_graph.identifier for g in dataset.graphs()) 

112 if multigraph or named: 

113 return dataset 

114 graph = Graph(identifier=identifier, bind_namespaces=_bind_namespaces) 

115 graph += dataset.default_graph 

116 return graph 

117 

118 

119def _decode_terms( 

120 source, 

121 blank_nodes, 

122 multigraph, 

123 preserve_ids, 

124 identifier, 

125 *, 

126 copied_subjects=None, 

127 generated_boolean=None, 

128 boolean_values=None, 

129 selected_values=None, 

130 normalize=None, 

131 _bind_namespaces="rdflib", 

132): 

133 records, quads = source 

134 nodes = blank_nodes if blank_nodes is not None else {} 

135 if preserve_ids: 

136 nodes = _NativeBlankNodes(nodes) 

137 terms = [] 

138 for kind, value, datatype, language in records: 

139 if kind == 0: 

140 term = URIRef(value) 

141 elif kind == 1: 

142 term = nodes.get(value) 

143 if term is None: 

144 term = nodes.setdefault(value, BNode()) 

145 elif kind == 2: 

146 term = ( 

147 Literal(value, language, URIRef(datatype) if datatype else None, normalize=False) 

148 if copied_subjects is None 

149 else None 

150 ) 

151 else: 

152 raise ValueError("Invalid native RDF term record") 

153 terms.append(term) 

154 if copied_subjects is not None: 

155 # Direct report terms restore existing values; conversion must not signal again. 

156 # One report-local context and the existing terms vector avoid per-term contexts. 

157 with localcontext(): 

158 for quad_index, quad in enumerate(quads): 

159 subject, _, obj, _ = quad 

160 if boolean_values is not None and quad_index in boolean_values: 

161 continue 

162 if generated_boolean is not None and tuple(quad) == generated_boolean[0]: 

163 continue 

164 if subject not in copied_subjects and records[obj][0] == 2 and terms[obj] is None: 

165 _, lexical, datatype, language = records[obj] 

166 terms[obj] = Literal( 

167 lexical, 

168 language, 

169 URIRef(datatype) if datatype else None, 

170 normalize=False, 

171 ) 

172 named = multigraph or any(g is not None for _, _, _, g in quads) 

173 result = ( 

174 _decoded_dataset(_bind_namespaces) 

175 if named 

176 else Graph(identifier=identifier, bind_namespaces=_bind_namespaces) 

177 ) 

178 for quad_index, quad in enumerate(quads): 

179 s, p, o, g = quad 

180 destination = ( 

181 (result.default_graph if g is None else result.graph(terms[g])) if named else result 

182 ) 

183 value = terms[o] 

184 if generated_boolean is not None and tuple(quad) == generated_boolean[0]: 

185 value = Literal(generated_boolean[1], normalize=False) 

186 elif selected_values is not None and quad_index in selected_values: 

187 value = selected_values[quad_index] 

188 elif boolean_values is not None and quad_index in boolean_values: 

189 from rdflib_turbo._literal import restore_boolean 

190 

191 value = restore_boolean(records[o][1], *boolean_values[quad_index]) 

192 elif copied_subjects is not None and records[o][0] == 2: 

193 copied = s in copied_subjects 

194 if copied: 

195 _, lexical, datatype, language = records[o] 

196 value = Literal( 

197 lexical, 

198 language, 

199 URIRef(datatype) if datatype else None, 

200 normalize=normalize, 

201 ) 

202 destination.add((terms[s], terms[p], value)) 

203 return result 

204 

205 

206def _term_input( 

207 source, *, flatten=False, observe_booleans=False, dataset_factory=None, borrow=False, view=None 

208): 

209 nodes = {} 

210 if observe_booleans: 

211 native = _native.BooleanInput( 

212 source, 

213 nodes, 

214 flatten, 

215 _terms=(URIRef, BNode, Literal), 

216 _dataset=dataset_factory, 

217 _view=view if borrow else None, 

218 ) 

219 return Input(native, "terms", None, nodes, dict(source.namespaces())) 

220 batch = _TermBatch(nodes) 

221 if source.context_aware: 

222 default = ( 

223 source.default_graph.identifier 

224 if isinstance(source, Dataset) 

225 else source.default_context.identifier 

226 ) 

227 for s, p, o, g in source.quads(): 

228 context = getattr(g, "identifier", g) 

229 batch.append(s, p, o, None if flatten or context == default else context) 

230 else: 

231 for s, p, o in source: 

232 batch.append(s, p, o) 

233 return Input((batch.records, batch.quads), "terms", None, nodes, dict(source.namespaces())) 

234 

235 

236def shape_batches(source, nodes): 

237 """Transfer exact shapes quads with bounded input ownership.""" 

238 batch = _TermBatch(nodes, preserve_empty_datatypes=True) 

239 if source.context_aware: 

240 default = ( 

241 source.default_graph.identifier 

242 if isinstance(source, Dataset) 

243 else source.default_context.identifier 

244 ) 

245 rows = ( 

246 (s, p, o, getattr(g, "identifier", g)) 

247 for s, p, o, g in source.quads((None, None, None, None)) 

248 ) 

249 else: 

250 default = None 

251 rows = ((s, p, o, None) for s, p, o in source) 

252 limit = _native.SHAPES_BATCH_SIZE 

253 for s, p, o, graph in rows: 

254 batch.append(s, p, o, None if graph == default else graph, retain_graph_owner=False) 

255 if len(batch.quads) == limit: 

256 yield batch.records, batch.quads 

257 batch = _TermBatch(nodes, preserve_empty_datatypes=True) 

258 if batch.quads: 

259 yield batch.records, batch.quads 

260 

261 

262def shape_graphs(source, nodes): 

263 """Retain declared named contexts, including empty contexts, as typed names.""" 

264 if not source.context_aware: 

265 return 

266 if isinstance(source, Dataset): 

267 default = source.default_graph.identifier 

268 contexts = source.graphs() 

269 else: 

270 default = source.default_context.identifier 

271 contexts = source.contexts() 

272 for context in contexts: 

273 if context.identifier != default: 

274 batch = _TermBatch(nodes) 

275 batch.intern(context.identifier, retain_blank_owner=False) 

276 yield batch.records[0] 

277 

278 

279def union(source): 

280 graph = Graph() 

281 for prefix, namespace in source.namespaces(): 

282 graph.bind(prefix, namespace) 

283 if source.context_aware: 

284 for s, p, o, _ in source.quads((None, None, None, None)): 

285 graph.add((s, p, o)) 

286 else: 

287 graph += source 

288 return graph 

289 

290 

291def _document(source, rdf_format): 

292 base = None 

293 if hasattr(source, "read"): 

294 body = source.read() 

295 if getattr(source, "name", None): 

296 base = Path(source.name).resolve().as_uri() 

297 elif isinstance(source, Path): 

298 source = source.resolve(strict=True) 

299 base, body = source.as_uri(), source.read_bytes() 

300 rdf_format = rdf_format or guess_format(source.name) 

301 elif isinstance(source, bytes): 

302 body = source 

303 elif isinstance(source, str): 

304 stripped = source.lstrip() 

305 if stripped.startswith(("http://", "https://", "file:")) and "\n" not in source: 

306 if stripped.startswith("file:"): 

307 return _document(Path(url2pathname(urlparse(source).path)), rdf_format) 

308 request = Request( 

309 source, 

310 headers={ 

311 "Accept": "text/turtle,application/rdf+xml,application/ld+json,application/n-quads" 

312 }, 

313 ) 

314 with urlopen(request, timeout=30) as response: 

315 base, body = response.geturl(), response.read() 

316 media = response.headers.get_content_type() 

317 rdf_format = ( 

318 rdf_format 

319 or { 

320 "text/turtle": "turtle", 

321 "application/rdf+xml": "xml", 

322 "application/ld+json": "json-ld", 

323 "application/n-quads": "nquads", 

324 "application/trig": "trig", 

325 "application/n-triples": "nt", 

326 }.get(media) 

327 or guess_format(urlparse(base).path) 

328 ) 

329 elif "\n" in source or stripped.startswith(("@", "PREFIX", "BASE", "<", "{", "[", "#")): 

330 body = source 

331 else: 

332 return _document(Path(source), rdf_format) 

333 else: 

334 raise TypeError("Expected an RDF graph, RDF text, bytes, file, path or URL") 

335 text = body.decode("utf-8-sig") if isinstance(body, bytes) else body 

336 if rdf_format is None: 

337 stripped = text.lstrip() 

338 if stripped.startswith(("{", "[")): 

339 rdf_format = "json-ld" 

340 elif stripped.startswith("<?xml") or "<rdf:RDF" in stripped[:500]: 

341 rdf_format = "xml" 

342 else: 

343 rdf_format = "turtle" 

344 return text, rdf_format, base or Path.cwd().as_uri() + "/" 

345 

346 

347def load_from_source( 

348 source, 

349 *, 

350 g=None, 

351 rdf_format=None, 

352 multigraph=False, 

353 do_owl_imports=False, 

354 logger=None, 

355 _bind_namespaces="rdflib", 

356 **kwargs, 

357): 

358 if kwargs: 

359 raise TypeError(f"Unsupported loader options: {', '.join(sorted(kwargs))}") 

360 if isinstance(source, Graph): 

361 result = source 

362 elif isinstance(source, Input): 

363 text = source.source 

364 if source.format == "oxigraph-nquads": 

365 text, _ = _native.parse_rdf(text, source.format, source.base) 

366 result = decode( 

367 text, 

368 source.blank_nodes, 

369 multigraph=multigraph, 

370 preserve_ids=source.preserve_ids, 

371 _bind_namespaces=_bind_namespaces, 

372 ) 

373 elif is_oxigraph_store(source): 

374 snapshot = input_graph(source) 

375 result = load_from_source( 

376 snapshot, multigraph=multigraph, _bind_namespaces=_bind_namespaces 

377 ) 

378 else: 

379 text, rdf_format, base = _document(source, rdf_format) 

380 nquads, prefixes = _native.parse_rdf(text, rdf_format, base) 

381 result = decode(nquads, multigraph=multigraph, _bind_namespaces=_bind_namespaces) 

382 for prefix, namespace in prefixes: 

383 result.bind(prefix, namespace) 

384 if do_owl_imports: 

385 result = union(result) 

386 visited = set() 

387 pending = list(result.objects(None, OWL.imports)) 

388 while pending: 

389 url = pending.pop() 

390 if url in visited: 

391 continue 

392 if not isinstance(url, URIRef): 

393 raise TypeError(f"owl:imports must name an IRI: {url}") 

394 visited.add(url) 

395 imported = load_from_source(str(url)) 

396 result += union(imported) 

397 pending.extend(imported.objects(None, OWL.imports)) 

398 if g is not None: 

399 for triple in union(result): 

400 g.add(triple) 

401 return g 

402 return result 

403 

404 

405@dataclass 

406class Input: 

407 source: str | tuple 

408 format: str 

409 base: str | None 

410 blank_nodes: dict 

411 namespaces: dict = field(default_factory=dict) 

412 preserve_ids: bool = False 

413 

414 

415def is_oxigraph_store(source): 

416 module = sys.modules.get("pyoxigraph") 

417 return module is not None and isinstance(source, module.Store) 

418 

419 

420def commit_serialized(target, source, nodes=None, *, before=None): 

421 if is_oxigraph_store(target): 

422 import pyoxigraph 

423 

424 if before is None: 

425 raise ValueError("Store commits require the original input snapshot") 

426 source = _native.additions(before.source, before.format, source) 

427 # extend is atomic, and parse preserves labels shared with existing data. 

428 target.extend( 

429 pyoxigraph.parse(source, format=pyoxigraph.RdfFormat.N_QUADS, rename_blank_nodes=False) 

430 ) 

431 elif isinstance(target, Input): 

432 target.source = source 

433 target.format = "nquads" if isinstance(source, str) else "terms" 

434 else: 

435 if before is not None: 

436 source = _native.additions(before.source, before.format, source) 

437 merge_graph(target, decode(source, nodes, preserve_ids=True)) 

438 

439 

440def input_graph( 

441 source, 

442 rdf_format=None, 

443 *, 

444 flatten=False, 

445 direct=False, 

446 observe_booleans=False, 

447 _dataset_factory=None, 

448 _borrow=False, 

449): 

450 from .graph_abstraction import DataGraph, _reject_native_store_graph 

451 

452 view = source if isinstance(source, DataGraph) else None 

453 if view is not None: 

454 source = source.impl 

455 _reject_native_store_graph(source) 

456 if isinstance(source, Input): 

457 if flatten: 

458 return input_graph(load_from_source(source), flatten=True) 

459 return source 

460 if is_oxigraph_store(source) and not flatten: 

461 import pyoxigraph 

462 

463 return Input( 

464 source.dump(format=pyoxigraph.RdfFormat.N_QUADS).decode("utf-8"), 

465 "nquads", 

466 None, 

467 {}, 

468 preserve_ids=True, 

469 ) 

470 if not isinstance(source, Graph): 

471 source = load_from_source(source, rdf_format=rdf_format) 

472 if direct: 

473 borrow = _borrow and not source.context_aware 

474 if borrow and view is None: 

475 view = DataGraph.from_rdflib_graph(source) 

476 return _term_input( 

477 source, 

478 flatten=flatten, 

479 observe_booleans=observe_booleans, 

480 dataset_factory=_dataset_factory, 

481 borrow=borrow, 

482 view=view if borrow else None, 

483 ) 

484 graph = union(source) if source.context_aware else source 

485 nodes = {str(n): n for n in graph.all_nodes() if isinstance(n, BNode)} 

486 if source.context_aware and not flatten: 

487 lines = [] 

488 contexts = source.contexts() if _legacy_context_graph(source) else source.graphs() 

489 for context in contexts: 

490 suffix = ( 

491 "" 

492 if context.identifier == _default_context(source).identifier 

493 else " " + context.identifier.n3() 

494 ) 

495 if isinstance(context.identifier, BNode): 

496 nodes[str(context.identifier)] = context.identifier 

497 # RDFLib's NT serializer emits one triple per line and no lines for 

498 # an empty context; escaped literal newlines stay inside that line. 

499 for line in context.serialize(format="nt").splitlines(): 

500 lines.append(line.rstrip().removesuffix(".").rstrip() + suffix + " .") 

501 return Input("\n".join(lines), "nquads", None, nodes, dict(source.namespaces())) 

502 return Input(graph.serialize(format="nt"), "nt", None, nodes, dict(source.namespaces())) 

503 

504 

505def copy_graph(source): 

506 from .graph_abstraction import _reject_native_store_graph 

507 

508 _reject_native_store_graph(source) 

509 if not source.context_aware: 

510 return union(source) 

511 result = Dataset(default_union=True) 

512 for context in source.graphs(): 

513 target = ( 

514 result.default_graph 

515 if context.identifier == source.default_graph.identifier 

516 else result.graph(context.identifier) 

517 ) 

518 target += context 

519 for prefix, namespace in source.namespaces(): 

520 result.bind(prefix, namespace) 

521 return result 

522 

523 

524def _legacy_context_graph(graph): 

525 return isinstance(graph, ConjunctiveGraph) and not isinstance(graph, Dataset) 

526 

527 

528def _default_context(graph): 

529 return graph.default_context if _legacy_context_graph(graph) else graph.default_graph 

530 

531 

532def merge_graph(target, source): 

533 from .graph_abstraction import DataGraph, _reject_native_store_graph 

534 

535 if isinstance(target, DataGraph): 

536 target = target.impl 

537 if isinstance(source, DataGraph): 

538 source = source.impl 

539 _reject_native_store_graph(target) 

540 _reject_native_store_graph(source) 

541 if source.context_aware and target.context_aware: 

542 contexts = source.contexts() if _legacy_context_graph(source) else source.graphs() 

543 for context in contexts: 

544 destination = ( 

545 _default_context(target) 

546 if context.identifier == _default_context(source).identifier 

547 else ( 

548 target.get_context(context.identifier) 

549 if _legacy_context_graph(target) 

550 else target.graph(context.identifier) 

551 ) 

552 ) 

553 destination += context 

554 elif target.context_aware: 

555 destination = _default_context(target) 

556 destination += source 

557 else: 

558 target += union(source) if source.context_aware else source 

559 return target