AI Build Log 1

November 28, 2026

Welcome to the first AI Build Log post. This series documents the ongoing development of my AI-powered knowledge retrieval system, including new features, technical challenges, implementation decisions and troubleshooting.

On 14 November 2026, I undertook a substantial overhaul of Mun’s document ingestion pipeline, transforming an EPUB-oriented workflow into a more versatile Universal Document Processor. The objective was to accommodate different document formats while improving extraction accuracy, preserving structured information and making the entire ingestion process easier to manage. Rather than replacing the existing system, I retained the working components and extended their capabilities.

The article follows the development process across six areas:

  1. Original pipeline and planning: Auditing the existing system and designing the replacement workflow.

  2. Spreadsheet processing: Structured extraction, region detection, chunking and retrieval testing.

  3. PDF processing: Native extraction, table preservation and automatic OCR.

  4. Image indexing: PDF illustration detection, caption embeddings and image retrieval.

  5. Production integration: Ingestion Management, ChromaDB integration, CSV exports and documentation.

  6. Testing and results: Validation, performance, limitations and future improvements.

Along the way, I’ve included code examples, Linux commands, processing logs, technical diagrams and before-and-after comparisons to demonstrate how the system works.

This is a technical record of what I built, the problems encountered and the decisions made along the way. Strap in, it’s a big one!

ORIGINAL INGESTION LIMITATIONS

The original application was a Flask-based uploader backed by a document extraction function, a text chunker, LM Studio embeddings and the mun_knowledge collection in ChromaDB. Its straightforward approach worked for text-heavy EPUBs, Markdown and similar material: extract text, split it into chunks, embed those chunks, preserve the source and store the records.

The limits became clearer with other formats. The application already had some PDF and spreadsheet parsing code, but the accepted-upload configuration did not expose all of it. The PDF conversion widget reconstructed a text-oriented EPUB; that was useful for readable prose but did not preserve the original PDF’s tables and illustrations reliably. A CSV could be accepted as text without interpreting the columns, and Excel extraction could collapse empty cells, removing the spatial information that gives a worksheet meaning.

The generic splitter used 2,400-character chunks with 300 characters of overlap. This was a reasonable default for prose, but row boundaries, page locations and formula references do not line up neatly with character counts. A technically successful extraction could therefore still produce mediocre retrieval material.

The early audit also identified a maintenance issue: document conversion and ingestion could share the same job state, making cancellation and rollback ownership harder to reason about. Rather than expanding the converter, I decided to make ingestion the primary workflow and leave format conversion out of the final interface.

READ-ONLY SUITABILITY ANALYSIS BEFOREI NGESTION

The first practical module was mun_analyze.py, which examines a document without changing the knowledge library. A browser endpoint accepts a temporary upload, runs a bounded analysis and returns a report. This became the expandable Analyse document suitability section in the ingestion interface.

The analysis is intentionally format-dependent. For PDFs, it samples text coverage, likely table locations, images and low-text pages. For EPUBs, it examines archive sections and embedded image counts. For CSVs, it samples rows and likely headers. For workbooks, it reports worksheets, dimensions and, in the extended analyser, formulas, merged cells and other layout characteristics.

An example workbook report contained this recommendation:

{
  "filename": "test1.xlsx",
  "format": "xlsx",
  "recommendation": "xlsx_structured",
  "worksheets": 3,
  "analysis_mode": "read_only_sampled",
  "temporary_analysis": true
}

The key word is sampled. It would be wrong for an analyser to imply it had inspected every page and every formula merely because it produced a recommendation. This module reports its scope and limitations and does not index anything.

On the live host, the analysis endpoint can also be tested without the browser:

curl -fsS \
  -F "file=@$HOME/Downloads/test1.xlsx" \
  http://192.168.1.111:1237/analyze \
  | python3 -m json.tool

This call reports suitability. It is not an ingestion operation, so it does not add records to ChromaDB.

STRUCTURED SPREADSHEETS: MANY TESTS

The Excel test documents were a useful reality check. They contained calculations, formulas, merged headers and observations arranged side by side. A worksheet could contain several distinct problems even when all the cells sat inside the same overall populated rectangle.

I developed mun_extract_xlsx.py as a read-only structured extractor. Its initial preview retained sheet names, cell addresses, formulas and cached results. A follow-up region detector examined both row and column gaps to identify disconnected blocks, while retaining the original cell coordinates. For one workbook, test3.xlsx, the old single region A1:N36 became three spatial regions:

Worksheet: Solution
A1:C31  - observations: number, repairs, age
E1:F30  - regression calculations
L1:N36 - hypothesis testing

The classification of these regions is a useful heuristic, not a claim that the software understands every spreadsheet’s semantics. A pair of adjacent tables with no blank separator can still be grouped together, and a workbook with unusual merged headers remains challenging.

