LogoKalli
Server

Parsing & Document Processor

Parsing & Document Processor

Le parsing des documents est délégué à un microservice dédié (apps/document-processor/) appelé par le serveur Bun via un client HTTP (apps/server/src/utils/document-processor-client.ts).

Architecture

Admin (web) → processUploadedFile (ORPC, admin)

          regular-processing.ts

    documentProcessor.processDocument()

    POST http://DOCUMENT_PROCESSOR_URL/process

    document-processor microservice (FastAPI)

    Chunks → INSERT INTO chunks (DB)

Microservice document-processor

Localisation: apps/document-processor/
Stack: Python, FastAPI, uvicorn

Démarrage

# Variables d'environnement
DOCUMENT_PROCESSOR_HOST=0.0.0.0
DOCUMENT_PROCESSOR_PORT=8001
MAX_FILE_SIZE_MB=50
ENABLE_OCR=false
TESSERACT_PATH=         # optionnel, si tesseract n'est pas dans PATH
LOG_LEVEL=INFO
cd apps/document-processor
pip install -e .
uvicorn src.main:app --host 0.0.0.0 --port 8001

Endpoints

GET /health

Response (HealthResponse):

{
  "status": "healthy",
  "timestamp": "2024-01-15T10:30:00.000Z"
}

POST /process

Parse et découpe un document en chunks.

Request (ProcessingRequest):

{
  file_content: string;        // base64, data URL, ou texte brut (pour text/plain, text/markdown, text/csv, application/json)
  file_name: string;
  file_type: string;           // MIME type (voir formats supportés)
  chunk_size?: number;         // default: 1000 (taille en caractères)
  overlap?: number;            // default: 200 (chevauchement entre chunks)
  extract_qa_pairs?: boolean;  // default: false
  extract_tables?: boolean;    // default: true
  extract_images?: boolean;    // default: false
}

Response (ProcessingResult):

{
  success: boolean;
  chunks: Chunk[];           // liste des chunks extraits
  qa_pairs: QAPair[];        // si extract_qa_pairs: true
  tables: Table[];           // tableaux extraits (si extract_tables: true)
  images: Image[];           // images extraites (si extract_images: true)
  metadata: Record<string, any>;
  processing_time_ms: number;
  error?: string;            // présent si success: false
}

type Chunk = {
  rank: number;
  content: string;
  category: string; // "not categorized" par défaut
  metadata?: {
    source_type: string;      // "text", "table", "picture"
    section_path?: string[];  // hiérarchie des sections
    page_numbers?: number[];  // pages du chunk
    bboxes?: Array<{l, t, r, b}>;  // coordonnées
    docling_item_refs?: string[];  // références items Docling
    token_count?: number;     // nombre de tokens
    origin?: string;          // nom du fichier d'origine
    parser_version: string;
    chunking_config: { max_tokens: number, merge_peers: boolean };
  };
  page_number?: number;
  section_title?: string;
  section_path?: string[];
  provenance?: {
    page_numbers?: number[];
    bboxes?: Array<{l, t, r, b}>;
    docling_item_refs?: string[];
  };
  token_count?: number;
  source_type?: string;
  has_table?: boolean;
  has_image?: boolean;
}

Codes d'erreur:

  • 400 — contenu fichier invalide (base64 malformé)
  • 413 — fichier trop grand (> MAX_FILE_SIZE_MB)
  • 415 — type de fichier non supporté
  • 500 — erreur de parsing interne

Formats supportés

Le microservice utilise Docling 2.116 pour le parsing, offrant une large compatibilité de formats.

MIME typeExtensionHandler
application/pdf.pdfDocling
application/vnd.openxmlformats-officedocument.wordprocessingml.document.docxDocling
application/vnd.openxmlformats-officedocument.presentationml.presentation.pptxDocling
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.xlsxDocling
application/vnd.ms-excel.xlsDocling
text/csv.csvDocling
text/markdown.md, .markdownDocling
text/plain.txtDocling
text/html.html, .htm, .xhtmlDocling
image/png.pngDocling
image/jpeg.jpg, .jpegDocling
image/tiff.tiff, .tifDocling
image/bmp.bmpDocling
image/webp.webpDocling
application/vnd.oasis.opendocument.text.odtDocling
application/vnd.oasis.opendocument.spreadsheet.odsDocling
application/vnd.oasis.opendocument.presentation.odpDocling
application/epub+zip.epubDocling
application/xml.xmlDocling
text/asciidoc.adoc, .asciidocDocling
application/msword.docDocling (legacy)
application/vnd.ms-powerpoint.pptDocling (legacy)
application/x-latex.texDocling
text/x-latex.texDocling
text/vtt.vttDocling
application/vtt.vttDocling
message/rfc822.emlDocling
application/xml+jats.jats.xmlDocling
application/xml+uspto.uspto.xmlDocling
application/xml+xbrl.xbrlDocling
application/json.jsonJSON (business/technical)

