| from __future__ import annotations |
|
|
| import hashlib |
| import json |
| import mimetypes |
| import re |
| import unicodedata |
| from dataclasses import dataclass, field |
| from pathlib import Path |
| from typing import Any, Iterable |
|
|
|
|
| DOI_RE = re.compile(r"10\.\d{4,9}/[-._;()/:A-Z0-9]+", re.IGNORECASE) |
| HEADING_RE = re.compile( |
| r"\\(?P<kind>part|chapter|section|subsection|subsubsection)\*?\s*\{", |
| re.IGNORECASE, |
| ) |
| ENV_TOKEN_RE = re.compile(r"\\(?P<op>begin|end)\s*\{(?P<env>[^{}]+)\}") |
| PROTECTED_ENVS = { |
| "equation", |
| "equation*", |
| "align", |
| "align*", |
| "alignat", |
| "alignat*", |
| "gather", |
| "gather*", |
| "multline", |
| "multline*", |
| "displaymath", |
| "math", |
| "theorem", |
| "lemma", |
| "proposition", |
| "corollary", |
| "definition", |
| "assumption", |
| "remark", |
| "example", |
| "proof", |
| "axiom", |
| "verbatim", |
| "lstlisting", |
| } |
| HEADING_LEVELS = { |
| "part": 0, |
| "chapter": 0, |
| "section": 1, |
| "subsection": 2, |
| "subsubsection": 3, |
| } |
| SECRET_PATTERNS = { |
| "openai_key": re.compile(r"(?<![A-Za-z0-9])sk-[A-Za-z0-9_-]{20,}"), |
| "huggingface_token": re.compile(r"(?<![A-Za-z0-9])hf_[A-Za-z0-9]{20,}"), |
| "github_token": re.compile(r"(?<![A-Za-z0-9])gh[pousr]_[A-Za-z0-9]{20,}"), |
| "private_key": re.compile( |
| r"-----BEGIN (?:RSA |OPENSSH |EC )?PRIVATE KEY-----" |
| ), |
| } |
|
|
|
|
| def sha256_bytes(data: bytes) -> str: |
| return hashlib.sha256(data).hexdigest() |
|
|
|
|
| def sha256_file(path: Path, chunk_size: int = 1024 * 1024) -> str: |
| digest = hashlib.sha256() |
| with path.open("rb") as stream: |
| while chunk := stream.read(chunk_size): |
| digest.update(chunk) |
| return digest.hexdigest() |
|
|
|
|
| def canonical_json(data: Any) -> str: |
| return json.dumps( |
| data, |
| ensure_ascii=False, |
| indent=2, |
| sort_keys=True, |
| separators=(",", ": "), |
| ) + "\n" |
|
|
|
|
| def write_text_lf(path: Path, text: str) -> None: |
| path.parent.mkdir(parents=True, exist_ok=True) |
| path.write_text(text.replace("\r\n", "\n"), encoding="utf-8", newline="\n") |
|
|
|
|
| def strip_tex_comments(text: str) -> str: |
| output: list[str] = [] |
| for line in text.splitlines(keepends=True): |
| cut = None |
| for index, char in enumerate(line): |
| if char != "%": |
| continue |
| backslashes = 0 |
| cursor = index - 1 |
| while cursor >= 0 and line[cursor] == "\\": |
| backslashes += 1 |
| cursor -= 1 |
| if backslashes % 2 == 0: |
| cut = index |
| break |
| if cut is None: |
| output.append(line) |
| else: |
| newline = "\n" if line.endswith("\n") else "" |
| output.append(line[:cut] + newline) |
| return "".join(output) |
|
|
|
|
| def extract_braced_command(text: str, command: str) -> str: |
| match = re.search(rf"\\{re.escape(command)}\s*\{{", text) |
| if not match: |
| return "" |
| start = match.end() |
| cursor = start |
| depth = 1 |
| while cursor < len(text) and depth: |
| char = text[cursor] |
| escaped = cursor > 0 and text[cursor - 1] == "\\" |
| if char == "{" and not escaped: |
| depth += 1 |
| elif char == "}" and not escaped: |
| depth -= 1 |
| cursor += 1 |
| if depth: |
| return "" |
| return text[start : cursor - 1] |
|
|
|
|
| def clean_tex_label(text: str) -> str: |
| cleaned = strip_tex_comments(text) |
| cleaned = re.sub(r"\\\\(?:\[[^\]]*\])?", " ", cleaned) |
| cleaned = re.sub(r"\\(?:href)\s*\{[^{}]*\}\s*\{([^{}]*)\}", r"\1", cleaned) |
| cleaned = re.sub(r"\\(?:url)\s*\{([^{}]*)\}", r"\1", cleaned) |
| cleaned = re.sub(r"\\[A-Za-z@]+\*?(?:\[[^\]]*\])?", " ", cleaned) |
| cleaned = cleaned.replace("{", " ").replace("}", " ").replace("~", " ") |
| cleaned = re.sub(r"\s+", " ", cleaned) |
| return cleaned.strip() |
|
|
|
|
| def normalize_title(text: str) -> str: |
| normalized = unicodedata.normalize("NFKD", clean_tex_label(text)).lower() |
| normalized = normalized.replace("–", "-").replace("—", "-") |
| normalized = re.sub(r"[^a-z0-9]+", " ", normalized) |
| return " ".join(normalized.split()) |
|
|
|
|
| def archive_stem_title(name: str) -> str: |
| stem = Path(name).stem |
| stem = re.sub(r"\s+\(\d+\)$", "", stem) |
| return stem.replace("__", " ").replace("_", " ").strip() |
|
|
|
|
| def extract_document_body(text: str) -> str: |
| begin = re.search(r"\\begin\s*\{document\}", text) |
| end_matches = list(re.finditer(r"\\end\s*\{document\}", text)) |
| if not begin: |
| return strip_tex_comments(text).strip() |
| end = end_matches[-1].start() if end_matches else len(text) |
| return strip_tex_comments(text[begin.end() : end]).strip() |
|
|
|
|
| def brace_balance(text: str) -> int: |
| balance = 0 |
| stripped = strip_tex_comments(text) |
| for index, char in enumerate(stripped): |
| if char not in "{}": |
| continue |
| backslashes = 0 |
| cursor = index - 1 |
| while cursor >= 0 and stripped[cursor] == "\\": |
| backslashes += 1 |
| cursor -= 1 |
| if backslashes % 2: |
| continue |
| balance += 1 if char == "{" else -1 |
| return balance |
|
|
|
|
| def mime_type_for(name: str) -> str: |
| extension = Path(name).suffix.lower() |
| overrides = { |
| ".tex": "application/x-tex", |
| ".bib": "application/x-bibtex", |
| ".json": "application/json", |
| ".py": "text/x-python", |
| ".zip": "application/zip", |
| } |
| return overrides.get(extension) or mimetypes.guess_type(name)[0] or "application/octet-stream" |
|
|
|
|
| def find_secret_patterns(text: str) -> list[str]: |
| return sorted(name for name, pattern in SECRET_PATTERNS.items() if pattern.search(text)) |
|
|
|
|
| def find_unsafe_tex_references(text: str) -> list[str]: |
| unsafe: list[str] = [] |
| pattern = re.compile( |
| r"\\(?:input|include|includegraphics|lstinputlisting)\s*" |
| r"(?:\[[^\]]*\])?\s*\{([^}]+)\}" |
| ) |
| for match in pattern.finditer(text): |
| candidate = match.group(1) |
| if ( |
| re.match(r"^[A-Za-z]:", candidate) |
| or candidate.startswith(("/", "\\\\")) |
| or ".." in Path(candidate).parts |
| ): |
| unsafe.append(candidate) |
| return sorted(set(unsafe)) |
|
|
|
|
| def readable_tex(text: str) -> tuple[str, list[str]]: |
| flags: list[str] = [] |
| try: |
| from pylatexenc.latex2text import LatexNodes2Text |
|
|
| converter = LatexNodes2Text( |
| math_mode="verbatim", |
| keep_comments=False, |
| strict_latex_spaces=False, |
| ) |
| rendered = converter.latex_to_text(text) |
| except Exception: |
| flags.append("latex_to_text_fallback") |
| rendered = clean_tex_label(text) |
| rendered = re.sub(r"[ \t]+\n", "\n", rendered) |
| rendered = re.sub(r"\n{3,}", "\n\n", rendered) |
| return rendered.strip(), flags |
|
|
|
|
| @dataclass(slots=True) |
| class TexEntry: |
| path: str |
| size: int |
| compressed_size: int |
| crc32: str |
| sha256: str |
| text: str |
| title_raw: str |
| title_clean: str |
| author_raw: str |
| author_clean: str |
| date_raw: str |
| doi_candidates: list[str] |
| content_status: str |
| quality_flags: list[str] = field(default_factory=list) |
|
|
|
|
| @dataclass(slots=True) |
| class Archive: |
| filename: str |
| source_path: Path |
| raw_path: str |
| size: int |
| sha256: str |
| entries: list[dict[str, Any]] |
| tex_entries: list[TexEntry] |
| primary_tex_index: int | None |
| mapped_dois: list[str] = field(default_factory=list) |
| mapping_method: str = "unresolved" |
| mapping_score: float = 0.0 |
| mapping_status: str = "archive_only" |
| candidate_dois: list[str] = field(default_factory=list) |
| duplicate_of_archive: str = "" |
| quality_flags: list[str] = field(default_factory=list) |
|
|
| @property |
| def primary_tex(self) -> TexEntry | None: |
| if self.primary_tex_index is None: |
| return None |
| return self.tex_entries[self.primary_tex_index] |
|
|
| @property |
| def content_status(self) -> str: |
| primary = self.primary_tex |
| if primary is None: |
| return "invalid_source" |
| if self.duplicate_of_archive: |
| return "exact_duplicate" |
| return primary.content_status |
|
|
|
|
| @dataclass(slots=True) |
| class Block: |
| start: int |
| end: int |
| text: str |
| section_path: tuple[str, ...] |
| kind: str |
|
|
|
|
| def _protected_spans(text: str) -> list[tuple[int, int]]: |
| spans: list[tuple[int, int]] = [] |
| stack: list[tuple[str, int]] = [] |
| for match in ENV_TOKEN_RE.finditer(text): |
| env = match.group("env").strip().lower() |
| if env not in PROTECTED_ENVS: |
| continue |
| if match.group("op") == "begin": |
| stack.append((env, match.start())) |
| continue |
| for index in range(len(stack) - 1, -1, -1): |
| open_env, open_start = stack[index] |
| if open_env != env: |
| continue |
| is_outer = index == 0 |
| del stack[index:] |
| if is_outer: |
| spans.append((open_start, match.end())) |
| break |
| return sorted(spans) |
|
|
|
|
| def _heading_title(block_text: str) -> tuple[int | None, str]: |
| match = HEADING_RE.search(block_text) |
| if not match: |
| return None, "" |
| command = match.group("kind").lower() |
| start = match.end() |
| cursor = start |
| depth = 1 |
| while cursor < len(block_text) and depth: |
| char = block_text[cursor] |
| escaped = cursor > 0 and block_text[cursor - 1] == "\\" |
| if char == "{" and not escaped: |
| depth += 1 |
| elif char == "}" and not escaped: |
| depth -= 1 |
| cursor += 1 |
| raw = block_text[start : cursor - 1] if depth == 0 else "" |
| return HEADING_LEVELS[command], clean_tex_label(raw) |
|
|
|
|
| def latex_blocks(body: str) -> list[Block]: |
| spans = _protected_spans(body) |
| raw_parts: list[tuple[int, int, str]] = [] |
| cursor = 0 |
| for start, end in spans: |
| if start > cursor: |
| raw_parts.append((cursor, start, "text")) |
| raw_parts.append((start, end, "environment")) |
| cursor = end |
| if cursor < len(body): |
| raw_parts.append((cursor, len(body), "text")) |
|
|
| pieces: list[tuple[int, int, str]] = [] |
| for start, end, kind in raw_parts: |
| if kind == "environment": |
| pieces.append((start, end, kind)) |
| continue |
| segment = body[start:end] |
| paragraph_starts = [0] |
| for match in re.finditer(r"\n\s*\n", segment): |
| paragraph_starts.append(match.end()) |
| paragraph_starts.append(len(segment)) |
| for left, right in zip(paragraph_starts, paragraph_starts[1:]): |
| absolute_left = start + left |
| absolute_right = start + right |
| content = body[absolute_left:absolute_right] |
| if not content.strip(): |
| continue |
| heading_positions = [m.start() for m in HEADING_RE.finditer(content)] |
| if not heading_positions: |
| pieces.append((absolute_left, absolute_right, "text")) |
| continue |
| split_points = sorted(set([0, *heading_positions, len(content)])) |
| for local_left, local_right in zip(split_points, split_points[1:]): |
| if local_right <= local_left: |
| continue |
| piece_start = absolute_left + local_left |
| piece_end = absolute_left + local_right |
| if body[piece_start:piece_end].strip(): |
| pieces.append((piece_start, piece_end, "heading_or_text")) |
|
|
| section_stack: list[str] = [] |
| blocks: list[Block] = [] |
| for start, end, kind in sorted(pieces): |
| text = body[start:end] |
| level, title = _heading_title(text) |
| block_kind = kind |
| if level is not None: |
| section_stack = section_stack[:level] |
| while len(section_stack) < level: |
| section_stack.append("") |
| if level == 0: |
| section_stack = [title] |
| else: |
| section_stack.append(title) |
| block_kind = "heading" |
| blocks.append( |
| Block( |
| start=start, |
| end=end, |
| text=text, |
| section_path=tuple(item for item in section_stack if item), |
| kind=block_kind, |
| ) |
| ) |
| return blocks |
|
|
|
|
| def make_chunks( |
| body: str, |
| target_chars: int = 4000, |
| max_chars: int = 6000, |
| overlap_chars: int = 400, |
| min_chars: int = 1500, |
| ) -> list[dict[str, Any]]: |
| blocks = latex_blocks(body) |
| if not blocks and body.strip(): |
| blocks = [Block(0, len(body), body, tuple(), "text")] |
| chunks: list[dict[str, Any]] = [] |
| current: list[Block] = [] |
|
|
| def emit(selected: list[Block]) -> None: |
| if not selected: |
| return |
| start = selected[0].start |
| end = selected[-1].end |
| tex = body[start:end].strip() |
| if not tex: |
| return |
| flags: list[str] = [] |
| if len(tex) > max_chars: |
| flags.append("oversize_block") |
| plain, render_flags = readable_tex(tex) |
| flags.extend(render_flags) |
| path = selected[0].section_path |
| chunks.append( |
| { |
| "char_start": start, |
| "char_end": end, |
| "chunk_tex": tex, |
| "chunk_text": plain, |
| "section_path": list(path), |
| "section_title": path[-1] if path else "", |
| "quality_flags": sorted(set(flags)), |
| } |
| ) |
|
|
| for block in blocks: |
| block_length = block.end - block.start |
| if block_length > max_chars: |
| emit(current) |
| current = [] |
| emit([block]) |
| continue |
| current_length = current[-1].end - current[0].start if current else 0 |
| starts_new_section = block.kind == "heading" and bool(current) |
| would_exceed = current and block.end - current[0].start > max_chars |
| target_reached = current_length >= min_chars and ( |
| starts_new_section or current_length >= target_chars |
| ) |
| if current and (would_exceed or target_reached): |
| previous = list(current) |
| emit(previous) |
| overlap: list[Block] = [] |
| overlap_size = 0 |
| for candidate in reversed(previous): |
| candidate_size = candidate.end - candidate.start |
| if overlap and overlap_size + candidate_size > overlap_chars: |
| break |
| if candidate.kind == "heading" and overlap: |
| break |
| overlap.insert(0, candidate) |
| overlap_size += candidate_size |
| if overlap_size >= overlap_chars: |
| break |
| current = [] if starts_new_section else overlap |
| current.append(block) |
| emit(current) |
| return chunks |
|
|
|
|
| def content_size_category(count: int) -> str: |
| if count < 1000: |
| return "n<1K" |
| if count < 10_000: |
| return "1K<n<10K" |
| if count < 100_000: |
| return "10K<n<100K" |
| if count < 1_000_000: |
| return "100K<n<1M" |
| return "n>1M" |
|
|
|
|
| def batched(items: Iterable[Any], size: int) -> Iterable[list[Any]]: |
| batch: list[Any] = [] |
| for item in items: |
| batch.append(item) |
| if len(batch) == size: |
| yield batch |
| batch = [] |
| if batch: |
| yield batch |
|
|