Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

feat(extractors): add support for .xlsx and .ods file content extraction (#949)

Corentin Thomassetec740ed16849
diff --git a/.changeset/eight-eyes-grin.md b/.changeset/eight-eyes-grin.md
new file mode 100644
index 00000000..14256441
--- /dev/null
+++ b/.changeset/eight-eyes-grin.md
@@ -0,0 +1,6 @@
+---
+"@papra/lecture": patch
+"@papra/app": patch
+---
+
+Added document content extraction support for .xlsx and .ods files.
diff --git a/packages/lecture/fixtures/018-xlsx/018.expected.txt b/packages/lecture/fixtures/018-xlsx/018.expected.txt
new file mode 100644
index 00000000..b9a0077e
--- /dev/null
+++ b/packages/lecture/fixtures/018-xlsx/018.expected.txt
@@ -0,0 +1,15 @@
+ID Name Role
+1 Sabrina Spellman Witch
+2 Darth Vader Sith Lord
+3 Arya Stark Assassin
+4 Sherlock Holmes Detective
+5 Ahsoka Cat / Jedi
+6 Pocky Cat
+
+ID Text
+a Lorem
+b Ipsum
+c Dolor
+d Sit
+e Amet Some text on the right (F6)
+Some text way below
\ No newline at end of file
diff --git a/packages/lecture/fixtures/018-xlsx/018.input.xlsx b/packages/lecture/fixtures/018-xlsx/018.input.xlsx
new file mode 100644
index 00000000..e81e5e99
Binary files /dev/null and b/packages/lecture/fixtures/018-xlsx/018.input.xlsx differ
diff --git a/packages/lecture/fixtures/019-ods/019.expected.txt b/packages/lecture/fixtures/019-ods/019.expected.txt
new file mode 100644
index 00000000..b9a0077e
--- /dev/null
+++ b/packages/lecture/fixtures/019-ods/019.expected.txt
@@ -0,0 +1,15 @@
+ID Name Role
+1 Sabrina Spellman Witch
+2 Darth Vader Sith Lord
+3 Arya Stark Assassin
+4 Sherlock Holmes Detective
+5 Ahsoka Cat / Jedi
+6 Pocky Cat
+
+ID Text
+a Lorem
+b Ipsum
+c Dolor
+d Sit
+e Amet Some text on the right (F6)
+Some text way below
\ No newline at end of file
diff --git a/packages/lecture/fixtures/019-ods/019.input.ods b/packages/lecture/fixtures/019-ods/019.input.ods
new file mode 100644
index 00000000..24016fc7
Binary files /dev/null and b/packages/lecture/fixtures/019-ods/019.input.ods differ
diff --git a/packages/lecture/src/extractors.registry.ts b/packages/lecture/src/extractors.registry.ts
index 056d1d10..eb013240 100644
--- a/packages/lecture/src/extractors.registry.ts
+++ b/packages/lecture/src/extractors.registry.ts
@@ -2,11 +2,13 @@ import type { ExtractorDefinition } from './extractors.models';
import { docExtractorDefinition } from './extractors/doc.extractor';
import { imageExtractorDefinition } from './extractors/img.extractor';
import { odpExtractorDefinition } from './extractors/odp.extractor';
+import { odsExtractorDefinition } from './extractors/ods.extractor';
import { odtExtractorDefinition } from './extractors/odt.extractor';
import { pdfExtractorDefinition } from './extractors/pdf.extractor';
import { pptxExtractorDefinition } from './extractors/pptx.extractor';
import { rtfExtractorDefinition } from './extractors/rtf.extractor';
import { txtExtractorDefinition } from './extractors/txt.extractor';
+import { xlsxExtractorDefinition } from './extractors/xlsx.extractor';
export const extractorDefinitions: ExtractorDefinition[] = [
pdfExtractorDefinition,
@@ -17,6 +19,8 @@ export const extractorDefinitions: ExtractorDefinition[] = [
pptxExtractorDefinition,
odtExtractorDefinition,
odpExtractorDefinition,
+ odsExtractorDefinition,
+ xlsxExtractorDefinition,
];
export function getExtractor({
diff --git a/packages/lecture/src/extractors.usecases.test.ts b/packages/lecture/src/extractors.usecases.test.ts
index 27ff27b8..2b11d1d3 100644
--- a/packages/lecture/src/extractors.usecases.test.ts
+++ b/packages/lecture/src/extractors.usecases.test.ts
@@ -69,7 +69,7 @@ describe('extractors usecases', () => {
});
expect(error).to.eql(undefined);
- expect(extractorName).to.not.eql(undefined);
+ expect(extractorName).to.not.eql(undefined, 'No extractor found for the fixture file');
expect(extractorType).to.not.eql(undefined);
const fixtureNumber = fixtureDir.split('/').filter(Boolean).pop().slice(0, 3);
diff --git a/packages/lecture/src/extractors/ods.extractor.ts b/packages/lecture/src/extractors/ods.extractor.ts
new file mode 100644
index 00000000..7260009d
--- /dev/null
+++ b/packages/lecture/src/extractors/ods.extractor.ts
@@ -0,0 +1,114 @@
+import { XMLParser } from 'fast-xml-parser';
+import { defineTextExtractor } from '../extractors.models';
+import { getFileContentFromArchive } from '../utils/archive';
+
+type XmlNode = Record<string, unknown>;
+
+function asNode(value: unknown): XmlNode | undefined {
+ if (value != null && typeof value === 'object' && !Array.isArray(value)) {
+ return value as XmlNode;
+ }
+ return undefined;
+}
+
+function asArray(value: unknown): unknown[] {
+ if (Array.isArray(value)) {
+ return value;
+ }
+ if (value != null) {
+ return [value];
+ }
+ return [];
+}
+
+// Recursively extract all text content from a parsed XML node,
+// handling nested elements like text:span and arrays of paragraphs.
+function extractText(node: unknown): string {
+ if (node == null) {
+ return '';
+ }
+ if (typeof node !== 'object') {
+ return String(node).trim();
+ }
+ if (Array.isArray(node)) {
+ return node.map(extractText).filter(Boolean).join(' ');
+ }
+ const obj = node as XmlNode;
+ const parts: string[] = [];
+ if (obj['#text'] != null) {
+ const t = String(obj['#text']).trim();
+ if (t) {
+ parts.push(t);
+ }
+ }
+ for (const key of Object.keys(obj)) {
+ if (key !== '#text') {
+ const child = extractText(obj[key]);
+ if (child) {
+ parts.push(child);
+ }
+ }
+ }
+ return parts.join(' ');
+}
+
+export const odsExtractorDefinition = defineTextExtractor({
+ name: 'ods',
+ mimeTypes: [
+ 'application/vnd.oasis.opendocument.spreadsheet',
+ ],
+ extract: async ({ arrayBuffer }) => {
+ const contentXml = await getFileContentFromArchive({ arrayBuffer, filePath: 'content.xml' });
+
+ if (!contentXml) {
+ return { content: '' };
+ }
+
+ const parser = new XMLParser({ ignoreAttributes: false, attributeNamePrefix: '@_', textNodeName: '#text', isArray: () => false });
+ const parsed = asNode(parser.parse(contentXml));
+
+ // Navigate to office:spreadsheet
+ const docContent = asNode(parsed?.['office:document-content']);
+ const body = asNode(docContent?.['office:body']);
+ const spreadsheet = asNode(body?.['office:spreadsheet']);
+ const tables = asArray(spreadsheet?.['table:table']);
+
+ const sheetTexts: string[] = [];
+
+ for (const tableRaw of tables) {
+ const table = asNode(tableRaw);
+ const rows = asArray(table?.['table:table-row']);
+ const rowTexts: string[] = [];
+
+ for (const rowRaw of rows) {
+ const row = asNode(rowRaw);
+ const cells = asArray(row?.['table:table-cell']);
+ const cellTexts: string[] = [];
+
+ for (const cellRaw of cells) {
+ const cell = asNode(cellRaw);
+ if (!cell) {
+ continue;
+ }
+
+ // text:p can be a primitive, object, or array of paragraphs (each possibly with nested spans)
+ const text = asArray(cell['text:p']).map(extractText).filter(Boolean).join(' ');
+
+ if (text) {
+ cellTexts.push(text);
+ }
+ }
+
+ if (cellTexts.length > 0) {
+ rowTexts.push(cellTexts.join('\t'));
+ }
+ }
+
+ if (rowTexts.length > 0) {
+ sheetTexts.push(rowTexts.join('\n'));
+ }
+ }
+
+ return { content: sheetTexts.join('\n\n') };
+ },
+});
diff --git a/packages/lecture/src/extractors/xlsx.extractor.ts b/packages/lecture/src/extractors/xlsx.extractor.ts
new file mode 100644
index 00000000..deb561b7
--- /dev/null
+++ b/packages/lecture/src/extractors/xlsx.extractor.ts
@@ -0,0 +1,187 @@
+import { XMLParser } from 'fast-xml-parser';
+import JSZip from 'jszip';
+import { defineTextExtractor } from '../extractors.models';
+
+type XmlNode = Record<string, unknown>;
+
+function asNode(value: unknown): XmlNode | undefined {
+ if (value != null && typeof value === 'object' && !Array.isArray(value)) {
+ return value as XmlNode;
+ }
+ return undefined;
+}
+
+function asArray(value: unknown): unknown[] {
+ if (Array.isArray(value)) {
+ return value;
+ }
+ if (value != null) {
+ return [value];
+ }
+ return [];
+}
+
+// <t> elements can have attributes (e.g. xml:space="preserve"), in which case
+// fast-xml-parser returns an object with '#text' rather than a plain string.
+function extractTText(t: unknown): string {
+ if (t == null) {
+ return '';
+ }
+ if (typeof t !== 'object') {
+ return String(t);
+ }
+ const obj = t as XmlNode;
+ return obj['#text'] != null ? String(obj['#text']) : '';
+}
+
+export const xlsxExtractorDefinition = defineTextExtractor({
+ name: 'xlsx',
+ mimeTypes: [
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
+ ],
+ extract: async ({ arrayBuffer }) => {
+ const zip = await JSZip.loadAsync(arrayBuffer);
+ const parser = new XMLParser({ ignoreAttributes: false, attributeNamePrefix: '@_', textNodeName: '#text', isArray: () => false });
+
+ // Load shared strings (may not exist in all xlsx files)
+ const sharedStrings: string[] = [];
+ const sharedStringsXml = await zip.file('xl/sharedStrings.xml')?.async('text');
+ if (sharedStringsXml) {
+ const parsed = asNode(parser.parse(sharedStringsXml));
+ const sst = asNode(parsed?.sst);
+ for (const si of asArray(sst?.si)) {
+ sharedStrings.push(extractSharedString(si));
+ }
+ }
+
+ // Resolve sheet targets from xl/_rels/workbook.xml.rels to handle non-contiguous sheet numbering
+ const rIdToTarget: Record<string, string> = {};
+ const relsXml = await zip.file('xl/_rels/workbook.xml.rels')?.async('text');
+ if (relsXml) {
+ const rels = asNode(parser.parse(relsXml));
+ const relationships = asNode(rels?.Relationships);
+ for (const rel of asArray(relationships?.Relationship)) {
+ const relNode = asNode(rel);
+ if (!relNode) {
+ continue;
+ }
+ const id = relNode['@_Id'] as string | undefined;
+ const target = relNode['@_Target'] as string | undefined;
+ const type = relNode['@_Type'] as string | undefined;
+ if (id && target && type?.endsWith('/worksheet')) {
+ rIdToTarget[id] = target.startsWith('xl/') ? target : `xl/${target}`;
+ }
+ }
+ }
+
+ // Determine sheet order from workbook.xml, resolving actual targets via rels
+ const sheetPaths: string[] = [];
+ const workbookXml = await zip.file('xl/workbook.xml')?.async('text');
+ if (workbookXml) {
+ const workbook = asNode(parser.parse(workbookXml));
+ const wb = asNode(workbook?.workbook);
+ const sheets = asNode(wb?.sheets);
+ for (const sheetRaw of asArray(sheets?.sheet)) {
+ const sheet = asNode(sheetRaw);
+ const rId = sheet?.['@_r:id'] as string | undefined;
+ const target = rId ? rIdToTarget[rId] : undefined;
+ if (target) {
+ sheetPaths.push(target);
+ }
+ }
+ }
+
+ // Fallback: discover sheets from zip if rels resolution yielded nothing
+ if (sheetPaths.length === 0) {
+ Object.keys(zip.files)
+ .filter(name => name.match(/^xl\/worksheets\/sheet\d+\.xml$/))
+ .sort((a, b) => {
+ const numA = Number.parseInt(a.match(/sheet(\d+)\.xml$/)?.[1] ?? '0', 10);
+ const numB = Number.parseInt(b.match(/sheet(\d+)\.xml$/)?.[1] ?? '0', 10);
+ return numA - numB;
+ })
+ .forEach(name => sheetPaths.push(name));
+ }
+
+ const sheets: string[] = [];
+
+ for (const sheetPath of sheetPaths) {
+ const sheetXml = await zip.file(sheetPath)?.async('text');
+ if (!sheetXml) {
+ continue;
+ }
+
+ const parsed = asNode(parser.parse(sheetXml));
+ const worksheet = asNode(parsed?.worksheet);
+ const sheetData = asNode(worksheet?.sheetData);
+ const rows = asArray(sheetData?.row);
+
+ const rowTexts: string[] = [];
+
+ for (const rowRaw of rows) {
+ const row = asNode(rowRaw);
+ const cells = asArray(row?.c);
+ const cellTexts: string[] = [];
+
+ for (const cellRaw of cells) {
+ const cell = asNode(cellRaw);
+ if (!cell) {
+ continue;
+ }
+
+ const cellType = cell['@_t'] as string | undefined;
+ const value = cell.v;
+ const inlineStr = asNode(cell.is);
+
+ let text = '';
+
+ if (cellType === 's' && value != null) {
+ // shared string reference
+ text = sharedStrings[Number(value)] ?? '';
+ } else if (cellType === 'inlineStr' && inlineStr) {
+ text = extractSharedString(inlineStr);
+ } else if (cellType === 'str' && value != null) {
+ // formula result string
+ text = String(value);
+ } else if (value != null) {
+ text = String(value);
+ }
+
+ if (text.trim()) {
+ cellTexts.push(text.trim());
+ }
+ }
+
+ if (cellTexts.length > 0) {
+ rowTexts.push(cellTexts.join('\t'));
+ }
+ }
+
+ if (rowTexts.length > 0) {
+ sheets.push(rowTexts.join('\n'));
+ }
+ }
+
+ return { content: sheets.join('\n\n') };
+ },
+});
+
+function extractSharedString(si: unknown): string {
+ const siObj = asNode(si);
+ if (!siObj) {
+ return '';
+ }
+
+ // Simple string: <si><t>text</t></si>
+ if (siObj.t != null) {
+ return extractTText(siObj.t);
+ }
+
+ // Rich text: <si><r><t>text</t></r>...</si>
+ return asArray(siObj.r)
+ .map((r) => {
+ const rObj = asNode(r);
+ return rObj?.t != null ? extractTText(rObj.t) : '';
+ })
+ .join('');
+}