|
| 1 | +""" |
| 2 | +This file provides a single function `serialize_in_chunks()` which can serialize a |
| 3 | +Graph into a number of NT files with a maximum number of triples or maximum file size. |
| 4 | +
|
| 5 | +There is an option to preserve any prefixes declared for the original graph in the first |
| 6 | +file, which will be a Turtle file. |
| 7 | +""" |
| 8 | + |
| 9 | +from contextlib import ExitStack, contextmanager |
| 10 | +from pathlib import Path |
| 11 | +from typing import TYPE_CHECKING, BinaryIO, Generator, Optional, Tuple |
| 12 | + |
| 13 | +from rdflib.graph import Graph |
| 14 | +from rdflib.plugins.serializers.nt import _nt_row |
| 15 | + |
| 16 | +# from rdflib.term import Literal |
| 17 | + |
| 18 | +# if TYPE_CHECKING: |
| 19 | +# from rdflib.graph import _TriplePatternType |
| 20 | + |
| 21 | +__all__ = ["serialize_in_chunks"] |
| 22 | + |
| 23 | + |
| 24 | +def serialize_in_chunks( |
| 25 | + g: Graph, |
| 26 | + max_triples: int = 10000, |
| 27 | + max_file_size_kb: Optional[int] = None, |
| 28 | + file_name_stem: str = "chunk", |
| 29 | + output_dir: Optional[Path] = None, |
| 30 | + write_prefixes: bool = False, |
| 31 | +) -> None: |
| 32 | + """ |
| 33 | + Serializes a given Graph into a series of n-triples with a given length. |
| 34 | +
|
| 35 | + :param g: |
| 36 | + The graph to serialize. |
| 37 | +
|
| 38 | + :param max_file_size_kb: |
| 39 | + Maximum size per NT file in kB (1,000 bytes) |
| 40 | + Equivalent to ~6,000 triples, depending on Literal sizes. |
| 41 | +
|
| 42 | + :param max_triples: |
| 43 | + Maximum size per NT file in triples |
| 44 | + Equivalent to lines in file. |
| 45 | +
|
| 46 | + If both this parameter and max_file_size_kb are set, max_file_size_kb will be used. |
| 47 | +
|
| 48 | + :param file_name_stem: |
| 49 | + Prefix of each file name. |
| 50 | + e.g. "chunk" = chunk_000001.nt, chunk_000002.nt... |
| 51 | +
|
| 52 | + :param output_dir: |
| 53 | + The directory you want the files to be written to. |
| 54 | +
|
| 55 | + :param write_prefixes: |
| 56 | + The first file created is a Turtle file containing original graph prefixes. |
| 57 | +
|
| 58 | +
|
| 59 | + See ``../test/test_tools/test_chunk_serializer.py`` for examples of this in use. |
| 60 | + """ |
| 61 | + |
| 62 | + if output_dir is None: |
| 63 | + output_dir = Path.cwd() |
| 64 | + |
| 65 | + if not output_dir.is_dir(): |
| 66 | + raise ValueError( |
| 67 | + "If you specify an output_dir, it must actually be a directory!" |
| 68 | + ) |
| 69 | + |
| 70 | + @contextmanager |
| 71 | + def _start_new_file(file_no: int) -> Generator[Tuple[Path, BinaryIO], None, None]: |
| 72 | + if TYPE_CHECKING: |
| 73 | + # this is here because mypy gets a bit confused |
| 74 | + assert output_dir is not None |
| 75 | + fp = Path(output_dir) / f"{file_name_stem}_{str(file_no).zfill(6)}.nt" |
| 76 | + with open(fp, "wb") as fh: |
| 77 | + yield fp, fh |
| 78 | + |
| 79 | + def _serialize_prefixes(g: Graph) -> str: |
| 80 | + pres = [] |
| 81 | + for k, v in g.namespace_manager.namespaces(): |
| 82 | + pres.append(f"PREFIX {k}: <{v}>") |
| 83 | + |
| 84 | + return "\n".join(sorted(pres)) + "\n" |
| 85 | + |
| 86 | + if write_prefixes: |
| 87 | + with open( |
| 88 | + Path(output_dir) / f"{file_name_stem}_000000.ttl", "w", encoding="utf-8" |
| 89 | + ) as fh: |
| 90 | + fh.write(_serialize_prefixes(g)) |
| 91 | + |
| 92 | + bytes_written = 0 |
| 93 | + with ExitStack() as xstack: |
| 94 | + if max_file_size_kb is not None: |
| 95 | + max_file_size = max_file_size_kb * 1000 |
| 96 | + file_no = 1 if write_prefixes else 0 |
| 97 | + for i, t in enumerate(g.triples((None, None, None))): |
| 98 | + row_bytes = _nt_row(t).encode("utf-8") |
| 99 | + if len(row_bytes) > max_file_size: |
| 100 | + raise ValueError( |
| 101 | + f"cannot write triple {t!r} as it's serialized size of {row_bytes / 1000} exceeds max_file_size_kb = {max_file_size_kb}" |
| 102 | + ) |
| 103 | + if i == 0: |
| 104 | + fp, fhb = xstack.enter_context(_start_new_file(file_no)) |
| 105 | + bytes_written = 0 |
| 106 | + elif (bytes_written + len(row_bytes)) >= max_file_size: |
| 107 | + file_no += 1 |
| 108 | + fp, fhb = xstack.enter_context(_start_new_file(file_no)) |
| 109 | + bytes_written = 0 |
| 110 | + |
| 111 | + bytes_written += fhb.write(row_bytes) |
| 112 | + |
| 113 | + else: |
| 114 | + # count the triples in the graph |
| 115 | + graph_length = len(g) |
| 116 | + |
| 117 | + if graph_length <= max_triples: |
| 118 | + # the graph is less than max so just NT serialize the whole thing |
| 119 | + g.serialize( |
| 120 | + destination=Path(output_dir) / f"{file_name_stem}_all.nt", |
| 121 | + format="nt", |
| 122 | + ) |
| 123 | + else: |
| 124 | + # graph_length is > max_lines, make enough files for all graph |
| 125 | + # no_files = math.ceil(graph_length / max_triples) |
| 126 | + file_no = 1 if write_prefixes else 0 |
| 127 | + for i, t in enumerate(g.triples((None, None, None))): |
| 128 | + if i % max_triples == 0: |
| 129 | + fp, fhb = xstack.enter_context(_start_new_file(file_no)) |
| 130 | + file_no += 1 |
| 131 | + fhb.write(_nt_row(t).encode("utf-8")) |
| 132 | + return |
0 commit comments