Converters API
Document format converters used in Stage 0 (Preprocess).
Converter Registry
scinr.newton.converters.registry
converters/registry.py — Extension-to-converter registry.
Provides get_converter(path) which returns the appropriate
BaseConverter instance for a given file path.
apply_converter_overrides
Apply converter overrides/additions to the registry.
Parameters
overrides: Dict mapping file extensions (without leading dot, lowercase) to BaseConverter subclasses. Existing extensions are overridden. New extensions are registered.
Raises
ConfigurationError If any converter class is not a subclass of BaseConverter.
Example
configure(extra_converters={ "pdf": MyCustomPdfConverter, # override built-in PDF converter "epub": EpubConverter, # add new format })
get_converter
Return the appropriate converter instance for path.
Parameters
path: File to be converted. The extension (case-insensitive, without leading dot) is used to look up the converter.
Returns
BaseConverter A freshly instantiated converter for the file's format.
Raises
UnsupportedFormatError If no converter is registered for the file's extension.
Base Classes
scinr.newton.converters.base
converters/base.py — Core dataclasses and abstract base converter.
Defines the intermediate document format that all converters produce, and the BaseConverter abstract class that all format-specific converters must implement.
BaseConverter
Bases: ABC
Abstract base class for all format-specific converters.
Subclasses must:
1. Define supported_extensions (frozenset of lowercase extensions
without leading dot, e.g. frozenset({"pdf"})).
2. Implement convert(source).
Subclasses whose convert() is implemented as a coroutine (async
def) rather than a regular blocking method — e.g. converters that
perform genuine async network I/O, like PdfConverter calling the
Mistral OCR API — must set the class attribute is_async = True.
ABC cannot verify at runtime whether a subclass's convert() is a
coroutine function, so this flag is purely declarative: callers (see
scinr.newton.converters.main._run_convert()) read it to decide
whether to await converter.convert(source) directly on the event
loop, or to dispatch the (blocking, sync) call to a worker thread via
asyncio.to_thread().
Parameters
supported_extensions : frozenset[str]
Class attribute listing the file extensions this converter handles.
is_async : bool
Class attribute declaring whether convert() is a coroutine
function. Defaults to False (regular sync method).
convert
abstractmethod
Convert source to the intermediate document format.
Parameters
source: Path to the source file to convert.
Returns
IntermediateDocument The converted document with one or more pages.
Raises
ConversionError If conversion fails for any reason. FileNotFoundError If source does not exist.
convert_and_write
Convert source and write the result to output_dir.
The output file is named {source.name}.json (the source file name
with its extension, e.g. doc.pdf.json). If a file with that name
already exists, a numeric suffix is appended to avoid silent
overwriting (e.g. doc.pdf_1.json).
Parameters
source: Path to the source file to convert. output_dir: Directory where the JSON output will be written. Created automatically if it does not exist.
Returns
Path Path to the written output file.
Raises
ConversionError
If conversion fails, or if this converter declares
is_async = True (async converters are not supported by
this method).
ConversionError
Bases: ConverterError, ScinrError
Raised when a converter fails to process a specific file.
ConverterError
Bases: Exception
Base class for converter errors (kept for backward compatibility).
IntermediateDocument
Bases: BaseModel
A complete document in the intermediate format.
This is the root object serialised to JSON and written to the converter output directory.
IntermediatePage
Bases: BaseModel
A single page of a document in the intermediate format.
This schema mirrors the Mistral OCR output consumed by Stage 1.
PageDimensions
Bases: BaseModel
Physical dimensions of a page.
PageImage
Bases: BaseModel
An image extracted from a page.
Parameters
index:
Zero-based position of the image within the page.
base64:
Base64-encoded image bytes. Empty when the image is loaded lazily
(see :meth:load_bytes) or once it has been released after the
embedded-image enrichment of Stage 0.
media_type:
MIME type of the image (e.g. "image/png").
description:
Textual description. Left empty by converters; filled by the
embedded-image enrichment of Stage 0 (describe_embedded_images,
only with a vision_llm configured).
image_id:
Id of the stored :class:~storage.models.PageImageRecord, when the
described image was stored (store_described_images with a
persistent storage backend whose stores_images is True).
Serialised in the intermediate JSON, like page_id.
ref:
Text that references the image in the page markdown as
. When present, the enrichment replaces that reference
with the description block; otherwise the block goes at the end of
the page.
width, height:
Size in pixels, when the converter knows it without decoding.
A converter may attach a private loader instead of filling base64
(PageImage(...)._loader = callable, see :meth:with_loader) so the
bytes are only read while the image is described. The loader is never
serialised: an intermediate JSON never carries lazy blobs.
load_bytes
Return the image bytes: from the loader if set, else decoded from base64.
UnsupportedFormatError
Bases: ConverterError
Raised when no converter is registered for the given file extension.
Format Converters
scinr.newton.converters.pdf
converters/pdf.py — PDF to Markdown converter via Mistral OCR API.
Submits the PDF as a base64 data URL to the Mistral OCR endpoint
(POST https://api.mistral.ai/v1/ocr). The JSON body is streamed: the
base64 is encoded block by block while it is sent (_OcrRequestBody), so
a request needs a few MB of memory whatever the size of the PDF. The API
response already matches the intermediate document format, so each page is
mapped directly to an IntermediatePage.
At most mistral_ocr_concurrency PDFs are converted at the same time per
event loop, independently of the caller's parallel_docs.
Para PDFs que exceden los límites de la API de Mistral OCR (máx. 1000
páginas / 50 MB por solicitud), el documento se divide automáticamente
en chunks contiguos (ver pdf_splitter.py), cada uno se envía por
separado, y los resultados se reúnen de forma transparente preservando
el índice de página absoluto del documento original. La división es
perezosa: los chunks se generan de uno en uno directamente desde el
fichero (nunca se lee el PDF completo en memoria), por lo que el pico de
memoria depende del tamaño de un chunk, no del del archivo. El manejo de
errores por chunk es configurable vía mistral_ocr_error_strategy
("fail_fast" por defecto, o "best_effort").
PdfConverter
Bases: BaseConverter
Convert .pdf files to the intermediate format via Mistral OCR.
Sends the PDF to the Mistral OCR API and maps the response to an
:class:~converters.base.IntermediateDocument. Each page returned
by Mistral becomes one :class:~converters.base.IntermediatePage.
Si el PDF excede los límites configurados de páginas o bytes, se
divide en chunks contiguos (ver :mod:pdf_splitter), cada uno se
envía por separado a la API, y las páginas resultantes se reúnen
preservando el índice absoluto del documento original. Los chunks se
generan de uno en uno directamente desde el fichero (iter_pdf_chunks),
de modo que solo hay un chunk en memoria a la vez.
Parameters
api_key:
Mistral API key. If None, the value of the environment
variable MISTRAL_API_KEY is used at conversion time.
safe_max_pages:
Override explícito del máximo de páginas por chunk. Si None,
se resuelve vía get_config() o el default del módulo.
safe_max_bytes:
Override explícito del máximo de bytes por chunk. Si None,
se resuelve vía get_config() o el default del módulo.
max_retries:
Override explícito del número máximo de intentos por chunk.
retry_backoff_seconds:
Override explícito de la base del backoff exponencial entre
reintentos.
error_strategy:
Override explícito de la estrategia de manejo de errores por
chunk: "fail_fast" o "best_effort".
Nota: esta estrategia solo aplica a fallos de red/API por chunk
(reintentos agotados, errores HTTP no reintentables) sobre chunks
ya generados por ``iter_pdf_chunks()``. NO cubre el caso en que la
propia partición falla estructuralmente
(:class:`PdfSplitError`, una página individual que excede
``safe_max_bytes`` incluso aislada) — en ese caso el documento
aborta siempre, independientemente del ``error_strategy``
configurado. Como los chunks se generan bajo demanda, ese error
puede detectarse tras haber enviado ya chunks anteriores a la API.
concurrency:
Override explícito del máximo de PDFs en conversión a la vez en el
event loop. Si None, se resuelve vía get_config()
(mistral_ocr_concurrency) o el default del módulo.
convert
async
Convert a PDF file to the intermediate format.
This is a native async def coroutine (not a sync method
dispatched to a thread): the actual conversion work is genuine
network I/O against the Mistral OCR API (httpx.AsyncClient,
with asyncio.sleep() backoff between retries), so it can be
awaited directly on the event loop without blocking it. See
is_async = True on this class and
scinr.newton.converters.main._run_convert() for how callers
dispatch based on this contract.
Parameters
source:
Path to the .pdf file.
Returns
IntermediateDocument
Document with one :class:~converters.base.IntermediatePage
per PDF page recognised by Mistral OCR. If el documento fue
dividido en chunks y alguno falló en modo best_effort,
missing_page_ranges contendrá los rangos omitidos.
Raises
FileNotFoundError If source does not exist. ConversionError If the Mistral API key is not available, the HTTP request fails, or the response is in an unexpected format.
scinr.newton.converters.docx
converters/docx.py — Microsoft Word DOCX to Markdown converter.
The DOCX document is split into pages using a two-layer strategy (tried in order, first match wins):
- Explicit breaks — any
<w:br w:type="page"/>run or<w:sectPr>section break triggers a page flush. A safety cap of_PARAGRAPHS_PER_PAGEelements is also applied so that a single logical section never grows unbounded. - Paragraph count — fallback; a new page every
_PARAGRAPHS_PER_PAGEelements (paragraphs + tables counted together).
No content is ever discarded.
Inline images of body paragraphs become lazy PageImage objects
(ref="docx-img-N", referenced in the paragraph text as
) only when embedded images are described
(describe_embedded_images with a vision_llm); otherwise no image blob
is read. Limitation: images in headers, footers, floating shapes and table
cells are not treated.
DocxConverter
Bases: BaseConverter
Convert .docx files to a paginated Markdown document.
Uses python-docx to iterate over paragraphs and tables in document
order. Headings are detected via paragraph style names and prefixed
with the appropriate number of # characters. Tables are rendered
as GFM Markdown tables.
Pagination strategy (first applicable wins):
- Explicit breaks (
<w:br w:type="page"/>or<w:sectPr>), with a_PARAGRAPHS_PER_PAGEsafety cap per section. - Paragraph/table count — new page every
_PARAGRAPHS_PER_PAGEelements.
convert
Convert a DOCX file to the intermediate format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
Path
|
Path to the |
required |
Returns:
| Type | Description |
|---|---|
IntermediateDocument
|
Multi-page document. The number of pages depends on which |
IntermediateDocument
|
pagination strategy is applied (see class docstring). |
Raises:
| Type | Description |
|---|---|
ConversionError
|
If |
FileNotFoundError
|
If source does not exist. |
scinr.newton.converters.pptx
converters/pptx.py — Microsoft PowerPoint PPTX to Markdown converter.
Each slide is rendered as a separate page. Text frames are converted to
Markdown (titles get a # prefix). Pictures become lazy PageImage
objects only when embedded images are described (describe_embedded_images
with a vision_llm). Tables are rendered as GFM Markdown tables.
PptxConverter
Bases: BaseConverter
Convert .pptx files to the intermediate format.
Each slide becomes a separate IntermediatePage. Text is extracted
from all text frames (title shapes get a # prefix). Pictures are
attached as lazy PageImage objects (no base64 until described) only
when embedded-image description is enabled; otherwise no image blob is
read. Tables are converted to GFM Markdown tables.
Requires python-pptx.
convert
Convert a PPTX file to the intermediate format.
Parameters
source:
Path to the .pptx file.
Returns
IntermediateDocument Multi-page document, one page per slide.
Raises
ConversionError
If python-pptx is not installed or the file cannot be parsed.
FileNotFoundError
If source does not exist.
scinr.newton.converters.xlsx
converters/xlsx.py — XLSX/XLS files are handled by the tabular ingestion pipeline.
XLSX/XLS files do not require conversion to an intermediate format.
Use: run_tabular_pipeline(
XlsxConverter
Bases: BaseConverter
Redirect handler for .xlsx and .xls files.
XLSX/XLS files are processed directly and efficiently by the tabular ingestion
pipeline. This converter raises a :class:ConversionError with a clear
redirect message so that callers know to use the correct pipeline stage.
scinr.newton.converters.csv
converters/csv.py — CSV files are handled by the tabular ingestion pipeline.
CSV files do not require conversion to an intermediate format.
Use: run_tabular_pipeline(
CsvConverter
Bases: BaseConverter
Redirect handler for .csv files.
CSV files are processed directly and efficiently by the tabular ingestion
pipeline. This converter raises a :class:ConversionError with a clear
redirect message so that callers know to use the correct pipeline stage.
scinr.newton.converters.html
converters/html.py — HTML/HTM to Markdown converter.
Extracts structured text from HTML using BeautifulSoup4 + lxml, converts headings/paragraphs/lists/tables to GFM Markdown, and removes noise (scripts, styles, nav, footer).
The document is split into pages at H1 headings (# … in Markdown).
Each H1 and its following content form one page. If the HTML has no H1
headings the entire document is a single page. No content is discarded.
HtmlConverter
Bases: BaseConverter
Convert .html and .htm files to the intermediate format.
Parses the HTML with BeautifulSoup4 (lxml backend) and converts the
document structure to GFM Markdown. The output is split into one page
per H1 heading (# …). Documents without H1 headings produce a
single page.
convert
Convert an HTML file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
Path
|
Path to the |
required |
Returns:
| Type | Description |
|---|---|
IntermediateDocument
|
Multi-page document split at H1 headings (one page per H1 |
IntermediateDocument
|
section). Produces a single page when no H1 headings are |
IntermediateDocument
|
present. |
Raises:
| Type | Description |
|---|---|
ConversionError
|
If BeautifulSoup4 or lxml is not installed, or the file cannot be parsed. |
scinr.newton.converters.api_json
converters/api_json.py — REST JSON API to intermediate document converter.
Fetches one or more pages of a JSON API, navigates the response with
JSONPath expressions, and maps each item to an
:class:~converters.base.IntermediatePage. Supports two pagination
strategies: following a next URL field (next_url) and classic
offset/limit pagination (offset_limit).
Config files can be YAML or JSON and are validated with Pydantic v2.
ApiJsonConverter
Convert a REST JSON API response to the intermediate document format.
This converter does not inherit from
:class:~converters.base.BaseConverter because its source is a URL,
not a file path. Use :meth:convert_from_url as the main entry
point.
Parameters
config: Mapping configuration describing how to navigate the API response. headers: Optional HTTP headers sent with every request (e.g. auth tokens).
convert_from_url
Fetch the API and convert the response to the intermediate format.
Parameters
url: Base URL of the API endpoint.
Returns
IntermediateDocument
One :class:~converters.base.IntermediatePage per item
extracted from the API response.
Raises
ConversionError If the HTTP request fails or the response cannot be parsed.
from_config_file
classmethod
Load configuration from a YAML or JSON file.
Parameters
config_path:
Path to a .yaml, .yml, or .json config file.
headers:
Optional HTTP headers forwarded to the constructor.
Returns
ApiJsonConverter
Raises
ConversionError If the file cannot be read, parsed, or validated.
ApiMappingConfig
Bases: BaseModel
Mapping configuration for a JSON REST API.
Parameters
document_name:
Human-readable name used in log messages.
items_path:
JSONPath expression pointing to the array of items in each
API response. Use "$" when the response is directly a list.
page_fields:
Mapping of field roles to JSONPath expressions evaluated on each
item. Recognised keys: "title", "content",
"metadata" (value may be a list of JSONPath strings).
pagination:
Optional pagination configuration.
PaginationConfig
Bases: BaseModel
Pagination strategy for a JSON API.
Parameters
type:
Pagination strategy: "next_url" follows a URL embedded in the
response; "offset_limit" increments an offset query parameter.
next_url_path:
JSONPath expression pointing to the next-page URL in the response.
Only used when type == "next_url".
offset_param:
Name of the offset query parameter.
Only used when type == "offset_limit".
limit_param:
Name of the limit query parameter.
Only used when type == "offset_limit".
limit:
Page size for offset/limit pagination.
total_path:
JSONPath expression pointing to the total item count in the
response. Only used when type == "offset_limit".
max_pages:
Hard cap on the number of requests made to prevent infinite loops.
scinr.newton.converters.api_xml
converters/api_xml.py — REST XML / SOAP API to intermediate document converter.
Fetches XML responses (REST or SOAP), parses them with lxml, navigates
the document with XPath expressions, and maps each matched element to an
:class:~converters.base.IntermediatePage. Supports two pagination
strategies (next_url and offset_limit) and optional SOAP
envelope wrapping.
Config files can be YAML or JSON and are validated with Pydantic v2.
ApiXmlConverter
Convert a REST XML or SOAP API response to the intermediate format.
This converter does not inherit from
:class:~converters.base.BaseConverter because its source is a URL,
not a file path. Use :meth:convert_from_url as the main entry
point.
Parameters
config: Mapping configuration describing how to navigate the API response. headers: Optional HTTP headers merged into every request (auth tokens, custom headers, etc.). SOAP-related headers are added automatically when required.
convert_from_url
Fetch the API and convert the response to the intermediate format.
Parameters
url:
URL of the API endpoint.
soap_body:
SOAP body content (without the envelope). If provided and
config.soap_envelope_template is not None (or
config.soap_action is set), the body is wrapped in the
SOAP envelope template before sending.
Returns
IntermediateDocument
One :class:~converters.base.IntermediatePage per XML element
matched by items_xpath.
Raises
ConversionError If the HTTP request fails or the XML cannot be parsed.
from_config_file
classmethod
Load configuration from a YAML or JSON file.
Parameters
config_path:
Path to a .yaml, .yml, or .json config file.
headers:
Optional HTTP headers forwarded to the constructor.
Returns
ApiXmlConverter
Raises
ConversionError If the file cannot be read, parsed, or validated.
ApiXmlMappingConfig
Bases: BaseModel
Mapping configuration for an XML REST or SOAP API.
Parameters
document_name:
Human-readable name used in log messages.
items_xpath:
XPath expression selecting the elements to convert to pages
(e.g. "//record").
page_fields:
Mapping of field roles to XPath expressions evaluated on each
element. Recognised keys: "title", "content",
"metadata" (value may be a list of XPath strings).
namespaces:
XML namespace prefix-to-URI mapping passed to all XPath calls.
pagination:
Optional pagination configuration.
soap_action:
Value of the SOAPAction HTTP header. When set, requests are
sent as SOAP POSTs.
soap_envelope_template:
XML template for the SOAP envelope. Must contain a {body}
placeholder. When None and soap_action is set, the
default SOAP 1.1 envelope is used.
XmlPaginationConfig
Bases: BaseModel
Pagination strategy for an XML API.
Parameters
type:
Pagination strategy: "next_url" follows a URL embedded in the
response; "offset_limit" increments an offset query parameter.
next_url_xpath:
XPath expression pointing to the next-page URL text.
Only used when type == "next_url".
offset_param:
Name of the offset query parameter.
Only used when type == "offset_limit".
limit_param:
Name of the limit query parameter.
Only used when type == "offset_limit".
limit:
Page size for offset/limit pagination.
total_xpath:
XPath expression pointing to the total item count text.
Only used when type == "offset_limit".
max_pages:
Hard cap on the number of requests made to prevent infinite loops.
scinr.newton.converters.text
converters/text.py — Plain text and Markdown converter.
The file is paginated into chunks of _LINES_PER_PAGE lines. Each
chunk becomes a separate IntermediatePage. .md files are passed
through unchanged (already Markdown); .txt files are used directly.
No lines are ever discarded.
TextConverter
Bases: BaseConverter
Convert .txt and .md files to the intermediate format.
The file content is split into pages of _LINES_PER_PAGE lines.
Markdown files are passed through as-is; plain text files are used
directly. An empty file produces a single empty page.
convert
Convert a text or Markdown file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
Path
|
Path to the |
required |
Returns:
| Type | Description |
|---|---|
IntermediateDocument
|
Multi-page document (one page per |
IntermediateDocument
|
An empty file produces a single empty page. |
Raises:
| Type | Description |
|---|---|
ConversionError
|
If the file cannot be read. |
Image, Audio and Video Converters
Always registered; a missing requirement (vision_llm, transcriber,
ffmpeg) fails that document at conversion with a message that says how to
configure it. See the Multimodal Ingestion guide.
scinr.newton.converters.image
converters/image.py — image files (photos, scans, screenshots) to text.
The whole image becomes one page: the vision_llm transcribes its visible
text and describes it (standalone mode). File metadata (size, capture
time, device and, only with strip_location=False, GPS) is read with
Pillow and reaches the :Document node as file_* properties.
Requirements are checked at conversion time: without a vision_llm the
conversion fails with a :class:ConversionError that says how to configure
it, before the file is read. HEIC/HEIF need pillow-heif
(pip install "scinr[media]").
Memory: one image (the file size) plus its downscaled JPEG copy while it is described.
ImageConverter
Bases: BaseConverter
Convert an image file into a one-page document with the vision_llm.
convert
async
Describe source and return it as a one-page document.
Raises
FileNotFoundError
If source does not exist.
ConversionError
No vision_llm configured, HEIC without pillow-heif, an
unreadable image or a failed model call (an image has nothing
partial to keep, so media_error_strategy does not apply).
read_image_metadata
Read size, capture time, device and (optionally) GPS from an encoded image.
The GPS IFD is not even read when strip_location is True. Size is
reported after EXIF orientation (a portrait photo is taller than wide).
scinr.newton.converters.audio
converters/audio.py — audio files to text with the configured transcriber.
One page per segment of media_segment_seconds, with start_ms /
end_ms and a time header::
[00:05:00 – 00:10:00]
transcribed text, one segment per line
A silent segment produces no page (the following indexes are not shifted,
like the gaps of best_effort in PDF). A failed segment is skipped and
recorded in missing_segments with media_error_strategy="best_effort"
(the default), or fails the document with "fail_fast".
Requirements (checked at conversion time, with a :class:ConversionError
that says how to configure them): a transcriber and the ffmpeg /
ffprobe system binaries.
Memory: the audio is never read in Python; one temporary segment file on
disk at a time. At most media_concurrency audio/video conversions run at
once per event loop.
AudioConverter
Bases: BaseConverter
Transcribe an audio file into one page per segment.
scinr.newton.converters.video
converters/video.py — video files to text: transcription plus described frames.
Same segments as the audio converter (one page per media_segment_seconds,
with start_ms / end_ms). Each page holds:
- the time header and the transcription of the segment (when the video has an audio track), and
-
one block per sampled frame, described by the
vision_llm::…description…
Frames are sampled uniformly at video_frames_per_minute (0 =
transcription only); a frame identical to the previous one is skipped. Each
frame that gets a description:
- is described with the segment's transcript as context (
framemode,Nonewhen the segment has none: no transcriber, a failed or empty transcription — decision D6); - is stored with its
time_msthrough :func:~scinr.newton.converters.image_store.store_frame, inside the same call that describes it, when the :func:image_sinkcontext has theframesswitch (store_video_frames) on — streamed from disk (store_image_file), with thewidth/heightread from the JPEG header, without decoding; a skipped (identical) frame is never stored; and - is deleted from disk right after its turn, whatever the outcome.
A storage failure (:class:~scinr.newton.exceptions.ImageStorageError) fails
the video, whatever the media_error_strategy (D5).
Requirements: ffmpeg / ffprobe; a transcriber when the video has
audio; a vision_llm for the frames (without it the frames are skipped
with a warning). With neither transcription nor frames available the
conversion fails.
Failures follow media_error_strategy: a failed transcription is recorded
per segment in missing_segments, a failed frame per image in
missing_images ((page_index, frame_index)). When ffmpeg cannot
extract the frames of a segment, every frame planned for it is recorded in
missing_images.
Memory: the video is never opened in Python. The frames of one segment are on
disk at a time, already scaled to image_max_side_px; they pass through
memory one by one (or as many as the LLM semaphore lets describe at once),
and each is uploaded from disk inside its own turn — never all at once. The
segment's transcript is just text (a few KB for 5 minutes), shared between
the segment's description calls.
VideoConverter
Bases: BaseConverter
Transcribe a video and describe sampled frames, one page per segment.
convert
async
Convert source.
Raises
FileNotFoundError
If source does not exist.
ConversionError
Missing ffmpeg; audio track without transcriber; nothing
to extract (no audio and no usable frames); longer than
max_media_duration_seconds; or a failure with
media_error_strategy="fail_fast".
scinr.newton.converters.media_common
Shared pieces of the audio and video converters.
Both cut the medium into segments of media_segment_seconds with
ffmpeg (one page per segment, start_ms / end_ms from the cut, not
from the model) and process the segments in sequence: at most one
temporary segment file (or the frames of one segment) exists on disk at a
time, and the medium is never read in Python.
check_duration
Fail before spending anything when the medium exceeds max_media_duration_seconds.
iter_segments
iter_segments(
duration_ms: int,
segment_seconds: int,
min_segment_seconds: int = 0,
) -> Iterator[Segment]
Consecutive segments covering [0, duration_ms); the last one ends at the duration.
When the last segment would be shorter than min_segment_seconds, the cut
before it moves earlier, to a whole second, so that it lasts at least that
long: 300.05 s in segments of 300 s gives [0, 290 s) + [290 s, 300.05 s).
No segment is ever longer than segment_seconds (provider request limits).
min_segment_seconds is at most half of segment_seconds (configure
enforces it), so the shortened segment keeps at least half its length.
media_semaphore
Semaphore bounding the audio and video conversions on the running loop.
time_header
Header of a segment page: [00:05:00 – 00:10:00].
transcribe_segment
async
transcribe_segment(
*,
binaries: Binaries,
transcriber,
source: Path,
segment: Segment,
workdir: Path,
language: str | None,
) -> list[TranscriptCue]
Cut segment to a temporary FLAC, transcribe it, delete it (also on failure).
Returns the segment's :class:TranscriptCue list (absolute times); the
page text comes from those cues, one per line, as :func:transcript_text
does today.
transcript_cues
The transcribed sentences of segment as cues with absolute times.
The transcriber's times are relative to the segment file: they are shifted
by segment.start_ms and clipped to [segment.start_ms, segment.end_ms].
A transcriber without timestamps returns a single segment with
end_ms <= start_ms (OpenAICompatibleTranscriber's
response_format=json fallback); it becomes a single cue with the whole
segment range — times are never invented. Cues without text are discarded,
same as :func:transcript_text.
Vision and Embedded-Image Enrichment
Descriptions of embedded images (PDF, DOCX, PPTX), standalone images and video
frames with the configured vision_llm.
scinr.newton.converters.vision
Image preparation and description with the configured vision_llm.
Memory: decoding is the expensive step (a 12 MP photo is ~36 MB of pixels,
whatever its file size), so :func:prepare_for_vision reads, decodes and
downscales at most image_decode_concurrency images at a time per event
loop (default 1), whatever the number of pages, documents
(parallel_docs) or LLM calls in flight. What waits for
the model is only the downscaled JPEG (image_max_side_px, a few hundred
KB) and its base64; the number of calls in flight is bounded by the global
LLM semaphore (llm_concurrency).
The largest single decode is bounded by Pillow's Image.MAX_IMAGE_PIXELS
(about 89 MP): a larger image fails as a decompression bomb. JPEGs are
decoded already reduced (draft), so only lossless formats (PNG, TIFF,
WebP lossless) pay their full size.
describe_image
async
Describe the image data with vision_llm and return Markdown text.
The image is downscaled to image_max_side_px and sent as a JPEG in a
standard LangChain image block (translated by each provider integration:
OpenAI-compatible, Bedrock Converse, Ollama…). The call runs under the
global LLM semaphore with the usual retries on throttling.
Parameters
image:
Encoded image bytes (any format Pillow can read), or a callable
that returns them: a loader is only called once it is this image's
turn to be decoded, so the bytes of images still waiting are not
read.
mode:
"embedded", "standalone" or "frame" (see :mod:vision_prompts).
context:
embedded mode: the page markdown; frame mode: the transcript
of the video segment the frame belongs to (None when the segment
has none). Always truncated to :data:CONTEXT_MAX_CHARS.
Returns
str The description; an empty string means the image carries no information.
Raises
ConfigurationError
No vision_llm configured.
ConversionError
The image cannot be read.
image_bytes_lane
The lane that bounds the images read and decoded at once per event loop.
Same semaphore :func:prepare_for_vision uses (_decode_semaphores,
sized image_decode_concurrency per event loop): anything that holds
one image's original bytes in memory — decoding, or re-reading them to
store the described original (converters/image_store.store_embedded)
— acquires a slot here, so the number of originals in memory at a time
has the same cap as the images being decoded, whatever the
llm_concurrency calls in flight.
image_size
Return (width, height) of the encoded image data, reading only its header.
data may be a :class:~pathlib.Path: then only the header is read from
disk (a stored video frame never passes through memory for this).
prepare_for_vision
async
Read (when image is a loader), decode and downscale one image.
Runs under a per-loop semaphore of size image_decode_concurrency
(default 1), so the encoded bytes and decoded pixels of at most that
many images are in memory at a time; the bytes are dropped as soon as the
downscaled JPEG exists.
prepare_image
Return data as a JPEG whose longer side is at most max_side pixels.
Applies the EXIF orientation, converts to RGB (flattening transparency on
white) and downscales with :meth:PIL.Image.Image.thumbnail. Synchronous
and CPU-bound: call it through :func:asyncio.to_thread.
scinr.newton.converters.vision_prompts
Prompts for the vision model (vision_llm).
Three modes:
embedded: an image inside a PDF, DOCX or PPTX page. The page text is passed as context.standalone: an image file (.jpg,.png…) that is the whole document.frame: a still frame sampled from a video.
All three answer in Markdown without preamble, in the language of the visible text or of the context, never identify real people by their appearance, and return an empty string when the image carries no information.
scinr.newton.converters.enrichment
Embedded-image enrichment of Stage 0.
Describes the images of each :class:~converters.base.IntermediatePage with
the vision_llm and writes the description into the page markdown as::
<image index="2">
…description…
</image>
The block replaces the image reference  when the page has one,
or goes at the end of the page otherwise. Only images that still hold bytes
and have no description are treated; every treated image is released
(base64 and loader dropped), whatever the outcome.
Called only when :func:~scinr.newton.config.embedded_images_enabled is
True (by converters/main.py after conversion, and by the PDF converter
chunk by chunk).
Memory: one page at a time. Inside a page the filter reads each image's
bytes one at a time and drops them before the next; the images to describe
are then read and decoded one at a time (per event loop, see
:func:~converters.vision.prepare_for_vision), and only their downscaled
JPEGs (image_max_side_px) wait for the model, at most
llm_concurrency calls in flight.
EnrichmentState
dataclass
Per-document state shared by every page (and every PDF chunk).
Attributes
seen: SHA-1 of the images already seen in the document: a repeated image (a logo on every page) is described only the first time.
enrich_pages
async
Describe the embedded images of pages, in place.
Returns the (page_index, image_index) pairs that failed and were
skipped (media_error_strategy="best_effort").
Raises
ConversionError
An image failed and media_error_strategy is "fail_fast".
ImageStorageError
A described image could not be stored. Always re-raised, whatever
the media_error_strategy (D5: a described image is never kept
without its original).