repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
nature-skills
skills/nature-downloader/scripts/extract_pdf_text.py
.py
#!/usr/bin/env python3 import argparse import json import sys from pathlib import Path def configure_utf8_stdio(): """Keep Chinese paths/text printable in Windows PowerShell and Claude Code terminals.""" for stream_name in ("stdout", "stderr"): stream = getattr(sys, stream_name, None) if hasat...
88
2,889
nature-skills
skills/nature-downloader/scripts/configure_school.py
.py
#!/usr/bin/env python3 """Command line helper for literature-downloader school configuration.""" from __future__ import annotations import argparse import json import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] SRC = ROOT / "src" if str(SRC) not in sys.path: sys.path.insert(0, str(SRC...
128
4,500
nature-skills
skills/nature-downloader/scripts/configure_credentials.py
.py
#!/usr/bin/env python3 """Configure publisher API credentials without echoing secrets.""" from __future__ import annotations import argparse import getpass import json import os import sys import tempfile import urllib.error import urllib.parse import urllib.request from pathlib import Path REGISTRY_FILE = Path(__fi...
162
6,843
nature-skills
skills/nature-downloader/src/health_check.py
.py
"""连通性自检模块。 下载前对配置做轻量可达性探测,结果缓存 10 分钟。 失败时给出具体排查建议。 """ from __future__ import annotations import json import time from pathlib import Path from typing import Any, Optional from config import CONFIG_DIR, load_config from validators import validate_carsi_entry, validate_sso_domain # 缓存文件 CACHE_FILE = CONFIG_DIR / "...
156
4,383
nature-skills
skills/nature-downloader/src/schools_loader.py
.py
"""Optional user-maintained institution preset loader. The distributed schools.yaml is intentionally empty. """ from __future__ import annotations from pathlib import Path from typing import Any, Optional try: import yaml # type: ignore except ImportError: yaml = None # type: ignore SCHOOLS_FILE = Path(_...
129
3,703
nature-skills
skills/nature-downloader/src/wizard.py
.py
"""配置向导模块。 7 步交互式配置流程,供 AI 调用。 每一步返回一个 prompt 给用户,并接收用户输入进行校验。 使用方式(AI 调用): from wizard import Wizard w = Wizard() # Step 1 prompt = w.start() # 返回给用户的提问 # 用户回答后 result = w.handle_step1(user_input) # result = {"next": "step2"|"retry"|"done", "prompt": str, "data": dict} 发行包...
583
23,905
nature-skills
skills/nature-downloader/src/config.py
.py
"""配置读写模块。 负责 school.json 的读取、写入、校验、备份。 配置路径:~/.config/lit-dl/school.json """ from __future__ import annotations import json import os import shutil from datetime import datetime from pathlib import Path from typing import Any, Optional try: import jsonschema # type: ignore except ImportError: jsonschema =...
174
5,334
nature-skills
skills/nature-downloader/src/validators.py
.py
"""字段校验模块。 对用户填写的配置字段做实时可达性探测: - sso_domain: DNS 解析 + TCP 443 + HTTPS 证书 - carsi_entry: HTTP GET 探测 - ezproxy_url: HTTP GET 探测登录表单 所有校验函数返回 (ok: bool, message: str)。 """ from __future__ import annotations import socket import ssl import urllib.parse import urllib.request def validate_sso_domain(domain: str, timeo...
195
6,180
nature-skills
skills/nature-paper-card/tests/test_prepare_paper.py
.py
#!/usr/bin/env python3 """Regression tests for source-map page-locator normalization.""" from __future__ import annotations import importlib.util import json import subprocess import sys import tempfile import unittest from pathlib import Path sys.dont_write_bytecode = True SCRIPT_PATH = Path(__file__).parents[1] /...
144
5,773
nature-skills
skills/nature-paper-card/scripts/audit_paper_card.py
.py
#!/usr/bin/env python3 """Audit a Paper Card against its source bundle and output contract.""" from __future__ import annotations import argparse import json import re import sys from pathlib import Path from typing import Any SECTION_RE = re.compile(r"^##\s+(\d{2})\b.*$", re.M) PAPER_POINTER_RE = re.compile(r"\[Pa...
416
13,551
nature-skills
skills/nature-paper-card/scripts/prepare_paper.py
.py
#!/usr/bin/env python3 """Prepare a stable source bundle for the nature-paper-card workflow.""" from __future__ import annotations import argparse import hashlib import json import re import sys from collections import defaultdict from pathlib import Path from typing import Any SECTION_NAMES = { "abstract", ...
491
17,979
nature-skills
skills/nature-response/tests/test_response_instruction_contracts.py
.py
from pathlib import Path ROOT = Path(__file__).parents[1] def read(relative: str) -> str: return (ROOT / relative).read_text(encoding="utf-8") def test_decision_type_gate_is_part_of_the_runtime_contract() -> None: router = read("SKILL.md") workflow = read("static/core/workflow.md") assert "Major ...
44
1,424
nature-skills
skills/nature-response/tests/test_package_consistency.py
.py
from __future__ import annotations import importlib.util import sys import tempfile import unittest from pathlib import Path SCRIPT = Path(__file__).parents[1] / "scripts" / "check_package_consistency.py" SPEC = importlib.util.spec_from_file_location("check_package_consistency", SCRIPT) assert SPEC and SPEC.loader C...
163
6,181
nature-skills
skills/nature-response/scripts/check_package_consistency.py
.py
#!/usr/bin/env python3 """Check mechanical consistency across a LaTeX revision package.""" from __future__ import annotations import argparse import json import re import sys from dataclasses import asdict, dataclass from pathlib import Path from typing import Iterable DEFAULT_QUOTE_MACROS = ("RevisedExcerpt", "rev...
311
10,149
Python
tools/example_runner.py
.py
"""扫描 Article/**/*.md,提取 ```python 代码块逐块跑一遍。 用法: python tools/example_runner.py [path] 不写 path 默认扫描 Article/。 代码块前若有 <!-- skip-ci --> 注释行则跳过。 """ import argparse import re import subprocess import sys import tempfile from pathlib import Path BLOCK_RE = re.compile( r"(?:(<!--\s*skip-ci\s*-->)\s*\n)?```[Pp]yt...
87
2,524
PageIndex
run_pageindex.py
.py
import argparse import os import json from pageindex import * from pageindex.page_index_md import md_to_tree from pageindex.utils import ConfigLoader if __name__ == "__main__": # Set up argument parser parser = argparse.ArgumentParser(description='Process PDF or Markdown document and generate structure') p...
194
10,033
PageIndex
pageindex/tree_optimize.py
.py
"""Tree optimization: merge and expand driven by worst-case search cost. Refines a PageIndex tree so that navigating it is never more expensive than necessary. Search cost is measured in pages, routing cost R(v) = 1 page: S(v) pages to linearly scan if v is collapsed = the whole subtree span R(v) ...
948
39,904
PageIndex
pageindex/errors.py
.py
class PageIndexAPIError(Exception): pass
3
45
PageIndex
pageindex/utils.py
.py
import logging import os import textwrap from datetime import datetime import time import json import PyPDF2 import copy import asyncio from io import BytesIO from dotenv import load_dotenv load_dotenv() import logging import yaml from pathlib import Path from types import SimpleNamespace as config import re # litellm...
1,031
37,550
PageIndex
pageindex/local_api.py
.py
"""Local implementation of the PageIndex SDK surface.""" from __future__ import annotations import asyncio import json import logging import os import uuid from concurrent.futures import ThreadPoolExecutor from datetime import datetime, timezone from typing import Any from .errors import PageIndexAPIError from .local...
358
14,129
PageIndex
pageindex/local_chat.py
.py
"""Managed local chat: document-QA agents over the local tools. Three methods, three backend protocols, routed 1:1: ``chat_completions`` drives the backend's /chat/completions (any OpenAI-compatible backend, final answer only), ``responses`` drives /responses (official-shape envelope; the full process transcript rides...
874
37,274
PageIndex
pageindex/_version.py
.py
"""Installed-package version, shared by every surface that reports it upstream.""" from __future__ import annotations def sdk_version() -> str: try: from importlib.metadata import version return version("pageindex") except Exception: return "0.0.0"
11
283
PageIndex
pageindex/local_store.py
.py
"""On-disk document store behind PageIndexClient's local mode.""" from __future__ import annotations import json import logging import os import shutil import uuid from pathlib import Path logger = logging.getLogger(__name__) def _write_json_atomic(path: Path, data) -> None: tmp = path.with_name(path.name + f"....
165
5,644
PageIndex
pageindex/__init__.py
.py
"""PageIndex SDK.""" from typing import TYPE_CHECKING as _TYPE_CHECKING from .client import PageIndexClient, PageIndexCloudClient, PageIndexLocalClient from .errors import PageIndexAPIError if _TYPE_CHECKING: from .flash import page_index_flash from .page_index_classic import page_index, page_index_main f...
57
2,156
PageIndex
pageindex/client.py
.py
"""PageIndex SDK client: the 0.2.x cloud surface, now with a local mode.""" from __future__ import annotations import os import time import warnings from typing import Any, Callable, Iterator, Optional, Union, cast from .errors import PageIndexAPIError def _parse_pages(pages: str) -> list[int]: result: set[int]...
1,030
47,220
PageIndex
pageindex/agent_tools.py
.py
"""Agent tools: the cloud MCP tool contract, executed against a PageIndexClient. Tool names and the surviving input-schema structure match the PageIndex cloud MCP server — the local surface hides the documented cloud-only parameters — so agent prompts port across the cloud MCP connection and this in-process layer. Onl...
1,634
69,911
PageIndex
pageindex/page_index_classic.py
.py
import os import json import copy import math import random import re from .utils import * from .tree_optimize import merge_tree import os from concurrent.futures import ThreadPoolExecutor, as_completed ######################### Hardening for prompt injection patterns ##################################################...
1,325
55,430
PageIndex
pageindex/mcp_bridge.py
.py
"""Minimal MCP client (streamable HTTP) for the PageIndex cloud MCP server. Backs the cloud branches of ``client.agent_tools()`` and ``client.agent_instructions()``: ``tools/list`` discovers the live tool set, ``tools/call`` executes a tool, and the ``initialize`` handshake carries the server's agent instructions. Syn...
211
9,328
PageIndex
pageindex/cloud_api.py
.py
"""Cloud mode of the PageIndex SDK, based on the 0.2.8 client.""" import requests from typing import Optional, Dict, Any, List, Union, Iterator import json import urllib.parse from .errors import PageIndexAPIError def _enc(value: str) -> str: """URL-encode a path segment (ids may contain / ? # or spaces).""" ...
436
15,948
PageIndex
pageindex/page_index_md.py
.py
import asyncio import json import re import os try: from .utils import * except: from utils import * async def get_node_summary(node, summary_token_threshold=200, model=None): node_text = node.get('text') num_tokens = count_tokens(node_text, model=model) if num_tokens < summary_token_threshold: ...
345
12,096
PageIndex
pageindex/flash/parser_pdfium_parallel.py
.py
"""Per-page parallel driver for the charlevel parser. Wraps the UNMODIFIED per-page pipeline (``_page_pass1`` / ``_page_pass2`` / ``_page_spans``) in a process pool. PDFium's FFI is not thread-safe and its handles are process-local, so parallelism uses processes, each opening its own copy of the document. Parity cont...
140
4,905
PageIndex
pageindex/flash/main.py
.py
""" End-to-end orchestrator for the TOC extraction pipeline. Pipeline order: 1. parse character-level spans and page viewport metadata 2. cluster spans into lines 3. compute page statistics 4. detect columns and recluster lines with column awareness 5. remove line-number artifacts and recompute statistics 6. compute do...
333
16,589
PageIndex
pageindex/flash/embedded_toc.py
.py
"""Embedded PDF bookmark (outline dictionary) consumption. Opt-in feature gated behind ``extract_toc(use_embedded_toc=True)``; the default path never imports this module. Bookmarks are read with PDFium, validated, and classified into tiers: * FULL deep and dense enough to be the frame: the bookmark tree ...
610
22,759
PageIndex
pageindex/flash/__init__.py
.py
"""PageIndex Flash: LLM-free tree structure extraction from PDF layout statistics.""" from .api import page_index_flash __all__ = ["page_index_flash"]
6
153
PageIndex
pageindex/flash/api.py
.py
"""Public API for PageIndex Flash. The only supported entry point is :func:`page_index_flash`. Everything else in this package is internal pipeline machinery.""" from __future__ import annotations from io import BytesIO from pathlib import Path from typing import BinaryIO import pypdfium2 as pdfium from .main impor...
137
6,888
PageIndex
pageindex/flash/columns/gutters.py
.py
"""Gutter-gap candidates and scoring for column detection.""" from __future__ import annotations import math from typing import Optional from ..model import ( Rect, rect_union, EMPTY_RECT, Line, info_weight, text_of_line, numbering_kind, numbering_value, _UNICODE_WHITESPACE_CLASS, _max_nan_propagating, _min_nan_...
346
15,852
PageIndex
pageindex/flash/columns/__init__.py
.py
""" Column detection via sweep-line gutter scoring and recursive page splitting. The detector builds horizontal and vertical sweep events, scores candidate gutters, assigns column indexes to lines, and returns column rectangles used by the second line-clustering pass. Direction code 0 scans vertical positions to find ...
50
1,441
PageIndex
pageindex/flash/columns/splitting.py
.py
"""Recursive column splitting and column index assignment.""" from __future__ import annotations import math from typing import Optional from ..model import ( Rect, rect_union, EMPTY_RECT, Line, info_weight, text_of_line, numbering_kind, numbering_value, _UNICODE_WHITESPACE_CLASS, _max_nan_propagating, _min_nan_...
224
10,512
PageIndex
pageindex/flash/outline_assembly/selection.py
.py
"""Heading rejection rules, hierarchy stack, and sub/top-level heading extraction.""" from __future__ import annotations import math from typing import Any, Callable, Optional from ..model import ( style_key, left_aligned, right_aligned, center_aligned, x_aligned, rect_union, Rect, last_span, avg_char_width, ...
386
18,207
PageIndex
pageindex/flash/outline_assembly/__init__.py
.py
"""Outline assembly chain. This module turns heading candidates and labeled section regions into the final nested outline tree. It groups candidates by numbering depth, style signature, script compatibility, document order, and local clusters, then serializes the tree into the public PageIndex JSON shape. """ import m...
111
4,150
PageIndex
pageindex/flash/outline_assembly/cliques.py
.py
"""Keyword cliques, clique trees, body-heading detection, and candidate partitioning.""" from __future__ import annotations from typing import Any, Callable, Optional from ..model import ( style_key, left_aligned, right_aligned, center_aligned, x_aligned, rect_union, Rect, last_span, avg_char_width, raw_text_...
404
19,505
PageIndex
pageindex/flash/outline_assembly/assembly.py
.py
"""Final outline assembly and conversion to the output dict tree.""" from __future__ import annotations from typing import Any, Callable, Optional from ..model import ( style_key, left_aligned, right_aligned, center_aligned, x_aligned, rect_union, Rect, last_span, avg_char_width, raw_text_of_line, heading_sco...
359
15,472
PageIndex
pageindex/flash/outline_assembly/style_context.py
.py
"""Style clusters, outline context/state, numbering trie, and depth comparison.""" from __future__ import annotations import math from typing import Any, Callable, Optional from sortedcontainers import SortedKeyList from ..model import ( style_key, left_aligned, right_aligned, center_aligned, x_aligned, rect_uni...
366
18,464
PageIndex
pageindex/flash/outline_assembly/candidates.py
.py
"""Heading candidate and outline node types plus ordering and signature helpers.""" from __future__ import annotations from ..model import ( style_key, left_aligned, right_aligned, center_aligned, x_aligned, rect_union, Rect, last_span, avg_char_width, raw_text_of_line, heading_score, numbering_text, numberin...
256
12,458
PageIndex
pageindex/flash/title/__init__.py
.py
"""Document-title detection. The scoring formula is the heart of title detection: score is a product of layout, recurrence, label, script, width, numbering, punctuation, alignment, and page-position factors. Each factor is in roughly ``[0.1, 3.0]-- the product can grow to a few thousand for a strong title candidate. Th...
55
1,750
PageIndex
pageindex/flash/title/dicts.py
.py
"""Dictionary tables for title detection.""" from __future__ import annotations import json import unicodedata from pathlib import Path from ..tokens import is_superscript_adjacent, clamp_value, enumerate_tokens, jenkins_hash, trie_prefix_match, set_case_fold, TrieConfig, build_trie, tokenize_block, _de_norm, BuiltTr...
36
1,389
PageIndex
pageindex/flash/title/scoring.py
.py
"""Title-candidate scoring.""" from __future__ import annotations import math from ..model import ( _trim_unicode_ws, left_aligned, right_aligned, center_aligned, Rect, last_span, heading_score, Line, last_line_of, first_span_of, block_text, deaccented_text, letter...
265
11,024
PageIndex
pageindex/flash/title/detect.py
.py
"""Document title search over early pages.""" from __future__ import annotations from typing import Optional from ..model import ( _trim_unicode_ws, left_aligned, right_aligned, center_aligned, Rect, last_span, heading_score, Line, last_line_of, first_span_of, block_text, ...
141
6,095
PageIndex
pageindex/flash/outline/__init__.py
.py
"""Heading predicates and section-keyword helpers. The full outline tree is assembled in ``outline_assembly``. This module keeps the lower-level heading checks that decide whether a block is a plausible outline heading based on numbering, style, geometry, and section-keyword tries. """ import re from collections impor...
55
1,456
PageIndex
pageindex/flash/outline/tree.py
.py
"""Level assignment and outline tree construction.""" from __future__ import annotations import re from collections import defaultdict from ..model import numbering_text, numbering_kind, block_text, is_caps_heavy, Block from .filtering import ( _style_key, _numbering_depth, ) def extract_top_level_headings...
146
5,816
PageIndex
pageindex/flash/outline/filtering.py
.py
"""Heading candidate collection, filtering, and keyword screening.""" from __future__ import annotations import re from collections import defaultdict from typing import Optional from ..labels import extract_structural_number from ..model import numbering_text, numbering_kind, block_text, is_caps_heavy, Block from ....
242
9,709
PageIndex
pageindex/flash/classification/toc_boilerplate.py
.py
"""Watermark, boilerplate, and TOC-range detection.""" from __future__ import annotations import math from typing import Optional from ..model import ( _UNICODE_WHITESPACE_CLASS, _strip_diacritics, _round_half_up_to_int, magnitude_ratio, intervals_overlap, y_overlaps, center_aligned, ...
376
15,439
PageIndex
pageindex/flash/classification/__init__.py
.py
""" Block classification for header/footer, watermark, boilerplate, TOC-page, and reference-list marking. The module combines recurrence hashes, page-number patterns, body-paragraph gates, cross-page geometry, and numeric-column clustering. The dot-leader and page-number gates intentionally use Unicode number propertie...
132
3,696
PageIndex
pageindex/flash/classification/keyword_tables.py
.py
"""Dictionary-backed keyword tries and shared regexes.""" from __future__ import annotations import json import regex as regex_module # Unicode \p{...} property classes from pathlib import Path from typing import Optional from ..model import ( _UNICODE_WHITESPACE_CLASS, _strip_diacritics, _round_half_up...
114
3,821
PageIndex
pageindex/flash/classification/body_text.py
.py
"""Body-paragraph classification and recurring-text recording.""" from __future__ import annotations import math from typing import Optional from ..model import ( _UNICODE_WHITESPACE_CLASS, _strip_diacritics, _round_half_up_to_int, magnitude_ratio, intervals_overlap, y_overlaps, center_al...
210
7,458
PageIndex
pageindex/flash/classification/header_footer.py
.py
"""Header and footer detection via cross-page recurrence.""" from __future__ import annotations import math from typing import Optional from ..model import ( _UNICODE_WHITESPACE_CLASS, _strip_diacritics, _round_half_up_to_int, magnitude_ratio, intervals_overlap, y_overlaps, center_aligned...
482
22,348
PageIndex
pageindex/flash/tokens/__init__.py
.py
"""Tokenizer subsystem. The tokenizer is character-driven: it walks each character of each line, uses category-transition tolerances to decide when the current token can extend, and closes tokens when script, punctuation, or spacing transitions require a boundary. Tokens keep back-references to the contributing line an...
106
2,822
PageIndex
pageindex/flash/tokens/token_types.py
.py
"""Token types, anchors, and token-view utilities.""" from __future__ import annotations from typing import Any, Iterable, Iterator, Optional from ..model import ( _strip_diacritics, avg_char_width2, intervals_overlap, to_number, rect_union, EMPTY_RECT, avg_char_width, Line, char_...
244
8,631
PageIndex
pageindex/flash/tokens/tokenizer.py
.py
"""Line tokenization into word, char, and number tokens.""" from __future__ import annotations import unicodedata from typing import Any, Iterable, Iterator, Optional from ..model import ( _strip_diacritics, avg_char_width2, intervals_overlap, to_number, rect_union, EMPTY_RECT, avg_char_w...
272
12,077
PageIndex
pageindex/flash/tokens/hashing.py
.py
"""32-bit integer helpers and the Jenkins string hash.""" from __future__ import annotations # --------------------------------------------------------------------------- # # Jenkins lookup2 string hash (UTF-8 bytes -> signed 32-bit int). # --------------------------------------------------------------------------- ...
140
6,477
PageIndex
pageindex/flash/tokens/tries.py
.py
"""Trie construction, matching, and token trimming utilities.""" from __future__ import annotations from typing import Any, Iterable, Iterator, Optional from ..model import ( _strip_diacritics, avg_char_width2, intervals_overlap, to_number, rect_union, EMPTY_RECT, avg_char_width, Line...
337
12,090
PageIndex
pageindex/flash/blocks/join_rules.py
.py
"""Line-to-block joining rules and the section-heading trie.""" from __future__ import annotations from typing import Optional import json from pathlib import Path from ..model import ( style_key, magnitude_ratio, left_aligned, right_aligned, center_aligned, x_centers_close, Rect, la...
327
14,184
PageIndex
pageindex/flash/blocks/__init__.py
.py
"""Block clustering. This module walks page lines in reading order, extends nearby compatible blocks, starts a new block when no neighbor fits, and then splits simple "heading + body" two-line blocks where the first line is a standalone section heading. The clustering pass must return blocks, not raw lines. Reading-ord...
57
1,500
PageIndex
pageindex/flash/blocks/build.py
.py
"""Clusters lines into blocks and splits heading-body blocks.""" from __future__ import annotations from sortedcontainers import SortedKeyList from ..model import ( style_key, magnitude_ratio, left_aligned, right_aligned, center_aligned, x_centers_close, Rect, last_span, avg_char_...
174
7,416
PageIndex
pageindex/flash/model/span_line.py
.py
"""Span and Line types with text and style helpers.""" from __future__ import annotations import re from decimal import Decimal, ROUND_HALF_UP from typing import Any, Iterator, Optional, Protocol from .char_stats import ( _trim_unicode_ws, CharStats, merge_char_stats, letter_count, info_weight, )...
229
8,798
PageIndex
pageindex/flash/model/char_stats.py
.py
"""Character categories and per-run character statistics.""" from __future__ import annotations import math import unicodedata # --------------------------------------------------------------------------- # # Character classifier # # --------------------------------------------------------------------------- # # C...
185
7,859
PageIndex
pageindex/flash/model/numbering.py
.py
"""Numbering-prefix detection and numeric parsing.""" from __future__ import annotations import math import re import unicodedata import regex as regex_module # supports Unicode \p{...} property classes from .char_stats import ( _trim_unicode_ws, _UNICODE_WHITESPACE_CLASS, ) from .span_line import ( Li...
132
4,902
PageIndex
pageindex/flash/model/__init__.py
.py
""" Data model for rectangles, spans, lines, blocks, character categories, and alignment predicates. Coordinate convention follows PDF (origin bottom-left, y increases upward). ``Rect`` is constructed as ``Rect(left, right, top, bottom)``. A few internal storage fields are implementation details; public callers should ...
122
3,400
PageIndex
pageindex/flash/model/block.py
.py
"""Block type with text, style, and alignment helpers.""" from __future__ import annotations import math import re import unicodedata from typing import Any, Iterator, Optional, Protocol from .char_stats import ( is_punct_category, CharStats, merge_char_stats, letter_count, punct_count, info_...
289
12,033
PageIndex
pageindex/flash/model/rects.py
.py
"""Rectangle types, geometry predicates, and ordering comparators.""" from __future__ import annotations import math from .char_stats import ( _max_nan_propagating, _min_nan_propagating, ) # --------------------------------------------------------------------------- # # Rectangle model # # ----------------...
230
11,147
PageIndex
pageindex/flash/heading_detection/neighbors.py
.py
"""Per-page block neighborhood maps and neighbor lookups.""" from __future__ import annotations import math from typing import Any, Optional from ..model import ( _UNICODE_WHITESPACE_CLASS, _strip_diacritics, _trim_unicode_ws, style_key, magnitude_ratio, same_x_extent, same_y_extent, y_overlaps, left_...
156
8,967
PageIndex
pageindex/flash/heading_detection/__init__.py
.py
"""Per-page heading-candidate detection. This module builds and filters heading candidates from page blocks. It combines numbering recognition, chapter/appendix keywords, local neighbor geometry, font/style signals, cross-page rejection, and page-level candidate filtering before handing candidates to outline assembly. ...
121
4,990
PageIndex
pageindex/flash/heading_detection/keyword_tables.py
.py
"""Dictionary-backed keyword tries, keyword sets, and numbering tables.""" from __future__ import annotations import json import re import regex as regex_module # Unicode \p{...} property classes. from pathlib import Path from ..model import ( _UNICODE_WHITESPACE_CLASS, _strip_diacritics, _trim_unicode_w...
97
5,358
PageIndex
pageindex/flash/heading_detection/detectors.py
.py
"""Numbered, labeled, chapter/appendix, and box heading detectors plus acceptability checks.""" from __future__ import annotations import math from typing import Any, Optional from ..outline_assembly import HeadingCandidate, OutlineNode from ..labels import is_uppercase_dominant, trie_matches_all, advance_past_line, ...
493
23,133
PageIndex
pageindex/flash/heading_detection/style_detectors.py
.py
"""Font-change and body-embedded heading detectors.""" from __future__ import annotations import math from typing import Any, Optional from ..outline_assembly import HeadingCandidate, OutlineNode from ..labels import is_uppercase_dominant, trie_matches_all, advance_past_line, skip_bracketed_word, token_case_signal, f...
384
21,386
PageIndex
pageindex/flash/heading_detection/text_checks.py
.py
"""Block-text predicates: keyword matches, continuation, content, and number parsing.""" from __future__ import annotations import math from typing import Any, Optional from ..labels import is_uppercase_dominant, trie_matches_all, advance_past_line, skip_bracketed_word, token_case_signal, format_caption_label, Captio...
222
10,045
PageIndex
pageindex/flash/heading_detection/page_scan.py
.py
"""Whole-page heading scan and document-level candidate collection/filtering.""" from __future__ import annotations import math from typing import Any, Optional from ..outline_assembly import HeadingCandidate, OutlineNode from ..labels import is_uppercase_dominant, trie_matches_all, advance_past_line, skip_bracketed_...
475
24,652
PageIndex
pageindex/flash/heading_detection/candidates.py
.py
"""Page scan state and heading-candidate constructors.""" from __future__ import annotations import math from typing import Any, Optional from ..outline_assembly import HeadingCandidate, OutlineNode from ..labels import is_uppercase_dominant, trie_matches_all, advance_past_line, skip_bracketed_word, token_case_signal...
215
10,554
PageIndex
pageindex/flash/parser_pdfium_charlevel/pipeline.py
.py
"""Whole-document parse drivers assembling per-page charlevel metadata.""" from __future__ import annotations from io import BytesIO from pathlib import Path from typing import Union import pypdfium2 as pdfium # Raw PDF object access (ToUnicode CMaps, content streams, font dicts, /WMode) # that PDFium does not expo...
296
14,665
PageIndex
pageindex/flash/parser_pdfium_charlevel/content_stream.py
.py
"""Content-stream show-operator tokenization and per-page operator tagging.""" from __future__ import annotations from .pdf_objects import ( _PDF_WHITESPACE_BYTES, _PDF_DELIMITER_BYTES, _PDF_STRING_ESCAPE_BYTES, _decode_pdf_name, ) # Text items start at font/size changes, positional line breaks or g...
425
24,429
PageIndex
pageindex/flash/parser_pdfium_charlevel/char_extract.py
.py
"""Raw textpage char extraction, Type3 sizing, and page viewport handling.""" from __future__ import annotations import ctypes import pypdfium2.raw as pdfium_c from .text_normalize import ( _is_whitespace, _is_zero_width_diacritic, _is_invisible_format_mark, ) from .geometry import ( _collect_text_ob...
394
22,291
PageIndex
pageindex/flash/parser_pdfium_charlevel/remerge.py
.py
"""Re-merges rotated, oblique, and vertical spans after the first join pass.""" from __future__ import annotations import math from .text_normalize import ( TRACKING_SPACE_FACTOR, NEGATIVE_SPACE_FACTOR, SPACE_IN_FLOW_MIN_FACTOR, SPACE_IN_FLOW_MAX_FACTOR, ) def _start_rot_span(chunk: dict) -> dict: ...
328
17,929
PageIndex
pageindex/flash/parser_pdfium_charlevel/text_normalize.py
.py
"""Unicode normalization tables, whitespace classes, spacing factors, and bidi reordering.""" from __future__ import annotations import json import unicodedata from pathlib import Path _DROP_CHARS = str.maketrans({ # U+FFFE is PDFium's "no unicode mapping" textpage sentinel. The # patch pipeline (_apply_fon...
289
14,365
PageIndex
pageindex/flash/parser_pdfium_charlevel/__init__.py
.py
"""PDFium-backed text-item reconstruction via textpage chars and bbox-mapped font handles. The parser reconstructs content-stream text items from rendered characters while preserving the geometry needed by downstream line clustering and heading detection. The merge thresholds operate on glyph advance, font size, text ...
172
4,426
PageIndex
pageindex/flash/parser_pdfium_charlevel/unicode_apply.py
.py
"""Applies per-font Unicode maps to page chars and synthesizes dropped glyphs.""" from __future__ import annotations import bisect import difflib from collections import Counter import pypdfium2.raw as pdfium_c from .text_normalize import _is_whitespace from .font_unicode import _font_unicode_map from .code_walk imp...
376
21,619
PageIndex
pageindex/flash/parser_pdfium_charlevel/glyph_tables.py
.py
"""Bundled glyph-name and encoding tables with cached lazy loading.""" from __future__ import annotations import json from pathlib import Path from .cmap_parse import _parse_int # --------------------------------------------------------------------------- # Font Unicode-map construction. # # PDFium's per-character...
83
3,457
PageIndex
pageindex/flash/parser_pdfium_charlevel/geometry.py
.py
"""Transform matrices, text-object collection, and char-to-object mapping.""" from __future__ import annotations import ctypes import math import pypdfium2.raw as pdfium_c def _obj_rotation(value: float, other_item: float, candidate_item: float, reference_item: float) -> int: """Classify a text-object matrix as...
237
13,191
PageIndex
pageindex/flash/parser_pdfium_charlevel/code_walk.py
.py
"""Resource-dictionary xref walking and per-page show-code enumeration.""" from __future__ import annotations import re import unicodedata from PyPDF2.generic import ( IndirectObject as PdfIndirectRef, NameObject as PdfName, NumberObject as PdfNumber, FloatObject as PdfFloat, BooleanObject as PdfBoolean, ...
250
14,095
PageIndex
pageindex/flash/parser_pdfium_charlevel/font_unicode.py
.py
"""Simple-font encoding resolution and per-font Unicode map construction.""" from __future__ import annotations import re from .glyph_tables import ( _load_glyph_tables, _get_unicode_for_glyph, _from_char_code, ) from .cmap_parse import ( _to_number, _parse_int, _parse_tounicode_cmap, ) _TY...
395
19,588
PageIndex
pageindex/flash/parser_pdfium_charlevel/merge.py
.py
"""Joins page glyphs into text runs with spacing and style thresholds.""" from __future__ import annotations from .text_normalize import ( TRACKING_SPACE_FACTOR, NON_SPACE_GAP_FACTOR, NEGATIVE_SPACE_FACTOR, SPACE_IN_FLOW_MIN_FACTOR, SPACE_IN_FLOW_MAX_FACTOR, _rtl_sign, _read_end, _read...
527
29,509
PageIndex
pageindex/flash/parser_pdfium_charlevel/pdf_objects.py
.py
"""Raw PDF object access (PyPDF2-backed) and PDF lexical primitives.""" from __future__ import annotations from PyPDF2.generic import ( IndirectObject as PdfIndirectRef, NameObject as PdfName, NumberObject as PdfNumber, FloatObject as PdfFloat, BooleanObject as PdfBoolean, DictionaryObject as PdfDictionar...
192
6,943
PageIndex
pageindex/flash/parser_pdfium_charlevel/cmap_parse.py
.py
"""PostScript number parsing and ToUnicode CMap interpretation.""" from __future__ import annotations import math import re from .pdf_objects import ( _PDF_WHITESPACE_BYTES, _PDF_DELIMITER_BYTES, _PDF_STRING_ESCAPE_BYTES, ) from .text_normalize import _WHITESPACE_CODEPOINTS def _utf16be_units_to_str(un...
342
17,674
PageIndex
pageindex/flash/clustering/__init__.py
.py
"""Line clustering pipeline. The initial pass walks spans in document order and groups them into lines using an in-line continuation test, while also collapsing overstrike duplicates (artificial-bold rendering where the same glyph is painted twice). The merge pass inserts lines into a sorted structure keyed by top-des...
69
1,790
PageIndex
pageindex/flash/clustering/build.py
.py
"""Builds initial lines and clusters them into merged lines.""" from __future__ import annotations from dataclasses import dataclass, field from typing import Optional from sortedcontainers import SortedKeyList from ..model import ( _UNICODE_WHITESPACE_CLASS, avg_char_width2, Span, magnitude_ratio, ...
212
9,825
PageIndex
pageindex/flash/clustering/merge_rules.py
.py
"""Span continuation and line-merge predicates.""" from __future__ import annotations import re from typing import Optional from ..model import ( _UNICODE_WHITESPACE_CLASS, avg_char_width2, Span, magnitude_ratio, same_x_extent, same_y_extent, append_span, last_span, avg_char_width...
191
8,783
PageIndex
pageindex/flash/stats/__init__.py
.py
"""Page-level and document-level layout statistics. The statistics layer computes weighted percentiles, dominant styles, script families, page spacing measures, and document-wide recurrence signals used by classification and outline assembly. """ import functools import json import math from pathlib import Path from t...
49
1,154
PageIndex
pageindex/flash/stats/aggregates.py
.py
"""Page-level and document-level statistics aggregation.""" from __future__ import annotations import functools import math from typing import Optional from ..model import Span, _format_half_up_one_decimal, Line, info_weight, _max_nan_propagating from .scripts import ( ScriptHistogram, tally_scripts, do...
314
14,091
PageIndex
pageindex/flash/stats/scripts.py
.py
"""Script bucket tables and script histogram helpers.""" from __future__ import annotations import json from pathlib import Path # --------------------------------------------------------------------------- # # Script-family detector and bucket table. # --------------------------------------------------------------...
86
2,925
PageIndex
pageindex/flash/phases/page_view.py
.py
"""Per-page processing driver and reading-order assignment.""" from __future__ import annotations from typing import Optional from ..clustering import LinesContainer, cluster_lines, build_initial_lines from ..columns import detect_columns, ColumnDetectionContext, columns_to_x_bounds from ..model import ( Span, ...
124
6,281
PageIndex
pageindex/flash/phases/__init__.py
.py
"""Per-page pipeline orchestration. For each page, the extractor builds initial lines, computes page statistics, detects columns, reclusters lines with column awareness, removes line-number artifacts, recomputes statistics, and assigns reading order. """ import math from typing import Optional from sortedcontainers i...
51
1,236