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
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
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