Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

📖 feat: Add Native ODT Document Parser Support (#12303)

Pol Burkardt Freire7e74165c3cc6
diff --git a/package-lock.json b/package-lock.json
index 2454745a79..a056cc32ef 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -43789,6 +43789,9 @@
"name": "@librechat/api",
"version": "1.7.26",
"license": "ISC",
+ "dependencies": {
+ "jszip": "^3.10.1"
+ },
"devDependencies": {
"@babel/preset-env": "^7.21.5",
"@babel/preset-react": "^7.18.6",
diff --git a/packages/api/package.json b/packages/api/package.json
index 42f1f0e9f0..57675ee371 100644
--- a/packages/api/package.json
+++ b/packages/api/package.json
@@ -119,5 +119,8 @@
"rate-limit-redis": "^4.2.0",
"undici": "^7.24.1",
"zod": "^3.22.4"
+ },
+ "dependencies": {
+ "jszip": "^3.10.1"
}
}
diff --git a/packages/api/src/files/documents/crud.spec.ts b/packages/api/src/files/documents/crud.spec.ts
index f8b255dd5e..a1c317279c 100644
--- a/packages/api/src/files/documents/crud.spec.ts
+++ b/packages/api/src/files/documents/crud.spec.ts
@@ -1,4 +1,6 @@
import path from 'path';
+import * as fs from 'fs';
+import JSZip from 'jszip';
import { parseDocument } from './crud';
describe('Document Parser', () => {
@@ -74,6 +76,72 @@ describe('Document Parser', () => {
});
});
+ test('parseDocument() parses text from odt', async () => {
+ const file = {
+ originalname: 'sample.odt',
+ path: path.join(__dirname, 'sample.odt'),
+ mimetype: 'application/vnd.oasis.opendocument.text',
+ } as Express.Multer.File;
+
+ const document = await parseDocument({ file });
+
+ expect(document).toEqual({
+ bytes: 50,
+ filename: 'sample.odt',
+ filepath: 'document_parser',
+ images: [],
+ text: 'This is a sample ODT file.\n\nIt has two paragraphs.',
+ });
+ });
+
+ test('parseDocument() throws for odt with no extractable text', async () => {
+ const file = {
+ originalname: 'empty.odt',
+ path: path.join(__dirname, 'empty.odt'),
+ mimetype: 'application/vnd.oasis.opendocument.text',
+ } as Express.Multer.File;
+
+ await expect(parseDocument({ file })).rejects.toThrow('No text found in document');
+ });
+
+ test('parseDocument() throws for odt whose decompressed content exceeds the size limit', async () => {
+ const zip = new JSZip();
+ zip.file('mimetype', 'application/vnd.oasis.opendocument.text', { compression: 'STORE' });
+ zip.file('content.xml', 'x'.repeat(51 * 1024 * 1024), { compression: 'DEFLATE' });
+ const buf = await zip.generateAsync({ type: 'nodebuffer' });
+
+ const tmpPath = path.join(__dirname, 'bomb.odt');
+ await fs.promises.writeFile(tmpPath, buf);
+ try {
+ const file = {
+ originalname: 'bomb.odt',
+ path: tmpPath,
+ mimetype: 'application/vnd.oasis.opendocument.text',
+ } as Express.Multer.File;
+ await expect(parseDocument({ file })).rejects.toThrow(/exceeds the 50MB limit/);
+ } finally {
+ await fs.promises.unlink(tmpPath);
+ }
+ });
+
+ test('parseDocument() decodes XML entities and normalizes tab and spacing elements to spaces from odt', async () => {
+ const file = {
+ originalname: 'sample-entities.odt',
+ path: path.join(__dirname, 'sample-entities.odt'),
+ mimetype: 'application/vnd.oasis.opendocument.text',
+ } as Express.Multer.File;
+
+ const document = await parseDocument({ file });
+
+ expect(document).toEqual({
+ bytes: 19,
+ filename: 'sample-entities.odt',
+ filepath: 'document_parser',
+ images: [],
+ text: 'AT&T and A>B\n\nx y z',
+ });
+ });
+
test.each([
'application/msexcel',
'application/x-msexcel',
diff --git a/packages/api/src/files/documents/crud.ts b/packages/api/src/files/documents/crud.ts
index 61c1956542..e255323f77 100644
--- a/packages/api/src/files/documents/crud.ts
+++ b/packages/api/src/files/documents/crud.ts
@@ -1,4 +1,5 @@
import * as fs from 'fs';
+import JSZip from 'jszip';
import { megabyte, excelMimeTypes, FileSources } from 'librechat-data-provider';
import type { TextItem } from 'pdfjs-dist/types/src/display/api';
import type { MistralOCRUploadResult } from '~/types';
@@ -6,6 +7,7 @@ import type { MistralOCRUploadResult } from '~/types';
type FileParseFn = (file: Express.Multer.File) => Promise<string>;
const DOCUMENT_PARSER_MAX_FILE_SIZE = 15 * megabyte;
+const ODT_MAX_DECOMPRESSED_SIZE = 50 * megabyte;
/**
* Parses an uploaded document and extracts its text content and metadata.
@@ -61,6 +63,9 @@ function getParserForMimeType(mimetype: string): FileParseFn | undefined {
) {
return excelSheetToText;
}
+ if (mimetype === 'application/vnd.oasis.opendocument.text') {
+ return odtToText;
+ }
return undefined;
}
@@ -110,3 +115,56 @@ async function excelSheetToText(file: Express.Multer.File): Promise<string> {
return text;
}
+
+/**
+ * Parses OpenDocument Text (.odt) by extracting the body text from content.xml.
+ * Uses regex-based XML extraction scoped to <office:body>: paragraph/heading
+ * boundaries become newlines, tab and spacing elements are preserved, and the
+ * five standard XML entities are decoded. Complex elements such as frames,
+ * text boxes, and annotations are stripped without replacement.
+ */
+async function odtToText(file: Express.Multer.File): Promise<string> {
+ const data = await fs.promises.readFile(file.path);
+ const zip = await JSZip.loadAsync(data);
+
+ let totalUncompressed = 0;
+ zip.forEach((_, entry) => {
+ const raw = entry as JSZip.JSZipObject & { _data?: { uncompressedSize?: number } };
+ // _data.uncompressedSize is populated from the ZIP central directory at parse time
+ // by jszip (private internal, [email protected]). If the field is absent the guard fails
+ // open (adds 0); this is an accepted limitation of the approach.
+ totalUncompressed += raw._data?.uncompressedSize ?? 0;
+ });
+ if (totalUncompressed > ODT_MAX_DECOMPRESSED_SIZE) {
+ throw new Error(
+ `ODT file decompressed content (${Math.ceil(totalUncompressed / megabyte)}MB) exceeds the ${ODT_MAX_DECOMPRESSED_SIZE / megabyte}MB limit`,
+ );
+ }
+
+ const contentFile = zip.file('content.xml');
+ if (!contentFile) {
+ throw new Error('ODT file is missing content.xml');
+ }
+ const xml = await contentFile.async('string');
+ const bodyMatch = xml.match(/<office:body[^>]*>([\s\S]*?)<\/office:body>/);
+ if (!bodyMatch) {
+ return '';
+ }
+ return bodyMatch[1]
+ .replace(/<\/text:p>/g, '\n')
+ .replace(/<\/text:h>/g, '\n')
+ .replace(/<text:line-break\/>/g, '\n')
+ .replace(/<text:tab\/>/g, '\t')
+ .replace(/<text:s[^>]*\/>/g, ' ')
+ .replace(/<[^>]+>/g, '')
+ .replace(/&lt;/g, '<')
+ .replace(/&gt;/g, '>')
+ .replace(/&amp;/g, '&')
+ .replace(/&quot;/g, '"')
+ .replace(/&apos;/g, "'")
+ .replace(/[ \t]+/g, ' ')
+ .replace(/\n[ \t]+/g, '\n')
+ .replace(/[ \t]+\n/g, '\n')
+ .replace(/\n{3,}/g, '\n\n')
+ .trim();
+}
diff --git a/packages/api/src/files/documents/empty.odt b/packages/api/src/files/documents/empty.odt
new file mode 100644
index 0000000000..348d78ba08
Binary files /dev/null and b/packages/api/src/files/documents/empty.odt differ
diff --git a/packages/api/src/files/documents/sample-entities.odt b/packages/api/src/files/documents/sample-entities.odt
new file mode 100644
index 0000000000..d40addffa6
Binary files /dev/null and b/packages/api/src/files/documents/sample-entities.odt differ
diff --git a/packages/api/src/files/documents/sample.odt b/packages/api/src/files/documents/sample.odt
new file mode 100644
index 0000000000..e6c49d0f29
Binary files /dev/null and b/packages/api/src/files/documents/sample.odt differ
diff --git a/packages/data-provider/src/file-config.spec.ts b/packages/data-provider/src/file-config.spec.ts
index 0ab9f23a3e..96f48621cc 100644
--- a/packages/data-provider/src/file-config.spec.ts
+++ b/packages/data-provider/src/file-config.spec.ts
@@ -31,6 +31,7 @@ describe('inferMimeType', () => {
expect(inferMimeType('test.py', '')).toBe('text/x-python');
expect(inferMimeType('code.js', '')).toBe('text/javascript');
expect(inferMimeType('photo.heic', '')).toBe('image/heic');
+ expect(inferMimeType('Main.java', '')).toBe('text/x-java');
});
it('should return empty string for unknown extension with no browser type', () => {
@@ -141,12 +142,12 @@ describe('documentParserMimeTypes', () => {
'application/x-msexcel',
'application/x-ms-excel',
'application/vnd.oasis.opendocument.spreadsheet',
+ 'application/vnd.oasis.opendocument.text',
])('matches natively parseable type: %s', (mimeType) => {
expect(check(mimeType)).toBe(true);
});
it.each([
- 'application/vnd.oasis.opendocument.text',
'application/vnd.oasis.opendocument.presentation',
'application/vnd.oasis.opendocument.graphics',
'text/plain',
diff --git a/packages/data-provider/src/file-config.ts b/packages/data-provider/src/file-config.ts
index 67b4197958..32a1a28cc9 100644
--- a/packages/data-provider/src/file-config.ts
+++ b/packages/data-provider/src/file-config.ts
@@ -202,12 +202,13 @@ export const defaultOCRMimeTypes = [
/^application\/vnd\.oasis\.opendocument\.(text|spreadsheet|presentation|graphics)$/,
];
-/** MIME types handled by the built-in document parser (pdf, docx, excel variants, ods) */
+/** MIME types handled by the built-in document parser (pdf, docx, excel variants, ods/odt) */
export const documentParserMimeTypes = [
excelMimeTypes,
/^application\/pdf$/,
/^application\/vnd\.openxmlformats-officedocument\.wordprocessingml\.document$/,
/^application\/vnd\.oasis\.opendocument\.spreadsheet$/,
+ /^application\/vnd\.oasis\.opendocument\.text$/,
];
export const defaultTextMimeTypes = [/^[\w.-]+\/[\w.-]+$/];
@@ -242,6 +243,7 @@ export const codeTypeMapping: { [key: string]: string } = {
py: 'text/x-python', // .py - Python source
rb: 'text/x-ruby', // .rb - Ruby source
tex: 'text/x-tex', // .tex - LaTeX source
+ java: 'text/x-java', // .java - Java source
js: 'text/javascript', // .js - JavaScript source
sh: 'application/x-sh', // .sh - Shell script
ts: 'application/typescript', // .ts - TypeScript source