Priorité: le type MIME est prioritaire sur l'extension.

OCR (optionnel)

L'OCR est configurée via DOCLING_ENABLE_OCR et DOCLING_OCR_ENGINE. Plusieurs moteurs sont supportés :

  • easyocr (défaut) — moteur OCR basé sur PyTorch
  • rapidocr — moteur OCR léger basé onnxruntime
  • tesseract-cli — Tesseract via CLI
  • tesserocr — Tesseract via Python wrapper

Exemple de configuration :

DOCLING_ENABLE_OCR=true
DOCLING_OCR_ENGINE=easyocr  # ou rapidocr, tesseract-cli, tesserocr
DOCLING_OCR_LANGUAGES=en,fr

Pour tesseract-cli ou tesserocr, l'installation de tesseract-ocr sur le système est requise.


Client côté serveur Bun

apps/server/src/utils/document-processor-client.ts

documentProcessor.processDocument(request: {
  file_content: string,
  file_name: string,
  file_type: string,
  chunk_size: number,
  overlap: number,
  extract_qa_pairs: boolean,
  extract_tables: boolean,
  extract_images: boolean
}): Promise<ProcessingResult>

La variable d'environnement DOCUMENT_PROCESSOR_URL doit pointer vers le microservice (ex: http://localhost:8001 en local, URL interne Kubernetes en production).


Flux processUploadedFile (serveur)

apps/server/src/utils/regular-processing.ts:

  1. Valide: fileContent non vide, chunkSize > overlap.
  2. Insère un enregistrement files (status: pending) → obtient fileId.
  3. Appelle documentProcessor.processDocument(...).
  4. Si échec ou 0 chunks: supprime l'entrée files et retourne { success: false }.
  5. Insère chaque chunk dans chunks (rank, content sanitisé, category: "not categorized", fileId).
  6. Retourne { success: true, fileId, chunkCount }.

Paramètres d'input:

ParamètreTypeDefaultDescription
fileContentstringContenu base64 ou texte brut
fileNamestringNom du fichier (détermine le parser)
fileTypestring"text/plain"MIME type
uploaderIdstringID de l'utilisateur (admin)
chunkSizenumber1000Taille des chunks en caractères
overlapnumber200Chevauchement entre chunks

Flux processUploadedQA (serveur)

apps/server/src/utils/qa-processing.ts — pour les fichiers CSV Q&A:

  1. Parse le CSV (colonnes question, answer).
  2. Insère un enregistrement files (type: qa).
  3. Insère chaque ligne dans qa_pair (rank, question, answer, category: "not categorized").

Le microservice document-processor n'est pas utilisé pour les QA (parsing interne direct).


Variables d'environnement serveur liées au parsing

VariableDescriptionExemple
DOCUMENT_PROCESSOR_URLURL du microservice document-processorhttp://doc-processor:8001
INDEX_API_URLURL de l'API d'index FAISS (chatbot)http://chatbot-index:8502

Configuration Docling (microservice)

VariableDescriptionDéfaut
DOCLING_MAX_TOKENSNombre max de tokens par chunk512
DOCLING_TOKENIZER_MODELModèle de tokenizer (Mistral)mistralai/Mistral-7B-v0.1
DOCLING_ENABLE_OCRActiver l'OCRtrue
DOCLING_OCR_ENGINEMoteur OCR (easyocr, rapidocr, tesseract-cli, tesserocr)easyocr
DOCLING_OCR_LANGUAGESLangues OCR (séparées par virgule)en,fr
DOCLING_TABLE_MODEMode table (fast, accurate)accurate
DOCLING_LAYOUT_MODELModèle layout (heron, egret_large, egret_xlarge)heron
DOCLING_NUM_THREADSNombre de threads4
DOCLING_DEVICEDevice (auto, cpu, cuda)auto
DOCLING_ENABLE_PICTURE_DESCRIPTIONActiver description VLM images (coûteux)false
DOCLING_PICTURE_DESCRIPTION_PRESETPreset VLM (granite_vision, smolvlm, pixtral, qwen)granite_vision
DOCLING_ENABLE_CODE_ENRICHMENTActiver enrichissement codefalse
DOCLING_ENABLE_FORMULA_ENRICHMENTActiver enrichissement formulesfalse
DOCLING_ENABLED_FORMATSFormats activés (séparés par virgule)pdf,docx,pptx,...