Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ else on request, so a host pays only for what it uses.
| --- | --- | --- |
| `cortex` (default) | `cortex`, `registry`, `config`, `registry::binder` | `CortexEngine` over both wires; `list_engines`, `build_engine`, `EngineCredential`, cached guarded `EngineBinder`, `MemoryConfig` (implies `safety`) |
| `documents` | `documents` | Format sniffing and conversion to markdown, producing `StoreItem::Document` |
| `documents-office` | `documents::OfficeConverter` | PDF, DOCX and PPTX to markdown; XLSX is temporarily unsupported (implies `documents`) |
| `documents-office` | `documents::OfficeConverter` | PDF, DOCX, PPTX and XLSX to markdown (implies `documents`) |
| `brain` | `brain` | Files into `tinymemory_tools::BrainDocument`s, by the source type their format implies (implies `documents`) |
| `sources` | `sources` | Folder, file and conversation readers (implies `documents`) |
| `sources-network` | `sources::fetch` and the network readers | GitHub, RSS and web-page readers and `fetch_url`, behind the SSRF guard (implies `sources`) |
Expand Down
17 changes: 11 additions & 6 deletions crates/tinymemory-integrations/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,15 @@ futures = { version = "0.3", optional = true }
sha2 = { version = "0.11", optional = true }

# --- documents-office ---
# Text out of PDFs, Word documents and PowerPoint decks. These readers are
# pure Rust with no system libraries. Spreadsheet import is temporarily
# disabled until a safe Calamine release is published.
# Text out of the formats people actually drop into memory — a contract PDF, a
# spec `.docx`, a pricing `.xlsx`, a deck. All pure Rust with no system
# libraries. `pdf-extract` reads a PDF's text layer. `zip` + `quick-xml` are
# the whole of `.docx` and `.pptx`, which are zip archives of XML. `.xlsx` is
# not — shared-string tables and cell typing make hand-parsing it a liability —
# so `calamine` reads that one. `zip` and `quick-xml` are the versions
# `calamine` already links, so the graph carries one copy of each.
pdf-extract = { version = "0.12", optional = true }
calamine = { version = "0.38", optional = true }
quick-xml = { version = "0.42", optional = true }
zip = { version = "9", default-features = false, features = ["deflate"], optional = true }

