The minimalistic document archiving platform.
feat(docling): support configurable conversion options (#1532)
Corentin Thomasset50cbe2cace34
diff --git a/.changeset/funny-pens-nail.md b/.changeset/funny-pens-nail.mdnew file mode 100644index 00000000..538fac74--- /dev/null+++ b/.changeset/funny-pens-nail.md@@ -0,0 +1,5 @@+---+'@papra/app': patch+---++You can now configure Docling OCR languages and other conversion options with `DOCLING_OPTIONS`, using a JSON object such as `{"ocr_lang":["en","fr"]}`.diff --git a/apps/docs/src/content/docs/03-guides/13-content-extraction.mdx b/apps/docs/src/content/docs/03-guides/13-content-extraction.mdxindex 0f5bad00..f255b2a5 100644--- a/apps/docs/src/content/docs/03-guides/13-content-extraction.mdx+++ b/apps/docs/src/content/docs/03-guides/13-content-extraction.mdx@@ -79,8 +79,19 @@ DOCLING_BASE_URL=http://docling:5001| `DOCLING_BASE_URL` | `http://localhost:5001` | Base URL of the Docling service. || `DOCLING_API_KEY` | – | Optional API key, sent as the `X-API-Key` header. On the Docling side this maps to `DOCLING_SERVE_API_KEY`. || `DOCLING_REQUEST_TIMEOUT_MS` | `300000` | Request timeout in milliseconds. |+| `DOCLING_OPTIONS` | `{}` | Conversion options as a JSON object, sent with every Docling request. || `DOCLING_MIME_TYPES_ALLOW_LIST` | `*` | Mime types this strategy handles. See [mime type filtering](#mime-type-filtering). |+Use `DOCLING_OPTIONS` to configure OCR languages and other [Docling conversion options](https://github.com/docling-project/docling-serve/blob/main/docs/usage.md#common-parameters). For example, to use English and French OCR and force OCR over existing text:++```bash+DOCLING_OPTIONS='{"ocr_lang":["en","fr"],"force_ocr":true}'+```++The value must be a JSON object. Papra sends strings, numbers, and booleans as form fields, arrays as repeated fields, and nested objects as JSON-encoded fields. Top-level `null` values and empty arrays are omitted so Docling uses its defaults. Docling validates individual options; available settings and language support depend on your Docling version and OCR engine.++Papra manages `files`, `to_formats`, `image_export_mode`, and `target` to upload your document and read its Markdown content from a JSON response. Setting any of these fields in `DOCLING_OPTIONS` causes a configuration error at startup.+### Azure Document IntelligenceUses the [Azure Document Intelligence](https://azure.microsoft.com/products/ai-services/ai-document-intelligence) service.diff --git a/apps/papra-server/src/modules/documents/content-extraction/content-extraction-strategies/docling/docling.content-extraction-strategy.config.ts b/apps/papra-server/src/modules/documents/content-extraction/content-extraction-strategies/docling/docling.content-extraction-strategy.config.tsindex a154bfed..7b81ecfb 100644--- a/apps/papra-server/src/modules/documents/content-extraction/content-extraction-strategies/docling/docling.content-extraction-strategy.config.ts+++ b/apps/papra-server/src/modules/documents/content-extraction/content-extraction-strategies/docling/docling.content-extraction-strategy.config.ts@@ -3,6 +3,7 @@ import type { AppConfigDefinition } from '../../../../config/config.types';import { urlSchema } from '../../../../config/config.schemas';import { coercedStrictlyPositiveIntegerSchema } from '../../../../shared/schemas/number.schemas';import { IN_MS } from '../../../../shared/units';+import { doclingOptionsSchema } from './docling.content-extraction-strategy.schemas';export const doclingConfig = {baseUrl: {@@ -23,6 +24,12 @@ export const doclingConfig = {schema: coercedStrictlyPositiveIntegerSchema,default: 5 * IN_MS.MINUTE,},+ options: {+ doc: 'Conversion options sent with every Docling request, as a JSON object. For example: `{"ocr_lang":["en","fr"],"force_ocr":true}`. Arrays are sent as repeated form fields and objects as JSON. Top-level null values and empty arrays are omitted. The files, to_formats, image_export_mode, and target fields are managed by Papra and cannot be set here. See the [Docling options](https://github.com/docling-project/docling-serve/blob/main/docs/usage.md#common-parameters) for supported settings.',+ env: 'DOCLING_OPTIONS',+ schema: doclingOptionsSchema,+ default: '{}',+ },mimeTypesAllowList: {doc: 'The list of mime types that the Docling strategy will be used for. If the document mime type is not in this list, the strategy will be skipped. Comma separated list. Supports wildcards, e.g. "image/*" matches all image mime types, and "*" matches all formats. Prefix an entry with "!" to negate it, e.g. "*,!image/png" allows everything except PNG. Negations always take precedence over allows, even more specific ones (e.g. "image/png,!image/*" rejects PNG).',env: 'DOCLING_MIME_TYPES_ALLOW_LIST',diff --git a/apps/papra-server/src/modules/documents/content-extraction/content-extraction-strategies/docling/docling.content-extraction-strategy.models.test.ts b/apps/papra-server/src/modules/documents/content-extraction/content-extraction-strategies/docling/docling.content-extraction-strategy.models.test.tsindex e1ade986..f129f1ad 100644--- a/apps/papra-server/src/modules/documents/content-extraction/content-extraction-strategies/docling/docling.content-extraction-strategy.models.test.ts+++ b/apps/papra-server/src/modules/documents/content-extraction/content-extraction-strategies/docling/docling.content-extraction-strategy.models.test.ts@@ -1,7 +1,83 @@import { describe, expect, test } from 'vitest';-import { stripDoclingImagePlaceholders } from './docling.content-extraction-strategy.models';+import {+ buildDoclingRequestBody,+ stripDoclingImagePlaceholders,+} from './docling.content-extraction-strategy.models';describe('docling.content-extraction-strategy.models', () => {+ describe('buildDoclingRequestBody', () => {+ const file = new File(['document content'], 'document.txt', { type: 'text/plain' });++ test('the document is uploaded with Markdown and image placeholder output', async () => {+ const body = buildDoclingRequestBody({ file, options: {} });+ const uploadedFile = body.get('files') as File;++ expect(uploadedFile.name).toEqual('document.txt');+ expect(uploadedFile.type).toEqual('text/plain');+ expect(await uploadedFile.text()).toEqual('document content');+ expect([...body.keys()]).toEqual(['files', 'to_formats', 'image_export_mode']);+ expect(body.getAll('to_formats')).toEqual(['md']);+ expect(body.get('image_export_mode')).toEqual('placeholder');+ });++ test('multiple OCR languages and page numbers are sent as repeated fields', () => {+ const body = buildDoclingRequestBody({+ file,+ options: { ocr_lang: ['en', 'fr'], page_range: [1, 5] },+ });++ expect(body.getAll('ocr_lang')).toEqual(['en', 'fr']);+ expect(body.getAll('page_range')).toEqual(['1', '5']);+ });++ test('scalar options preserve punctuation, false, and zero values', () => {+ const body = buildDoclingRequestBody({+ file,+ options: {+ ocr_lang: 'en',+ force_ocr: true,+ do_table_structure: false,+ images_scale: 1.5,+ picture_description_area_threshold: 0,+ md_page_break_placeholder: 'Page break: next, please',+ },+ });++ expect(body.getAll('ocr_lang')).toEqual(['en']);+ expect(body.get('force_ocr')).toEqual('true');+ expect(body.get('do_table_structure')).toEqual('false');+ expect(body.get('images_scale')).toEqual('1.5');+ expect(body.get('picture_description_area_threshold')).toEqual('0');+ expect(body.get('md_page_break_placeholder')).toEqual('Page break: next, please');+ });++ test('nested options are JSON-encoded without flattening their values', () => {+ const body = buildDoclingRequestBody({+ file,+ options: {+ picture_description_api: {+ url: 'http://localhost:11434/v1/chat/completions',+ params: { model: 'granite3.2-vision:2b', stop: ['end', 'stop'], seed: null },+ },+ },+ });++ expect(body.get('picture_description_api')).toEqual(+ '{"url":"http://localhost:11434/v1/chat/completions","params":{"model":"granite3.2-vision:2b","stop":["end","stop"],"seed":null}}',+ );+ });++ test('null options and empty lists are omitted so Docling uses its defaults', () => {+ const body = buildDoclingRequestBody({+ file,+ options: { ocr_lang: [], document_timeout: null },+ });++ expect(body.has('ocr_lang')).toEqual(false);+ expect(body.has('document_timeout')).toEqual(false);+ });+ });+describe('stripDoclingImagePlaceholders', () => {test('docling replaces graphical content with <!-- image -->, this function removes it', () => {expect(diff --git a/apps/papra-server/src/modules/documents/content-extraction/content-extraction-strategies/docling/docling.content-extraction-strategy.models.ts b/apps/papra-server/src/modules/documents/content-extraction/content-extraction-strategies/docling/docling.content-extraction-strategy.models.tsindex 89d6f087..6360e3d5 100644--- a/apps/papra-server/src/modules/documents/content-extraction/content-extraction-strategies/docling/docling.content-extraction-strategy.models.ts+++ b/apps/papra-server/src/modules/documents/content-extraction/content-extraction-strategies/docling/docling.content-extraction-strategy.models.ts@@ -1,3 +1,30 @@+export function buildDoclingRequestBody({+ file,+ options,+}: {+ file: File;+ options: Record<string, unknown>;+}): FormData {+ const body = new FormData();+ body.append('files', file);+ body.append('to_formats', 'md');+ body.append('image_export_mode', 'placeholder');++ for (const [key, value] of Object.entries(options)) {+ if (value === null) {+ continue;+ }++ const values = Array.isArray(value) ? value : [value];++ for (const item of values) {+ body.append(key, typeof item === 'string' ? item : JSON.stringify(item));+ }+ }++ return body;+}+export function stripDoclingImagePlaceholders(text: string): string {return text.replaceAll('<!-- image -->', '').trim();}diff --git a/apps/papra-server/src/modules/documents/content-extraction/content-extraction-strategies/docling/docling.content-extraction-strategy.schemas.test.ts b/apps/papra-server/src/modules/documents/content-extraction/content-extraction-strategies/docling/docling.content-extraction-strategy.schemas.test.tsnew file mode 100644index 00000000..01b19da6--- /dev/null+++ b/apps/papra-server/src/modules/documents/content-extraction/content-extraction-strategies/docling/docling.content-extraction-strategy.schemas.test.ts@@ -0,0 +1,46 @@+import { describe, expect, test } from 'vitest';+import { doclingOptionsSchema } from './docling.content-extraction-strategy.schemas';+import * as v from 'valibot';++describe('docling.content-extraction-strategy.schemas', () => {+ describe('doclingOptionsSchema', () => {+ test('DOCLING_OPTIONS accepts a JSON object with Docling conversion options', () => {+ const options = {+ ocr_lang: ['en', 'fr'],+ force_ocr: true,+ images_scale: 2,+ table_mode: 'accurate',+ ocr_custom_config: { kind: 'rapidocr' },+ document_timeout: null,+ future_option: 'custom value',+ };++ const parsedOptions = v.parse(doclingOptionsSchema, JSON.stringify(options));++ expect(parsedOptions).toEqual(options);+ });++ test('malformed JSON and comma-separated options are rejected', () => {+ expect(() => v.parse(doclingOptionsSchema, '{"ocr_lang":')).toThrow();+ expect(() => v.parse(doclingOptionsSchema, 'ocr_lang:en,force_ocr:true')).toThrow();+ });++ test('empty string is treated as an empty object', () => {+ expect(v.parse(doclingOptionsSchema, '')).toEqual({});+ });++ test('the JSON value must be an object', () => {+ for (const input of ['[]', 'null', 'true', '42', '"en"']) {+ expect(() => v.parse(doclingOptionsSchema, input)).toThrow();+ }+ });++ test('fields controlling the uploaded file and response format are rejected', () => {+ for (const key of ['files', 'to_formats', 'image_export_mode', 'target']) {+ expect(() => v.parse(doclingOptionsSchema, JSON.stringify({ [key]: 'override' }))).toThrow(+ 'DOCLING_OPTIONS cannot set files, to_formats, image_export_mode, or target; these fields are managed by Papra.',+ );+ }+ });+ });+});diff --git a/apps/papra-server/src/modules/documents/content-extraction/content-extraction-strategies/docling/docling.content-extraction-strategy.schemas.ts b/apps/papra-server/src/modules/documents/content-extraction/content-extraction-strategies/docling/docling.content-extraction-strategy.schemas.tsnew file mode 100644index 00000000..01eccea0--- /dev/null+++ b/apps/papra-server/src/modules/documents/content-extraction/content-extraction-strategies/docling/docling.content-extraction-strategy.schemas.ts@@ -0,0 +1,21 @@+import * as v from 'valibot';++export const doclingOptionsSchema = v.pipe(+ v.string(),+ v.transform((value) => (value === '' ? '{}' : value)),+ v.parseJson(),+ v.check(+ (value) => typeof value === 'object' && value !== null && !Array.isArray(value),+ 'DOCLING_OPTIONS must be a JSON object.',+ ),+ v.record(+ v.pipe(+ v.string(),+ v.check(+ (key) => !['files', 'to_formats', 'image_export_mode', 'target'].includes(key),+ 'DOCLING_OPTIONS cannot set files, to_formats, image_export_mode, or target; these fields are managed by Papra.',+ ),+ ),+ v.unknown(),+ ),+);diff --git a/apps/papra-server/src/modules/documents/content-extraction/content-extraction-strategies/docling/docling.content-extraction-strategy.ts b/apps/papra-server/src/modules/documents/content-extraction/content-extraction-strategies/docling/docling.content-extraction-strategy.tsindex da6dacdb..0b02dde6 100644--- a/apps/papra-server/src/modules/documents/content-extraction/content-extraction-strategies/docling/docling.content-extraction-strategy.ts+++ b/apps/papra-server/src/modules/documents/content-extraction/content-extraction-strategies/docling/docling.content-extraction-strategy.ts@@ -1,16 +1,25 @@+import { ofetch } from 'ofetch';import type { Config } from '../../../../config/config.types';import type { ContentExtractionStrategy } from '../content-extraction-strategies.types';import { isMimeTypeAllowed } from '../../../../shared/mime-types/mime-types.models';-import { extractTextWithDoclingServer } from './docling.content-extraction-strategy.usecases';+import { buildExtractTextWithDoclingServer } from './docling.content-extraction-strategy.usecases';export function buildDoclingContentExtractionStrategy({config,}: {config: Config;}): ContentExtractionStrategy {- const { baseUrl, apiKey, mimeTypesAllowList, timeoutMs } =+ const { baseUrl, apiKey, mimeTypesAllowList, timeoutMs, options } =config.documentContentExtraction.strategy.docling;+ const extractTextWithDoclingServer = buildExtractTextWithDoclingServer({+ baseUrl,+ apiKey,+ timeoutMs,+ options,+ request: ofetch,+ });+return {canExtractTextFromDocument: async ({ file }) => {return isMimeTypeAllowed({@@ -19,15 +28,6 @@ export function buildDoclingContentExtractionStrategy({});},- extractTextFromDocument: async ({ file }) => {- const { text } = await extractTextWithDoclingServer({- file,- baseUrl,- apiKey,- timeoutMs,- });-- return { text };- },+ extractTextFromDocument: extractTextWithDoclingServer,};}diff --git a/apps/papra-server/src/modules/documents/content-extraction/content-extraction-strategies/docling/docling.content-extraction-strategy.usecases.test.ts b/apps/papra-server/src/modules/documents/content-extraction/content-extraction-strategies/docling/docling.content-extraction-strategy.usecases.test.tsnew file mode 100644index 00000000..8dc1a0a2--- /dev/null+++ b/apps/papra-server/src/modules/documents/content-extraction/content-extraction-strategies/docling/docling.content-extraction-strategy.usecases.test.ts@@ -0,0 +1,38 @@+import { describe, expect, test } from 'vitest';+import { buildExtractTextWithDoclingServer } from './docling.content-extraction-strategy.usecases';++describe('extractTextWithDoclingServer', () => {+ test('configured options accompany the document upload and the response yields clean text', async () => {+ const file = new File(['scanned document'], 'scan.jpg', { type: 'image/jpeg' });+ const extractText = buildExtractTextWithDoclingServer({+ baseUrl: 'http://docling:5001/',+ apiKey: 'test-api-key',+ timeoutMs: 300000,+ options: { ocr_lang: ['en', 'fr'], force_ocr: true },+ request: async (url, { method, headers, timeout, body }) => {+ expect(url).toEqual('http://docling:5001/v1/convert/file');+ expect(method).toEqual('POST');+ expect(headers).toEqual({ 'X-Api-Key': 'test-api-key' });+ expect(timeout).toEqual(300000);++ // Round-trip the multipart body to verify the fields Docling receives.+ const form = await new Response(body as FormData).formData();+ const uploadedFile = form.get('files') as File;++ expect(uploadedFile.name).toEqual('scan.jpg');+ expect(uploadedFile.type).toEqual('image/jpeg');+ expect(await uploadedFile.text()).toEqual('scanned document');+ expect(form.getAll('ocr_lang')).toEqual(['en', 'fr']);+ expect(form.get('force_ocr')).toEqual('true');+ expect(form.get('to_formats')).toEqual('md');++ return {+ status: 'success',+ document: { md_content: ' <!-- image -->Extracted text ' },+ };+ },+ });++ expect(await extractText({ file })).toEqual({ text: 'Extracted text' });+ });+});diff --git a/apps/papra-server/src/modules/documents/content-extraction/content-extraction-strategies/docling/docling.content-extraction-strategy.usecases.ts b/apps/papra-server/src/modules/documents/content-extraction/content-extraction-strategies/docling/docling.content-extraction-strategy.usecases.tsindex 17b7f56a..69ab34c8 100644--- a/apps/papra-server/src/modules/documents/content-extraction/content-extraction-strategies/docling/docling.content-extraction-strategy.usecases.ts+++ b/apps/papra-server/src/modules/documents/content-extraction/content-extraction-strategies/docling/docling.content-extraction-strategy.usecases.ts@@ -1,6 +1,9 @@-import { ofetch } from 'ofetch';+import type { FetchOptions } from 'ofetch';import * as v from 'valibot';-import { stripDoclingImagePlaceholders } from './docling.content-extraction-strategy.models';+import {+ buildDoclingRequestBody,+ stripDoclingImagePlaceholders,+} from './docling.content-extraction-strategy.models';export const doclingResponseSchema = v.object({status: v.literal('success'),@@ -9,39 +12,37 @@ export const doclingResponseSchema = v.object({}),});-export async function extractTextWithDoclingServer({- file,+export function buildExtractTextWithDoclingServer({baseUrl,apiKey,timeoutMs,+ options,+ request,}: {- file: File;baseUrl: string;apiKey?: string;timeoutMs: number;+ options: Record<string, unknown>;+ request: (url: string, options: FetchOptions<'json'>) => Promise<unknown>;}) {const url = `${baseUrl.replace(/\/$/, '')}/v1/convert/file`;- const body = new FormData();- body.append('files', file);- body.append('to_formats', 'md');- body.append('image_export_mode', 'placeholder');+ return async ({ file }: { file: File }) => {+ const body = buildDoclingRequestBody({ file, options });- const response = await ofetch<unknown>(url, {- method: 'POST',- headers: {- // 'Content-Type': 'multipart/form-data',- ...(apiKey ? { 'X-Api-Key': apiKey } : {}),- },- timeout: timeoutMs,- body,- });+ const response = await request(url, {+ method: 'POST',+ headers: {+ ...(apiKey ? { 'X-Api-Key': apiKey } : {}),+ },+ timeout: timeoutMs,+ body,+ });- const parsedResponse = v.parse(doclingResponseSchema, response);+ const parsedResponse = v.parse(doclingResponseSchema, response);- const text = stripDoclingImagePlaceholders(parsedResponse.document.md_content);+ const text = stripDoclingImagePlaceholders(parsedResponse.document.md_content);- return {- text,+ return { text };};}