LeanReader#
- class scikitplot.corpus.LeanReader(input_path, chunker=None, filter_=None, filename_override=None, default_language=None, source_uri=None, source_provenance=<factory>, custom_extractor=None, custom_extractor_kwargs=<factory>, max_text_chars=None, max_text_chars_per_byte=None, on_text_limit='refuse', encoding=None, max_file_bytes=52428800, lines_per_chunk=200, language=None, proofs='keep', kinds=None, watch=(), commands=(), dialect='lean4', max_scope_depth=256, references=False, statements=False)[source]#
Read a Lean source file one command at a time, each chunk naming its declaration.
- Parameters:
- input_pathpathlib.Path
Path to the
.leanfile.- proofs{“keep”, “drop”}, optional
"keep"(default) keeps every line."drop"leaves out the proofs oftheorem,lemmaandexample: the chunk holds the statement (doc comment and attributes included) and names the proof’s lines inproof_line_startandproof_line_end. A statement index of a large development is a fraction of its size.- kindscollection of str or None, optional
Only chunks whose
lean_kindis in this collection are yielded, for example{"theorem", "lemma"}.None(default): all.- watchcollection of str, optional
Identifiers to find: each chunk lists in
watchedthose it uses in code. A name matches whole, or as the last components of a dotted name (keyLemmamatchesMain.keyLemmaand thekeyLemmaofkeyLemma.symm). Default: none.- commandscollection of str, optional
Further command keywords that start a chunk of their own at column 0, for commands a project defines: those an index reads with (
scikitplot.lean.LeanIndex.commands), or those every file of the project defines (scikitplot.lean.defined_commands). Default: none.- referencesbool, optional
Also record, per chunk, the identifiers its code uses (
references) and the namespaces open for it (opens): whatLeanIndexresolves into a dependency graph. Default:False.- statementsbool, optional
Also record, on each
theoremandlemmachunk, its statement (its text before the proof) instatement, every line still kept: whatLeanIndexgroups by shape. Needsproofs="keep"andlines_per_chunk=None(a part could cut a statement short). Default:False.- dialect{“lean4”, “lean3”}, optional
"lean3"also reads Lean 3’sbegin ... endandmatch ... endblocks, whoseendcloses no namespace, and its| pattern := proofequations. Default:"lean4".- max_scope_depthint, optional
Most namespaces and sections open at once; deeper nesting is refused. Default: 256.
- lines_per_chunkint or None, optional
A command longer than this is yielded in parts of at most this many lines, each with
part(1, 2, …).None: one chunk per command. Default: 200.- encoding, max_file_bytes, language
As for
CodeReader.
- Attributes:
- flag_tokensMapping of str to str
Class variable: code token to audit flag,
LEAN_FLAGS. Subclass to change it.
- Raises:
- TypeError
If
kinds,watchorcommandsis not a collection of str, orreferencesorstatementsis not a bool.- ValueError
If an option’s value is invalid,
statements=Trueis given withproofs="drop"orlines_per_chunk, the file is too large or binary, or it nests more thanmax_scope_depthscopes.
- Parameters:
input_path (Path)
chunker (ChunkerBase | None)
filter_ (FilterBase | None)
filename_override (str | None)
default_language (str | None)
source_uri (str | None)
custom_extractor (Any | None)
max_text_chars (int | None)
max_text_chars_per_byte (float | None)
on_text_limit (str)
encoding (str | Sequence[str] | Callable[[bytes], str] | None)
max_file_bytes (int)
lines_per_chunk (int | None)
language (str | None)
proofs (str)
kinds (Collection[str] | None)
watch (Collection[str])
commands (Collection[str])
dialect (str)
max_scope_depth (int)
references (bool)
statements (bool)
See also
scikitplot.corpus._readers.CodeReaderOther source code, in line blocks.
Notes
User note. Each chunk carries
language("lean"),line_startandline_end(1-based, inclusive, the file’s own line numbers),encoding, and:lean_kind: the command keyword ("theorem","def","instance","#eval", …);"import"for the module header,"context"for a run ofopen,variable,namespace,section,end,set_option…;"moduledoc"for a/-! -/comment;"comment"for comments apart from any command;"command"for code before any known command.declaration: the fully qualified name, namespaces included (_root_.removed); absent for unnamed declarations (example, an unnamedinstance).namespace,modifiers(private,noncomputable, …),attributes(simp,implemented_by, …) andimports, when present.flags: audit marks found in the chunk’s code (seeLEAN_FLAGS); withproofs="drop"the dropped proof’s marks are on its statement.watched,part,proof_line_start,proof_line_end,statement: see the options.source_problems: text Lean refuses to read, on the chunk holding its line, as{"line", "problem"}items: anendthat closes no scope or names another, a file ending inside a comment, string or «name», and bytes that are not UTF-8 (Lean reads UTF-8 only; the text is decoded with the codec chosen for the file, named in the problem). Withkindsset, a problem on a chunk left out is not yielded.With
references=True:references, the identifiers the chunk’s code uses, sorted, without Lean’s own words and the chunk’s own name (withproofs="drop", the dropped proof’s too); andopens, the namespaces open for it (its file’s, its scopes’, its ownopen .. in). Which declaration an identifier names is forLeanIndexto resolve.
With
proofs="keep"andkinds=Noneevery non-blank line of the file is in exactly one chunk, in order: the line ranges never overlap.What starts a command. A known command keyword at column 0, after any attributes and modifiers (
@[simp] private theorem); a declaration keyword (theorem,def,instance, …) or a scope keyword at any indentation, since those never begin a line of a proof; insidemutual, the indentation of its first declaration. A doc comment, an attribute line and comments directly above a command belong to it;open Foo inandset_option o v injoin the command they prefix, so its flags include the option. Any other line continues the command before it: a command a project defines withsyntaxis read as part of the preceding chunk unless it is named incommands. A declaration’s name is read from its keyword’s line.Lexical audit, not proof checking.
flagssay what the text contains, outside comments and strings. A macro that expands tosorryis flagged where it is defined, not where it is used, and an axiom is flagged where it is declared, not in the theorems that use it. Whether a theorem is proved from Lean’s standard axioms alone is what#print axioms(and an independent kernel replay) answers.Statement and proof. With
proofs="drop"the statement ends at the first:=outside brackets that is not alet’s or ahave’s, at awhere, or at a line that starts with|and holds=>(:=in Lean 3): the equations of a proof by pattern matching. Definitions keep their bodies; their values are their meaning.Indexing.
scikitplot.lean.LeanIndex.add_chunksindexes a file read withreferences=True, statements=True, lines_per_chunk=Noneand the project’scommands, for example from an archive: the same declarations, references, flags, statement shapes and source problems asadd_filereads from a UTF-8 file.Developer note. The file is decoded as
TextReaderdecodes it, then read line by line through a lexer that blanks comments, strings and character literals (Lean’s rules: nested/- -/,/--and/-!docs, escapes and gaps,s!interpolation,r#"..."#raw strings,'primes, «names» over lines). Every pattern moves forward, so time is linear in the file’s size, and memory is one command (a long one is emitted in parts as it is read) plus at mostmax(lines_per_chunk, 256)comment lines waiting for the next command.Examples
>>> from pathlib import Path >>> reader = LeanReader(input_path=Path("Main.lean")) >>> [ ... c.get("declaration") ... for c in reader.get_raw_chunks() ... if c["lean_kind"] == "theorem" ... ] ['mainTheorem', ...]
Statements only, with every use of a name located:
>>> reader = LeanReader( ... input_path=Path("Main.lean"), proofs="drop", watch=["keyLemma"] ... )
- property backend_reports: tuple[dict[str, Any], ...]#
Return structured optional-backend reports from the current run.
Reports are JSON-compatible dictionaries. They intentionally retain exception type/message strings rather than live exception objects, so fail-soft readers remain observable without retaining traceback object graphs.
get_documentsclears old reports at the start of each run.- Returns:
- tuple of dict
One report per backend operation that opted into central orchestration. Empty when no optional backend operation ran.
- chunker: ChunkerBase | None = None#
Chunker to apply to each raw text block.
Nonemeans each raw chunk is used as-is (one CorpusDocument per raw chunk).
- clear_backend_reports()[source]#
Clear structured optional-backend reports on this reader instance.
- Return type:
None
- commands: Collection[str] = ()#
Further command keywords that start a chunk at column 0.
- classmethod create(*input_path, chunker=None, filter_=None, filename_override=None, default_language=None, source_type=None, source_title=None, source_author=None, source_date=None, collection_id=None, doi=None, isbn=None, **kwargs)[source]#
Instantiate the appropriate reader for one or more sources.
Accepts any mix of file paths, URL strings, and
pathlib.Pathobjects — in any order. URL strings (those starting withhttp://orhttps://) are automatically detected and routed tofrom_url; everything else is treated as a local file path and dispatched by extension via the registry.- Parameters:
- *input_pathstr or pathlib.Path
One or more source paths or URL strings. Each element is classified independently:
strmatching^https?://(case-insensitive) — treated as a URL and routed tofrom_url. Must be passed as a plain ``str``, not wrapped inpathlib.Path; wrapping collapses the double-slash (https://→https:/) and breaks URL detection.strnot matching the URL pattern — treated as a local file path and converted topathlib.Pathinternally.pathlib.Path— always treated as a local file path and dispatched by extension via the reader registry.
Pass a single value for the common case; pass multiple values to get a
_MultiSourceReaderthat chains all their documents in order.- chunkerChunkerBase or None, optional
Chunker injected into every reader. Default:
None.- filter_FilterBase or None, optional
Filter injected into every reader. Default:
None(DefaultFilter).- filename_overridestr or None, optional
Override the
input_pathlabel. Only applied when input_path contains exactly one source. Default:None.- default_languagestr or None, optional
ISO 639-1 language code applied to all sources. Default:
None.- source_typeSourceType, list[SourceType or None], or None, optional
Semantic label for the source kind. When input_path has more than one element you may pass a list of the same length to assign a distinct type per source;
Noneentries in the list mean “infer from extension / URL”. A single value is broadcast to all sources. Default:None.- source_titlestr or None, optional
Title propagated into every yielded document. Default:
None.- source_authorstr or None, optional
Author propagated into every yielded document. Default:
None.- source_datestr or None, optional
ISO 8601 publication date. Default:
None.- collection_idstr or None, optional
Corpus collection identifier. Default:
None.- doistr or None, optional
Digital Object Identifier (file sources only). Default:
None.- isbnstr or None, optional
ISBN (file sources only). Default:
None.- **kwargsAny
Extra keyword arguments forwarded verbatim to each concrete reader constructor (e.g.
transcribe=TrueforAudioReader,backend="easyocr"forImageReader).
- Returns:
- DocumentReader
A single reader when input_path has exactly one element (backward compatible with every existing call site). A
_MultiSourceReaderwhen input_path has more than one element — it implements the sameget_documents()interface and chains documents from all sub-readers in order.
- Raises:
- ValueError
If input_path is empty, or if a source URL is invalid, or if no reader is registered for a file’s extension.
- TypeError
If any element of input_path is not a
strorpathlib.Path.
- Parameters:
input_path (str | pathlib.Path)
chunker (ChunkerBase | None)
filter_ (FilterBase | None)
filename_override (str | None)
default_language (str | None)
source_type (SourceType | list[SourceType | None] | None)
source_title (str | None)
source_author (str | None)
source_date (str | None)
collection_id (str | None)
doi (str | None)
isbn (str | None)
kwargs (Any)
- Return type:
Self
Notes
URL auto-detection: A
strelement is treated as a URL when it matches^https?://(case-insensitive). All other strings and allpathlib.Pathobjects are treated as local file paths. This means you no longer need to callfrom_urlexplicitly — just pass the URL string tocreate.Per-source source_type: When passing multiple input_path with different media types, supply a list:
DocumentReader.create( Path("podcast.mp3"), "report.pdf", "https://iris.who.int/.../content", # returns image/jpeg source_type=[SourceType.PODCAST, SourceType.RESEARCH, SourceType.IMAGE], )
Reader-specific kwargs (forwarded via
**kwargs):transcribe=True,whisper_model="small",strict=False→AudioReader,VideoReaderbackend="easyocr"→ImageReaderprefer_backend="pypdf"→PDFReaderclassify=True,classifier=fn→AudioReader
Examples
Single file (backward-compatible):
>>> reader = DocumentReader.create(Path("hamlet.txt")) >>> docs = list(reader.get_documents())
URL string auto-detected — no from_url() call required:
>>> reader = DocumentReader.create( ... "https://en.wikipedia.org/wiki/Python_(programming_language)" ... )
Mixed multi-source batch:
>>> reader = DocumentReader.create( ... Path("podcast.mp3"), ... "report.pdf", ... "https://iris.who.int/api/bitstreams/abc/content", ... source_type=[SourceType.PODCAST, SourceType.RESEARCH, SourceType.IMAGE], ... ) >>> docs = list(reader.get_documents()) # chained stream from all three
- custom_extractor: Any | None = None#
User-supplied extraction callable that replaces
get_raw_chunksentirely for this reader instance.When set,
_iter_raw_chunkscallscustom_extractor(self.input_path, **custom_extractor_kwargs)and normalises the return value throughnormalize_extractor_output. The built-inget_raw_chunksimplementation is not called.This hook is available on every reader class (
ALTOReader,TextReader,PDFReader,ImageReader, etc.) without any subclassing — simply pass a callable at construction time.Callable contract
def my_extractor(path: pathlib.Path, **kwargs) -> ExtractorOutput
where
ExtractorOutputisstr,list[str],dict, orlist[dict]— the same contract asCustomReader.Examples
Override PDF extraction with
pdfplumberfor a single reader:import pdfplumber from pathlib import Path from scikitplot.corpus._base import DocumentReader def plumber_fn(path, **kw): with pdfplumber.open(path) as pdf: return [{"text": p.extract_text() or "", "page_number": i} for i, p in enumerate(pdf.pages)] reader = DocumentReader.create( Path("report.pdf"), custom_extractor=plumber_fn, ) docs = list(reader.get_documents())
- custom_extractor_kwargs: dict[str, Any][source]#
Extra keyword arguments forwarded to
custom_extractoron every invocation. Merged into the call as**custom_extractor_kwargs.Examples
reader = DocumentReader.create( Path("report.pdf"), custom_extractor=my_fn, custom_extractor_kwargs={"password": "s3cret", "pages": [0, 1, 2]}, )
- default_filter[source]#
alias of
CodeAwareFilter
- default_language: str | None = None#
ISO 639-1 language code to assign when the source has no language info.
- encoding: str | Sequence[str] | Callable[[bytes], str] | None = None#
None(detect, see the Notes), a codec name, a list of candidate codecs,"chardet", or a callable(raw: bytes) -> codec. Default:None.- Type:
How the file is decoded
- property file_name: str#
Effective filename used in document labels.
Returns
filename_overridewhen set; otherwise returnsinput_path.name.- Returns:
- str
File name string (not a full path).
Examples
>>> from pathlib import Path >>> reader = TextReader(input_path=Path("/data/corpus.txt")) >>> reader.file_name 'corpus.txt'
- file_type: ClassVar[str] = '.lean'#
Single file extension this reader handles (lowercase, including leading dot). E.g.
".txt",".xml",".zip".For readers that handle multiple extensions, define
file_types(plural) instead. Exactly one offile_typeorfile_typesmust be defined on every concrete subclass.
- file_types: ClassVar[list[str] | None] = ['.lean']#
List of file extensions this reader handles (lowercase, leading dot). Use instead of
file_typewhen a single reader class should be registered for several extensions — e.g. an image reader for[".png", ".jpg", ".jpeg", ".gif", ".webp"].When both
file_typeandfile_typesare defined on the same class,file_typestakes precedence andfile_typeis ignored.
- filter_: FilterBase | None = None#
Filter applied after chunking.
Noneuses the reader’sdefault_filter(DefaultFilterunless the reader says otherwise).
- flag_tokens: ClassVar[Mapping[str, str]] = mappingproxy({'sorry': 'sorry', 'sorryAx': 'sorry', 'mkSorry': 'sorry', 'mkLabeledSorry': 'sorry', 'admit': 'admit', 'native_decide': 'native', 'ofReduceBool': 'native', 'ofReduceNat': 'native', '+native': 'native', 'unsafe': 'unsafe', 'implemented_by': 'implemented_by', 'extern': 'extern', 'skipKernelTC': 'skip_kernel_tc', 'addDecl': 'add_decl', 'addAndCompile': 'add_decl', 'axiomDecl': 'axiom'})#
- classmethod from_manifest(manifest_path, *, chunker=None, filter_=None, default_language=None, source_type=None, source_title=None, source_author=None, source_date=None, collection_id=None, doi=None, isbn=None, encoding='utf-8', **kwargs)[source]#
Build a
_MultiSourceReaderfrom a manifest file.The manifest is a text file with one source per line — either a file path or a URL. Blank lines and lines starting with
#are ignored. JSON manifests (a list of strings or objects) are also supported.- Parameters:
- manifest_pathstr or pathlib.Path
Path to the manifest file. Supported formats:
.txt/.manifest— one source per line..json— a JSON array of strings (sources) or objects with at least a"source"key (and optional"source_type","source_title"per-entry overrides).
- chunkerChunkerBase or None, optional
Chunker applied to all sources. Default:
None.- filter_FilterBase or None, optional
Filter applied to all sources. Default:
None.- default_languagestr or None, optional
ISO 639-1 language code. Default:
None.- source_typeSourceType or None, optional
Override source type for all sources. Default:
None.- source_titlestr or None, optional
Override title for all sources. Default:
None.- source_authorstr or None, optional
Override author for all sources. Default:
None.- source_datestr or None, optional
Override date for all sources. Default:
None.- collection_idstr or None, optional
Collection identifier. Default:
None.- doistr or None, optional
DOI override. Default:
None.- isbnstr or None, optional
ISBN override. Default:
None.- encodingstr, optional
Text encoding for
.txtmanifests. Default:"utf-8".- **kwargsAny
Forwarded to each reader constructor.
- Returns:
- _MultiSourceReader
Multi-source reader chaining all manifest entries.
- Raises:
- ValueError
If manifest_path does not exist or is empty after filtering blank and comment lines.
- ValueError
If the manifest format is not recognised.
- Parameters:
chunker (ChunkerBase | None)
filter_ (FilterBase | None)
default_language (str | None)
source_type (SourceType | None)
source_title (str | None)
source_author (str | None)
source_date (str | None)
collection_id (str | None)
doi (str | None)
isbn (str | None)
encoding (str)
kwargs (Any)
- Return type:
_MultiSourceReader
Notes
Per-entry overrides in JSON manifests: each entry may be an object with:
{ "source": "https://example.com/report.pdf", "source_type": "research", "source_title": "Annual Report 2024", }
String-level
source_typevalues are coerced viaSourceType(value)and an invalid value raisesValueError.Examples
Text manifest
sources.txt:# WHO corpus https://www.who.int/europe/news/item/... https://youtu.be/rwPISgZcYIk WHO-EURO-2025.pdf scan.jpg
Usage:
reader = DocumentReader.from_manifest( Path("sources.txt"), collection_id="who-corpus", ) docs = list(reader.get_documents())
- classmethod from_url(url, *, chunker=None, filter_=None, filename_override=None, default_language=None, source_type=None, source_title=None, source_author=None, source_date=None, collection_id=None, doi=None, isbn=None, **kwargs)[source]#
Instantiate the appropriate reader for a URL source.
Dispatches to
YouTubeReaderfor YouTube URLs and toWebReaderfor all otherhttp:///https://URLs.- Parameters:
- urlstr
Full URL string. Must start with
http://orhttps://.- chunkerChunkerBase or None, optional
Chunker to inject. Default:
None.- filter_FilterBase or None, optional
Filter to inject. Default:
None(DefaultFilter).- filename_overridestr or None, optional
Override for the
input_pathlabel. Default:None.- default_languagestr or None, optional
ISO 639-1 language code. Default:
None.- source_typeSourceType or None, optional
Semantic label for the source. Default:
None.- source_titlestr or None, optional
Title of the source work. Default:
None.- source_authorstr or None, optional
Primary author. Default:
None.- source_datestr or None, optional
Publication date in ISO 8601 format. Default:
None.- collection_idstr or None, optional
Corpus collection identifier. Default:
None.- doistr or None, optional
Digital Object Identifier. Default:
None.- isbnstr or None, optional
International Standard Book Number. Default:
None.- **kwargsAny
Additional kwargs forwarded to the reader constructor (e.g.
include_auto_generated=FalseforYouTubeReader).
- Returns:
- DocumentReader
YouTubeReaderorWebReaderinstance.
- Raises:
- ValueError
If
urldoes not start withhttp://orhttps://.- ImportError
If the required reader class is not registered (i.e.
scikitplot.corpus._readershas not been imported yet).
- Parameters:
url (str)
chunker (ChunkerBase | None)
filter_ (FilterBase | None)
filename_override (str | None)
default_language (str | None)
source_type (SourceType | None)
source_title (str | None)
source_author (str | None)
source_date (str | None)
collection_id (str | None)
doi (str | None)
isbn (str | None)
kwargs (Any)
- Return type:
Self
Notes
Prefer :meth:`create` for new code. Passing a URL string to
createautomatically callsfrom_url— you rarely need to callfrom_urldirectly.Examples
>>> reader = DocumentReader.from_url("https://en.wikipedia.org/wiki/Python") >>> docs = list(reader.get_documents())
>>> yt = DocumentReader.from_url("https://www.youtube.com/watch?v=rwPISgZcYIk") >>> docs = list(yt.get_documents())
- get_documents()[source]#
Yield validated
CorpusDocumentinstances for the input file.Orchestrates the full per-file pipeline:
validate_input— fail fast if file is missing.get_raw_chunks— format-specific text extraction.Chunker (if set) — sub-segments each raw block.
CorpusDocumentconstruction with validated schema.Filter — discards noise documents.
- Yields:
- CorpusDocument
Validated documents that passed the filter.
- Raises:
- ValueError
If the input file is missing or the format is invalid.
- Return type:
Generator[CorpusDocument, None, None]
Notes
The global
chunk_indexcounter is monotonically increasing across all raw chunks and sub-chunks for a single file, ensuring that(input_path, chunk_index)is a unique key within one reader run.Omitted-document statistics are logged at INFO level after processing each file.
Examples
>>> from pathlib import Path >>> reader = DocumentReader.create(Path("corpus.txt")) >>> docs = list(reader.get_documents()) >>> all(isinstance(d, CorpusDocument) for d in docs) True
- get_raw_chunks()[source]#
Yield the file’s commands, each with its line range and declaration.
- Yields:
- dict
text,section_type,source_type,language,encoding,line_start,line_end,lean_kindand, when they apply,declaration,namespace,modifiers,attributes,imports,flags,watched,part,proof_line_start,proof_line_end,statementandsource_problems.
- Raises:
- ValueError
If the file is too large or binary, or nests more than
max_scope_depthscopes.
- Return type:
- input_path: Path[source]#
Path to the source file.
For URL-based readers (
WebReader,YouTubeReader), passpathlib.Path(url_string)here and setsource_urito the original URL string.validate_input()is overridden in those subclasses to skip the file-existence check.
- kinds: Collection[str] | None = None#
all.
- Type:
Only these
lean_kindvalues are yielded;None
- max_text_chars: int | None = None#
Most characters of text one input may yield, over all its chunks.
The bound on what a small input can expand into (compressed or repeated content).
None(the default here): no limit, for formats whose text cannot outgrow their input, already bounded by their size limit. Readers of amplifying formats (OfficeReader,PDFReader) default to 256 Mi characters. Counted as chunks stream, at the one place every chunk passes (_iter_raw_chunks), custom extractors included.
- max_text_chars_per_byte: float | None = None#
Most characters of text per byte of the input file.
Keeps the output, and so the work of extracting it, in proportion to the input: with it, the limit is the smaller of
max_text_charsandmax(max_text_chars_per_byte x file size, 1 Mi)characters (a small file may always yield 1 Mi). It covers compression, shared and repeated content alike.None(the default here): no ratio limit;OfficeReaderandPDFReaderdefault to 50 (ordinary documents yield under 10 characters per byte). Not applied when the input is not a file on disk.
- on_text_limit: str = 'refuse'#
What happens past the text limit (
max_text_chars,max_text_chars_per_byte):"refuse"(default) raisesValueError;"truncate"keeps exactly the firstmax_text_charscharacters, marks the chunk it cutstext_truncated=True(none when the limit falls between chunks) and logs a warning either way.
- source_provenance: dict[str, Any][source]#
Provenance overrides propagated into every yielded
CorpusDocument.Keys may include
"source_type","source_title","source_author", and"collection_id". Populated bycreate/from_urlfrom their keyword arguments.
- source_uri: str | None = None#
Original URI for URL-based readers (web pages, YouTube videos).
Set this to the full URL string when
input_pathis a syntheticpathlib.Pathwrapping a URL. File-based readers leave thisNone.Examples
>>> reader = WebReader( ... input_path=Path("https://example.com/article"), ... source_uri="https://example.com/article", ... )
- classmethod subclass_by_type()[source]#
Return a copy of the extension → reader class registry.
- Returns:
- dict
Mapping of file extension (str) → reader class. Returns a shallow copy so callers cannot accidentally mutate the registry.
- Return type:
Examples
>>> registry = DocumentReader.subclass_by_type() >>> ".txt" in registry True
- classmethod supported_types()[source]#
Return a sorted list of file extensions supported by registered readers.
- Returns:
- list of str
Lowercase file extensions, each including the leading dot. E.g.
['.pdf', '.txt', '.xml', '.zip'].
- Return type:
Examples
>>> DocumentReader.supported_types() ['.pdf', '.txt', '.xml', '.zip']
- validate_input()[source]#
Assert that the input file exists and is readable.
- Raises:
- ValueError
If
input_pathdoes not exist or is not a regular file.
- Return type:
None
Notes
Called automatically by
get_documentsbefore iterating. Can also be called eagerly after construction to fail fast.Examples
>>> reader = DocumentReader.create(Path("missing.txt")) >>> reader.validate_input() Traceback (most recent call last): ... ValueError: Input file does not exist: missing.txt
- watch: Collection[str] = ()#
Identifiers to locate; each chunk lists those it uses in
watched.
Gallery examples#
Read Lean Proofs with LeanReader: Tracing Every Line of a Formal Development