Expand Down Expand Up @@ -116,10 +121,10 @@ cortex = ["dep:async-trait", "dep:serde", "dep:serde_json", "dep:reqwest", "dep:
# `documents`: format sniffing and conversion to markdown, emitting
# `StoreItem::Document`. Does no I/O.
documents = ["dep:async-trait", "dep:serde", "dep:serde_json", "dep:thiserror"]
# `documents::OfficeConverter`: PDF, DOCX and PPTX to markdown, for a
# `documents::OfficeConverter`: PDF, DOCX, PPTX and XLSX to markdown, for a
# host to prepend to its `ConverterChain`. Off by default because a PDF parser
# is real weight. XLSX is recognized but temporarily unsupported.
documents-office = ["documents", "dep:pdf-extract", "dep:quick-xml", "dep:zip"]
# and a spreadsheet reader are real weight.
documents-office = ["documents", "dep:pdf-extract", "dep:calamine", "dep:quick-xml", "dep:zip"]
# `brain`: converting raw files into `tinymemory_tools::BrainDocument`s
# placed under the source type their format implies.
brain = ["documents", "dep:tinymemory-tools"]
Expand Down
4 changes: 2 additions & 2 deletions crates/tinymemory-integrations/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ wants one integration enables one feature and links nothing else.
| --- | --- | --- | --- |
| `cortex`, `registry`, `config` | `cortex` (default) | `CortexEngine` over two wires (`cortexdb`, `tinyhumans`); `list_engines`, `build_engine`, `EngineCredential`, cached guarded `EngineBinder`; `MemoryConfig` | [`src/cortex/README.md`](src/cortex/README.md) |
| `documents` | `documents` | Format sniffing and conversion to markdown, producing `StoreItem::Document`. No I/O. | [`src/documents/README.md`](src/documents/README.md) |
| `documents::OfficeConverter` | `documents-office` | PDF, DOCX and PPTX to markdown; XLSX is temporarily unsupported | (same) |
| `documents::OfficeConverter` | `documents-office` | PDF, DOCX, PPTX and XLSX to markdown, in process | (same) |
| `sources` | `sources` | Readers and host source types, target/layout validation, sync state, batch storage and placement jobs; `collect_items`. Links no HTTP client. | [`src/sources/README.md`](src/sources/README.md) |
| Source schemas | `schema` | Optional JSON Schema derives for the source configuration and reader types | (same) |
| `sources::fetch`, GitHub, RSS and web-page readers | `sources-network` | The network readers and `fetch_url`, all behind the SSRF guard | (same) |
Expand All @@ -38,7 +38,7 @@ already needs):
| --- | --- |
| `cortex` | `reqwest` (rustls TLS, streaming bodies), `tokio` (`time` only), `futures`, `sha2`, `tinyredact` (through mandatory binder safety) |
| `documents` | nothing beyond the small set above |
| `documents-office` | `pdf-extract`, `quick-xml`, `zip` (all pure Rust, no system libraries) |
| `documents-office` | `pdf-extract`, `calamine`, `quick-xml`, `zip` (all pure Rust, no system libraries) |
| `brain` | `tinymemory-tools` (for `BrainDocument`; it adds only `futures`, `chrono`, `log`) |
| `sources` | `tinymemory-tools` (layout and background-job types; no Tokio), `url`, `regex`, `walkdir`, `chrono`, `log`, `tracing` |
| `schema` | `schemars` |
Expand Down
32 changes: 14 additions & 18 deletions crates/tinymemory-integrations/src/documents/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ caller's to state.
| `ConvertedDocument` | markdown plus title, source format, language, and converter metadata |
| `DocumentConverter` | the conversion seam — object-safe and async |
| `NativeConverter` | markdown, text, HTML and code, with no dependencies |
| `OfficeConverter` | PDF, DOCX and PPTX, in-process (feature `documents-office`); XLSX is temporarily unsupported |
| `OfficeConverter` | PDF, DOCX, PPTX and XLSX, in-process (feature `documents-office`) |
| `ConverterChain` | converters in priority order; first claim wins |
| `document_item` / `converted_item` | the conversion wrapped as a `StoreItem::Document` |
| `markdown_from_text` | the synchronous core, for callers that already hold text |
Expand All @@ -67,23 +67,18 @@ conversion is a trait a host binds:
let chain = ConverterChain::default().prepend(Box::new(MyPdfConverter));
```

The `documents-office` feature ships one such binding, `OfficeConverter`: PDF
(text layer only — a scanned PDF is refused as having no text; pages are
extracted one by one, normalized on their own and joined by `PAGE_BREAK`, a
form feed, so a reader can number them), DOCX and PPTX (slides in numeric
order), all pure Rust. It refuses hostile archive input rather than allocating
for it when declared uncompressed sizes exceed `MAX_DECOMPRESSED_BYTES`
(64 MiB). Unreadable documents are `Error::Invalid`. Parsing is CPU-bound; a
host on a shared executor calls `OfficeConverter::convert_blocking` from its
The `documents-office` feature ships one such binding, `OfficeConverter`: PDF (text
layer only — a scanned PDF is refused as having no text; pages are extracted
one by one, normalized on their own and joined by `PAGE_BREAK`, a form feed,
so a reader can number them), DOCX, PPTX (slides
in numeric order) and XLSX (one `sheet | cell | cell` line per row), all pure
Rust. It refuses hostile input rather than allocating for it: an archive whose
declared uncompressed size exceeds `MAX_DECOMPRESSED_BYTES` (64 MiB), and a
spreadsheet whose dense used range exceeds `MAX_SPREADSHEET_DENSE_CELLS`
(1,000,000). Unreadable documents are `Error::Invalid`. Parsing is CPU-bound;
a host on a shared executor calls `OfficeConverter::convert_blocking` from its
own blocking pool.

XLSX and macro-enabled XLSM remain recognizable formats, but the built-in
spreadsheet reader is temporarily disabled while TinyMemory waits for a safe
Calamine release. `OfficeConverter::supports(DocumentFormat::Xlsx)` is false;
calling it directly returns `Error::UnsupportedFormat` with a restoration
message before opening the workbook. A host can still bind its own spreadsheet
converter. CSV and other plain text continue through `NativeConverter`.

A zip upload is told apart by its part names (`word/`, `xl/`, `ppt/`) read
from the central directory, so an `.xlsx` sent as `application/octet-stream`
still sniffs as XLSX. When the parts say nothing, an Office label refines the
Expand All @@ -108,5 +103,6 @@ success.

- `documents` — this module; depends only on `async-trait`, `serde`,
`serde_json` and `thiserror`.
- `documents-office` — `OfficeConverter` (`pdf-extract`, `zip`, `quick-xml`).
Off by default; it links a PDF parser a text-only host has no use for.
- `documents-office` — `OfficeConverter` (`pdf-extract`, `calamine`, `zip`,
`quick-xml`). Off by default; it links a PDF parser and a spreadsheet reader
a text-only host has no use for.
4 changes: 0 additions & 4 deletions crates/tinymemory-integrations/src/documents/convert/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -246,10 +246,6 @@ impl DocumentConverter for ConverterChain {
let format = document.format();
match self.converters.iter().find(|c| c.supports(format)) {
Some(converter) => converter.convert(document).await,
None if format == DocumentFormat::Xlsx => Err(Error::UnsupportedFormat(
"spreadsheet import is temporarily disabled until a safe reader release is available"
.to_string(),
)),
None => Err(Error::UnsupportedFormat(format!(
"no converter handles {format}; this build converts {}",
describe(&self.supported_formats())
Expand Down
5 changes: 2 additions & 3 deletions crates/tinymemory-integrations/src/documents/format/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,8 @@ pub enum DocumentFormat {
Pdf,
/// Office Open XML word processing (`.docx`). Needs a real extractor.
Docx,
/// Office Open XML spreadsheet (`.xlsx`, macro-enabled `.xlsm`). The
/// format remains recognizable, though TinyMemory's built-in reader is
/// temporarily disabled; a host may bind its own converter.
/// Office Open XML spreadsheet (`.xlsx`, macro-enabled `.xlsm`). Needs a
/// real extractor.
Xlsx,
/// Office Open XML presentation (`.pptx`). Needs a real extractor.
Pptx,
Expand Down
5 changes: 2 additions & 3 deletions crates/tinymemory-integrations/src/documents/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,8 @@
//! 2. **Turn it into markdown.** [`DocumentConverter`] is the seam;
//! [`NativeConverter`] covers markdown, plain text, HTML and code with no
//! dependencies; a host binds its own for PDF and Office documents, or
//! prepends `OfficeConverter` (feature `documents-office`) for PDF, DOCX and
//! PPTX. XLSX is still recognized but the built-in reader is temporarily
//! disabled; a host may provide its own converter.
//! prepends `OfficeConverter` (feature `documents-office`) for PDF, DOCX, PPTX and
//! XLSX.
//! 3. **Wrap it as an item.** [`document_item`] produces a
//! `StoreItem::Document` with the caller's
//! [`MemoryMeta`](tinymemory_api::MemoryMeta), filling `language` from the
Expand Down
52 changes: 35 additions & 17 deletions crates/tinymemory-integrations/src/documents/office/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
//!
//! [`crate::documents::convert::NativeConverter`] handles what is already text. This is
//! the converter for the formats people actually drop into memory that are not
//! — a contract PDF, a spec `.docx`, a deck — so a host
//! — a contract PDF, a spec `.docx`, a pricing `.xlsx`, a deck — so a host
//! does not have to bind an extractor of its own for them:
//!
//! ```
Expand All @@ -16,9 +16,12 @@
//! | PDF | `pdf-extract`, text layer only | each page's text, whitespace-normalized, pages joined by [`PAGE_BREAK`] |
//! | DOCX | `zip` + `quick-xml` over `word/document.xml` | one paragraph per `w:p` |
//! | PPTX | `zip` + `quick-xml` over `ppt/slides/slideN.xml` | slides in numeric order, one paragraph per `a:p` |
//! XLSX remains recognizable as a format but is temporarily unsupported while
//! the project waits for a safe Calamine release. Direct conversion returns a
//! helpful [`Error::UnsupportedFormat`] without opening the workbook.
//! | XLSX | `calamine` | one `sheet \| cell \| cell` line per non-empty row |
//!
//! A spreadsheet is flattened rather than rebuilt as a table because that is
//! what recall can use: a chunk reading `Q3 | EMEA | 412000` answers a question
//! about EMEA revenue, and the same data as aligned columns does not survive
//! chunking.
//!
//! ## Hostile input
//!
Expand All @@ -29,6 +32,18 @@
//! before any entry is read — and each entry read is capped as well, so an
//! archive that lies about its sizes cannot force the allocation either.
//!
//! A spreadsheet has one more: calamine materializes the dense bounding box of
//! a sheet's cells, so a tiny workbook with one cell at `A1` and one at
//! `XFD1048576` would allocate ~17 billion cells. The cells are scanned
//! sparsely first and a sheet whose box exceeds
//! [`MAX_SPREADSHEET_DENSE_CELLS`] is refused before that happens. The same
//! scan sums each cell's text, counting every reference to a shared string,
//! because reading a sheet copies the string into each cell: a workbook past
//! [`MAX_SPREADSHEET_TEXT_BYTES`] is refused too. And calamine reserves room
//! for the shared-string count a workbook declares while it opens it, so a
//! table declaring more entries than a sheet could hold cells is refused
//! before calamine sees it.
//!
//! `pdf-extract` panics on some malformed documents rather than erroring; the
//! panic is caught and reported as an unreadable document.
//!
Expand All @@ -43,6 +58,7 @@
mod normalize;
mod ooxml;
mod pdf;
mod xlsx;