Cell preservation was a stronger, testable invariant. For the three workbooks used in the evaluation, source and extracted-cell counts matched:

WorkbookPopulated cells checkedInitial detected regions
test1.xlsx7627 across three worksheets
test2.xlsx2095
test3.xlsx1563
Total1,12715

Before/after photo opportunity B: Include an archived screenshot of the original one-region Solution preview beside the later three-region preview. A close crop showing the A1:C31, E1:F30 and L1:N36 boundaries will demonstrate the improvement more clearly than another long paragraph.

Formulas and cached results

Excel formula cells need special treatment. The extractor retains expressions such as:

Solution!F4 = COVARIANCE.P(C2:C31,B2:B31)
Cached result: 1040.946311111111
Status: unverified; not recalculated

The cached result is what the workbook stored, not proof that the formula has recently been recalculated or that the calculation itself is correct. Mun therefore labels these numbers appropriately and does not pretend to be an Excel calculation engine.

CHUNK CONTEXT AND FORMULAE DEPENDENCIES

The next step was to create RAG-ready chunks that retained enough context to make a retrieved result understandable on its own. mun_xlsx_chunks.py produced worksheet-labelled text with row and cell references, plus contextual column headings on continuation chunks. A preservation check verified that populated cells were represented exactly once as actual data records.

The calculation area in test3.xlsx contained formulas referring to B2:B31 and C2:C31 in the observation region. The preview exposed that relationship explicitly:

Worksheet: Solution
Region: E1:F30
Formula-linked regions: Solution!A1:C31

This allows a future retrieval strategy to follow a calculation back to its inputs. It is also an example of why vector search alone is not a substitute for structured data processing: embeddings find relevant areas, whereas exact numbers, formulas and arithmetic should be grounded in the source values.

A production caveat: the XLSX import that was later enabled retained region labels and formulas in its extracted text, but still passed that text through the main application’s generic 2,400-character splitter. The richer region-aware retrieval remained a tested technique, not a fully deployed replacement for all production spreadsheet retrieval behaviour. This is an area for future refinement, not an invisible success claim.

TESTING RETRIEVAL

Before enabling spreadsheet uploads in production, I used an isolated temporary ChromaDB store and Mun’s existing Nomic embedding model. The trial compared ordinary spreadsheet chunks with a region-aware arrangement incorporating region overviews and consolidation of tiny continuation chunks.

The three-workbook benchmark used 12 expected-region questions and six deliberately out-of-scope questions. The measured ranking results were:

MetricBaselineRegion-aware
Correct region ranked first6/128/12
Correct region in top three8/1210/12

The result was encouraging, but not perfect. A question mentioning test1.xlsx could still rank similar content from test3.xlsx ahead of the named file. That illustrates a real problem: semantic similarity does not automatically obey an explicit document restriction. Source-aware filtering remains a sensible retrieval refinement.

I also compared ChromaDB distances with out-of-scope queries. This helped reveal which results might be excluded by a threshold, but the distances are not confidence percentages. Twelve positive queries are far too few to choose a universal production cutoff, and six negative probes do not establish robust out-of-scope rejection.

The important outcome was practical: structured chunks could be embedded and retrieved, the underlying cells remained accounted for, and the production collections were not touched by the benchmark.

INCORPORATING XLSX AND CSV INTO INGESTION

Once the extraction previews were stable, I integrated structured formats into mun_ingest.py using a separate module, mun_structured_ingest.py. It reused the main system’s upload, embedding, source-retention, job progress and ChromaDB storage path rather than creating a disconnected spreadsheet importer.

The integration applied size limits and rejected truncated workbook scans rather than silently embedding an incomplete worksheet. A live import of test3.xlsx then completed with this sequence:

Extracted 5,791 characters
Created 4 chunks
Original saved: .../Spreadsheets/test3.xlsx
Embedded batch 1/1 (4/4 chunks, 0.6s)
Embedding dimensions: 768
Stored records 1-4
Done in 0.9s

The numbers came from that actual job. They demonstrate a complete path from Excel upload to four vector records, not just a successful local parse. CSV ingestion uses its own structured extraction, which also supports legitimate one-column data such as a FolderName list.

For service administration, the ingestion process continues to be a systemd service. These are read-only examples of how I check its state and recent messages:

ssh mun 'systemctl is-active mun-ingest mun-web mun-chroma'
ssh mun 'journalctl -u mun-ingest -n 40 --no-pager'

The first checks whether the main ingestion, retrieval and database services are active. The second prints the most recent ingestion-service journal entries without restarting anything.

NATIVE PDF EXTRACTION

