Infinity08's picture
Add files using upload-large-folder tool
91ac3cc verified
Raw History Blame Contribute Delete
5.1 kB
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()