use async_trait::async_trait;

Expand All @@ -57,15 +73,19 @@ use crate::documents::format::DocumentFormat;
/// before it is refused as a likely zip bomb. See the module docs.
pub const MAX_DECOMPRESSED_BYTES: u64 = 64 * 1024 * 1024;

/// The historical spreadsheet used-range cap, retained for API compatibility.
///
/// The built-in spreadsheet reader is temporarily disabled, so the limit is
/// not currently applied by [`OfficeConverter`].
/// The most cells a spreadsheet's dense used range may span before it is
/// refused. The used range of a real spreadsheet is a small fraction of the
/// grid, so this only bites hostile input; see the module docs.
pub const MAX_SPREADSHEET_DENSE_CELLS: usize = 1_000_000;

/// Converts PDF, DOCX and PPTX documents to markdown, in-process.
/// The most cell text, in bytes, a spreadsheet may expand to across all its
/// sheets before it is refused. Every reference to a shared string counts, as
/// reading the sheet copies the string into each cell.
pub const MAX_SPREADSHEET_TEXT_BYTES: u64 = 64 * 1024 * 1024;

/// Converts PDF, DOCX, PPTX and XLSX documents to markdown, in-process.
///
/// Claims exactly those three formats, so it composes with
/// Claims exactly those four formats, so it composes with
/// [`crate::documents::convert::NativeConverter`] in a [`crate::documents::convert::ConverterChain`]
/// without shadowing it. A document whose text cannot be read — malformed,
/// over a cap, or a scanned PDF with no text layer — is [`Error::Invalid`]
Expand All @@ -92,12 +112,7 @@ impl OfficeConverter {
DocumentFormat::Pdf => paged(&pdf::extract(bytes)?),
DocumentFormat::Docx => normalize::normalize(&ooxml::docx(bytes)?),
DocumentFormat::Pptx => normalize::normalize(&ooxml::pptx(bytes)?),
DocumentFormat::Xlsx => {
return Err(Error::UnsupportedFormat(
"spreadsheet import is temporarily disabled until a safe reader release is available"
.to_string(),
));
}
DocumentFormat::Xlsx => normalize::normalize(&xlsx::extract(bytes)?),
other => {
return Err(Error::UnsupportedFormat(format!(
"the office converter does not handle {other}"
Expand Down Expand Up @@ -132,7 +147,10 @@ impl DocumentConverter for OfficeConverter {
fn supports(&self, format: DocumentFormat) -> bool {
matches!(
format,
DocumentFormat::Pdf | DocumentFormat::Docx | DocumentFormat::Pptx
DocumentFormat::Pdf
| DocumentFormat::Docx
| DocumentFormat::Xlsx
| DocumentFormat::Pptx
)
}

Expand Down
Loading
Loading