The original PDF converter was removed from the critical path. Native PDF extraction now uses PyMuPDF to inspect pages and create records with page and content-type metadata. Tables can be detected separately from surrounding text and represented in row order with headers where detected.

A simplified excerpt of the approach, reflecting the real mun_pdf_native.py extractor, is:

import pymupdf

with pymupdf.open("technical-manual.pdf") as doc:
    for page_number, page in enumerate(doc, start=1):
        text = page.get_text("text")
        tables = page.find_tables()
        for table_number, table in enumerate(tables.tables, start=1):
            rows = table.extract()
            # Create a page-labelled table record from rows.

The loop above is an illustrative excerpt, not a complete ingestion script: production code also guards table size, handles extraction failures, separates overlapping text and tracks the job’s metadata and cancellation state.

 

The two large source PDFs used for sampled assessment demonstrated why format-aware handling matters:

PDFPagesSampled pagesLow-text sampled pagesTable records in sampled native preview
test4.pdf1,1301209
test6.pdf2301240

These are sample results, not claims about every page of each book.

A short two-page PDF was then ingested into production. The resulting records were verified in ChromaDB:

Record 1: pdf_page=1; pdf_kind=text
Record 2: pdf_page=1; pdf_kind=table; pdf_table=1
Record 3: pdf_page=2; pdf_kind=text
Chunk strategy: pdf_native_v1

Before/after photo opportunity C: Place an old PDF-to-EPUB conversion screenshot next to a current native PDF ingestion log. A crop showing pdf_page, pdf_kind and pdf_table in the metadata verification provides concrete evidence of what direct ingestion preserves.

The native PDF extractor also has a stand-alone read-only preview mode, useful during troubleshooting:

ssh mun '/home/eor/AI/venv/bin/python \
  /home/eor/AI/scripts/mun_pdf_native.py \
  --preview "/path/to/manual.pdf" --pages 12'
AUTOMATIC OCR AND CONDITIONAL EXECUTION

A low-text page is not necessarily a scanned page. It could be a cover, an illustration, a vector drawing or a genuinely blank page. I therefore introduced an OCR triage module that examines both native-text availability and a low-resolution estimate of visible marks.

The production decision was to run OCR automatically, without making manual review part of routine ingestion. If a page has sufficient native text, Mun uses it. If the page has low text but visible content, Mun attempts OCR. Apparently blank pages can be skipped, and failures are reported in the job output rather than silently concealed.

The implementation uses the existing Tesseract installation, with English text recognition available. The code includes a bounded timeout and a document-level OCR page limit. The production importer caps automatic OCR at 400 pages per document, preventing unexpectedly large OCR jobs from proceeding without a bound.

The OCR fixture was a scanned image of a page containing these lines:

MUN OCR VALIDATION
The sample contains 25 concrete blocks.
Each block weighs 18 kilograms.

Tesseract recovered the wording and numbers correctly. A subsequent live upload completed in 1.1 seconds:

Automatic OCR page 1/1
Automatic OCR: attempted=1; succeeded=1;
               unresolved=0; likely blank=0
Stored records 1-1

OCR-derived records retain their page source and an unverified status. That distinction is particularly important for technical documents: successful recognition of a test fixture does not guarantee correct reading of equations, small print or unusual layouts in every real book.

ON DEMAND PDF DELIVERY

Mun already maintained an EPUB illustration index. The PDF extension reused the same mun_images collection and the same Nomic text embedding model. Eligible PDF figures are located using their raster image placement and nearby captions. The record stores descriptive text and a locator containing the original PDF’s page, image reference and bounding rectangle.

A real test image carried this caption:

Figure 1. Diagram of an industrial pump assembly and feed pipe.

The matching mun_images metadata included source_format=pdf, pdf_page=1, a PDF image reference and a pdf_rect bounding box. The retrieval API used this information to render the relevant area from the original PDF rather than relying on a permanent extracted duplicate.

The full chain was verified with a read-only check of ChromaDB and the image endpoint:

Matching images: 1
HTTP status: 200
Content type: image/png
Image bytes: 5783

This is valuable for storage efficiency, but it is not general visual understanding. The index is caption-based, and uncaptioned raster imagery, complex graphics and vector-only diagrams remain imperfectly covered.

A compact read-only ChromaDB verification resembles the actual test:

import chromadb

client = chromadb.HttpClient(host="127.0.0.1", port=8000)
images = client.get_collection("mun_images")
result = images.get(
    where={"source_hash": "<SHA256_OF_ORIGINAL_PDF>"},
    include=["metadatas", "documents"],
)
print("Indexed illustrations:", len(result["ids"]))

The source hash in the example is a placeholder; the command does not modify the collection.

OPERATIONAL SAFEGUARDING

