File size: 5,098 Bytes
91ac3cc | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 | from __future__ import annotations
import gzip
import json
from collections.abc import Iterator, Sequence
from pathlib import Path
from typing import Any, TextIO
import glob
SUPPORTED_SUFFIXES = (".jsonl", ".jsonl.gz", ".txt", ".txt.gz")
def discover_paths(inputs: Sequence[str | Path]) -> list[Path]:
found: set[Path] = set()
for raw_input in inputs:
raw = str(raw_input)
path = Path(raw)
if path.is_dir():
for candidate in path.rglob("*"):
if candidate.is_file() and any(
str(candidate).lower().endswith(suffix)
for suffix in SUPPORTED_SUFFIXES
):
found.add(candidate.resolve())
continue
matches = [Path(item) for item in glob.glob(raw, recursive=True)]
if matches:
found.update(item.resolve() for item in matches if item.is_file())
elif path.is_file():
found.add(path.resolve())
return sorted(found)
def open_text(path: Path) -> TextIO:
if path.name.lower().endswith(".gz"):
return gzip.open(path, "rt", encoding="utf-8", errors="replace")
return path.open("r", encoding="utf-8", errors="replace")
def iter_documents(
paths: Sequence[Path],
*,
text_field: str = "text",
txt_mode: str = "line",
) -> Iterator[dict[str, Any]]:
if txt_mode not in {"line", "document"}:
raise ValueError("txt_mode must be 'line' or 'document'")
for path in paths:
lower_name = path.name.lower()
source_default = path.name.removesuffix(".gz")
if lower_name.endswith((".jsonl", ".jsonl.gz")):
with open_text(path) as handle:
for line_number, line in enumerate(handle, start=1):
if not line.strip():
continue
try:
row = json.loads(line)
except json.JSONDecodeError as error:
raise ValueError(
f"Invalid JSON at {path}:{line_number}: {error}"
) from error
if not isinstance(row, dict):
raise ValueError(
f"Expected a JSON object at {path}:{line_number}"
)
text = row.get(text_field)
if not isinstance(text, str):
continue
yield {
"id": row.get("id", f"{path.name}:{line_number}"),
"text": text,
"source": row.get("source", source_default),
"url": row.get("url"),
"license": row.get("license"),
}
continue
if lower_name.endswith((".txt", ".txt.gz")):
with open_text(path) as handle:
if txt_mode == "document":
text = handle.read()
if text.strip():
yield {
"id": path.name,
"text": text,
"source": source_default,
"url": None,
"license": None,
}
else:
for line_number, line in enumerate(handle, start=1):
if line.strip():
yield {
"id": f"{path.name}:{line_number}",
"text": line.rstrip("\n"),
"source": source_default,
"url": None,
"license": None,
}
class ShardedJsonlWriter:
def __init__(
self,
output_dir: Path,
split: str,
*,
documents_per_shard: int,
) -> None:
self.output_dir = output_dir
self.split = split
self.documents_per_shard = documents_per_shard
self.document_count = 0
self.shard_index = -1
self._handle: TextIO | None = None
def _open_next(self) -> None:
if self._handle is not None:
self._handle.close()
self.shard_index += 1
path = self.output_dir / f"{self.split}-{self.shard_index:05d}.jsonl"
self._handle = path.open("w", encoding="utf-8", newline="\n")
def write(self, row: dict[str, Any]) -> None:
if self._handle is None or self.document_count % self.documents_per_shard == 0:
self._open_next()
assert self._handle is not None
self._handle.write(json.dumps(row, ensure_ascii=False, separators=(",", ":")))
self._handle.write("\n")
self.document_count += 1
def close(self) -> None:
if self._handle is not None:
self._handle.close()
self._handle = None
def __enter__(self) -> "ShardedJsonlWriter":
return self
def __exit__(self, *_: object) -> None:
self.close()
|