The ingestion system retains its existing operational features: file hashing for duplicates, subject categories, job progress, cancellation checks and cleanup or rollback on supported failure paths. The larger format handlers also impose practical limits. The PDF importer, for example, has a 400 MiB input limit and a 2,000-page limit; the automatic OCR path has its own 400-page cap.

The processing jobs save the original source, extracted text and document metadata to separate repository locations. Text and image indexing are related operations but are not identical transactions: PDF illustration indexing runs after the main text-ingestion commit. This keeps an image-indexing failure from automatically undoing otherwise valid text records, but also means image issues need their own reporting and retry strategy.

For a sysadmin, the useful operational question is not merely did the script run? It is which stage completed, what was committed and what still needs attention? The ingestion terminal output exposes hashes, batch progress, stored-record counts, warnings and completion status so failures can be investigated without guessing.

A safe systemd diagnostic, executed from the desktop, is:

ssh mun '
  systemctl status mun-ingest --no-pager
  journalctl -u mun-ingest --since "30 minutes ago" --no-pager
'

No restart is needed for the command above. Before deployment, installation scripts created timestamped source backups and validated Python syntax; live services were restarted only after the patches passed their checks.

INTERFACE CONSOLIDATION

The browser front end is now titled Ingestion Management, with File Ingestion as the main upload panel. It provides subject categories, document upload and queue controls, expandable suitability analysis, spreadsheet extraction previews, processing logs, storage reporting and the knowledge inventory CSV export.

I removed the standalone Convert PDF to EPUB panel and disabled the conversion-only endpoint. The older implementation was left dormant initially for safety, but it is no longer an active operation in the interface. For ordinary ingestion, PDFs go directly into the native extractor and automatic OCR path as needed.

Before/after photo opportunity D — strongest visual comparison: Use matching browser screenshots of the old converter and the final two-column Ingestion Management screen. Crop them to approximately the same width, showing the main heading and upload area. Include a third smaller crop of the expanded suitability report if space allows.

The admin portal’s Documentation and Help pages were then updated to reflect the actual routes, format support, OCR behaviour and storage/reporting features rather than the obsolete conversion instructions.

EXPORTING DATABASE INVENTORY

The knowledge inventory CSV was expanded to include the fields needed to audit text and illustration coverage. Its header is:

Title,Images (Yes/No),Image Count,Text Chunk Count,
Category,Source Filename,Source Size (bytes),
Processed Size (bytes)

The counts come from the corresponding mun_knowledge and mun_images records. Image Count means indexed illustrations, not every raster or vector object physically found in a source PDF. Text Chunk Count means actual text knowledge records, not a prediction based on document length.

I verified the result against the PDF figure fixture:

mun_pdf_figure_fixture,Yes,1,1,Test Env,mun_pdf_figure_fixture.pdf,388816,75

The existing endpoint can be called directly if I want a local copy of the report:

curl -fsS \
  http://192.168.1.111:1237/export-processed \
  -o "$HOME/Downloads/mun-knowledge-inventory.csv"
RESULTS, BOUNDARIES, REMAINS

By the end of the work, Mun could ingest EPUB and ordinary text, structured XLSX and CSV sources, and native PDF pages containing text and detectable tables. The PDF pipeline included automatic OCR for qualifying low-text pages and image indexing for captioned raster figures. The indexing system continued to use the existing mun_knowledge and mun_images collections, and the admin interface and inventory export reflected the available data.

The deployment was tested in layers: read-only extraction previews, temporary embedding stores, small synthetic documents for page/table and OCR validation, live ChromaDB metadata checks and an HTTP image retrieval test. That provided useful evidence without repeatedly re-running expensive whole-book imports.

There are still boundaries worth remembering. Spreadsheet regions are detected heuristically, and production spreadsheet chunks are not yet guaranteed to align with every logical region. OCR can misread technical content. Caption-based image indexing cannot reliably discover every uncaptioned or vector-only diagram. The retrieval API can be improved further with stronger source-specific filters and dependency-aware spreadsheet context.

None of these limitations makes the pipeline unusable; they define the next sensible engineering tasks. The substantial difference is that source structure, extraction quality and operational transparency now have their own explicit places in the architecture.

CLOSING NOTES

The most useful lesson from this overhaul was that a RAG system’s quality depends heavily on what happens before the language model sees a question. Poorly extracted tables, missing page references and flattened spreadsheets do not become reliable just because they have embeddings. Equally, an ingestion system is difficult to maintain if its interface, documentation and exports describe different workflows.

Mun now has a coherent document intake system: analysis, format-specific extraction, text and image indexing, automatic OCR, progress reporting and a management interface focused entirely on ingestion. The core language model did not need retraining, and the existing database and chat applications did not need replacing. Most of the value came from making the surrounding infrastructure better at getting reference material into a retrievable form.