{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Serialization"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Overview"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this notebook we showcase the usage of Docling [serializers](../../concepts/serialization)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Setup"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Note: you may need to restart the kernel to use updated packages.\n"
     ]
    }
   ],
   "source": [
    "%pip install -qU pip docling docling-core~=2.29 rich"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "DOC_SOURCE = \"https://arxiv.org/pdf/2311.18481\"\n",
    "\n",
    "# we set some start-stop cues for defining an excerpt to print\n",
    "start_cue = \"Copyright © 2024\"\n",
    "stop_cue = \"Application of NLP to ESG\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "from rich.console import Console\n",
    "from rich.panel import Panel\n",
    "\n",
    "console = Console(width=210)  # for preventing Markdown table wrapped rendering\n",
    "\n",
    "\n",
    "def print_in_console(text):\n",
    "    console.print(Panel(text))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Basic usage"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We first convert the document:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/pva/work/github.com/DS4SD/docling/.venv/lib/python3.13/site-packages/torch/utils/data/dataloader.py:683: UserWarning: 'pin_memory' argument is set as true but not supported on MPS now, then device pinned memory won't be used.\n",
      "  warnings.warn(warn_msg)\n"
     ]
    }
   ],
   "source": [
    "from docling.document_converter import DocumentConverter\n",
    "\n",
    "converter = DocumentConverter()\n",
    "doc = converter.convert(source=DOC_SOURCE).document"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can now apply any `BaseDocSerializer` on the produced document.\n",
    "\n",
    "👉 Note that, to keep the shown output brief, we only print an excerpt.\n",
    "\n",
    "E.g. below we apply an `HTMLDocSerializer`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">╭────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮\n",
       "│ Copyright © 2024, Association for the Advancement of Artificial Intelligence (www.aaai.org). All rights reserved.&lt;/p&gt;                                                                                          │\n",
       "│ &lt;table&gt;&lt;tbody&gt;&lt;tr&gt;&lt;th&gt;Report&lt;/th&gt;&lt;th&gt;Question&lt;/th&gt;&lt;th&gt;Answer&lt;/th&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;IBM 2022&lt;/td&gt;&lt;td&gt;How many hours were spent on employee learning in 2021?&lt;/td&gt;&lt;td&gt;22.5 million hours&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;IBM         │\n",
       "│ 2022&lt;/td&gt;&lt;td&gt;What was the rate of fatalities in 2021?&lt;/td&gt;&lt;td&gt;The rate of fatalities in 2021 was 0.0016.&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;IBM 2022&lt;/td&gt;&lt;td&gt;How many full audits were con- ducted in 2022 in                    │\n",
       "│ India?&lt;/td&gt;&lt;td&gt;2&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;Starbucks 2022&lt;/td&gt;&lt;td&gt;What is the percentage of women in the Board of Directors?&lt;/td&gt;&lt;td&gt;25%&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;Starbucks 2022&lt;/td&gt;&lt;td&gt;What was the total energy con-         │\n",
       "│ sumption in 2021?&lt;/td&gt;&lt;td&gt;According to the table, the total energy consumption in 2021 was 2,491,543 MWh.&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;Starbucks 2022&lt;/td&gt;&lt;td&gt;How much packaging material was made from renewable mate-    │\n",
       "│ rials?&lt;/td&gt;&lt;td&gt;According to the given data, 31% of packaging materials were made from recycled or renewable materials in FY22.&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;                                                       │\n",
       "│ &lt;p&gt;Table 1: Example question answers from the ESG reports of IBM and Starbucks using Deep Search DocQA system.&lt;/p&gt;                                                                                             │\n",
       "│ &lt;p&gt;ESG report in our library via our QA conversational assistant. Our assistant generates answers and also presents the information (paragraph or table), in the ESG report, from which it has generated the   │\n",
       "│ response.&lt;/p&gt;                                                                                                                                                                                                  │\n",
       "│ &lt;h2&gt;Related Work&lt;/h2&gt;                                                                                                                                                                                          │\n",
       "│ &lt;p&gt;The DocQA integrates multiple AI technologies, namely:&lt;/p&gt;                                                                                                                                                  │\n",
       "│ &lt;p&gt;Document Conversion: Converting unstructured documents, such as PDF files, into a machine-readable format is a challenging task in AI. Early strategies for document conversion were based on geometric     │\n",
       "│ layout analysis (Cattoni et al. 2000; Breuel 2002). Thanks to the availability of large annotated datasets (PubLayNet (Zhong et al. 2019), DocBank (Li et al. 2020), DocLayNet (Pfitzmann et al. 2022; Auer et │\n",
       "│ al. 2023), deep learning-based methods are routinely used. Modern approaches for recovering the structure of a document can be broadly divided into two categories: image-based or PDF representation-based .  │\n",
       "│ Imagebased methods usually employ Transformer or CNN architectures on the images of pages (Zhang et al. 2023; Li et al. 2022; Huang et al. 2022). On the other hand, deep learning-&lt;/p&gt;                        │\n",
       "│ &lt;figure&gt;&lt;figcaption&gt;Figure 1: System architecture: Simplified sketch of document question-answering pipeline.&lt;/figcaption&gt;&lt;/figure&gt;                                                                            │\n",
       "│ &lt;p&gt;based language processing methods are applied on the native PDF content (generated by a single PDF printing command) (Auer et al. 2022; Livathinos et al. 2021; Staar et al. 2018).&lt;/p&gt;                     │\n",
       "│ &lt;p&gt;                                                                                                                                                                                                            │\n",
       "╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\n",
       "</pre>\n"
      ],
      "text/plain": [
       "╭────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮\n",
       "│ Copyright © 2024, Association for the Advancement of Artificial Intelligence (www.aaai.org). All rights reserved.</p>                                                                                          │\n",
       "│ <table><tbody><tr><th>Report</th><th>Question</th><th>Answer</th></tr><tr><td>IBM 2022</td><td>How many hours were spent on employee learning in 2021?</td><td>22.5 million hours</td></tr><tr><td>IBM         │\n",
       "│ 2022</td><td>What was the rate of fatalities in 2021?</td><td>The rate of fatalities in 2021 was 0.0016.</td></tr><tr><td>IBM 2022</td><td>How many full audits were con- ducted in 2022 in                    │\n",
       "│ India?</td><td>2</td></tr><tr><td>Starbucks 2022</td><td>What is the percentage of women in the Board of Directors?</td><td>25%</td></tr><tr><td>Starbucks 2022</td><td>What was the total energy con-         │\n",
       "│ sumption in 2021?</td><td>According to the table, the total energy consumption in 2021 was 2,491,543 MWh.</td></tr><tr><td>Starbucks 2022</td><td>How much packaging material was made from renewable mate-    │\n",
       "│ rials?</td><td>According to the given data, 31% of packaging materials were made from recycled or renewable materials in FY22.</td></tr></tbody></table>                                                       │\n",
       "│ <p>Table 1: Example question answers from the ESG reports of IBM and Starbucks using Deep Search DocQA system.</p>                                                                                             │\n",
       "│ <p>ESG report in our library via our QA conversational assistant. Our assistant generates answers and also presents the information (paragraph or table), in the ESG report, from which it has generated the   │\n",
       "│ response.</p>                                                                                                                                                                                                  │\n",
       "│ <h2>Related Work</h2>                                                                                                                                                                                          │\n",
       "│ <p>The DocQA integrates multiple AI technologies, namely:</p>                                                                                                                                                  │\n",
       "│ <p>Document Conversion: Converting unstructured documents, such as PDF files, into a machine-readable format is a challenging task in AI. Early strategies for document conversion were based on geometric     │\n",
       "│ layout analysis (Cattoni et al. 2000; Breuel 2002). Thanks to the availability of large annotated datasets (PubLayNet (Zhong et al. 2019), DocBank (Li et al. 2020), DocLayNet (Pfitzmann et al. 2022; Auer et │\n",
       "│ al. 2023), deep learning-based methods are routinely used. Modern approaches for recovering the structure of a document can be broadly divided into two categories: image-based or PDF representation-based .  │\n",
       "│ Imagebased methods usually employ Transformer or CNN architectures on the images of pages (Zhang et al. 2023; Li et al. 2022; Huang et al. 2022). On the other hand, deep learning-</p>                        │\n",
       "│ <figure><figcaption>Figure 1: System architecture: Simplified sketch of document question-answering pipeline.</figcaption></figure>                                                                            │\n",
       "│ <p>based language processing methods are applied on the native PDF content (generated by a single PDF printing command) (Auer et al. 2022; Livathinos et al. 2021; Staar et al. 2018).</p>                     │\n",
       "│ <p>                                                                                                                                                                                                            │\n",
       "╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\n"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from docling_core.transforms.serializer.html import HTMLDocSerializer\n",
    "\n",
    "serializer = HTMLDocSerializer(doc=doc)\n",
    "ser_result = serializer.serialize()\n",
    "ser_text = ser_result.text\n",
    "\n",
    "# we here only print an excerpt to keep the output brief:\n",
    "print_in_console(ser_text[ser_text.find(start_cue) : ser_text.find(stop_cue)])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the following example, we use a `MarkdownDocSerializer`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">╭────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮\n",
       "│ Copyright © 2024, Association for the Advancement of Artificial Intelligence (www.aaai.org). All rights reserved.                                                                                              │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ | Report         | Question                                                         | Answer                                                                                                          |        │\n",
       "│ |----------------|------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------|        │\n",
       "│ | IBM 2022       | How many hours were spent on employee learning in 2021?          | 22.5 million hours                                                                                              |        │\n",
       "│ | IBM 2022       | What was the rate of fatalities in 2021?                         | The rate of fatalities in 2021 was 0.0016.                                                                      |        │\n",
       "│ | IBM 2022       | How many full audits were con- ducted in 2022 in India?          | 2                                                                                                               |        │\n",
       "│ | Starbucks 2022 | What is the percentage of women in the Board of Directors?       | 25%                                                                                                             |        │\n",
       "│ | Starbucks 2022 | What was the total energy con- sumption in 2021?                 | According to the table, the total energy consumption in 2021 was 2,491,543 MWh.                                 |        │\n",
       "│ | Starbucks 2022 | How much packaging material was made from renewable mate- rials? | According to the given data, 31% of packaging materials were made from recycled or renewable materials in FY22. |        │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ Table 1: Example question answers from the ESG reports of IBM and Starbucks using Deep Search DocQA system.                                                                                                    │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ ESG report in our library via our QA conversational assistant. Our assistant generates answers and also presents the information (paragraph or table), in the ESG report, from which it has generated the      │\n",
       "│ response.                                                                                                                                                                                                      │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ ## Related Work                                                                                                                                                                                                │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ The DocQA integrates multiple AI technologies, namely:                                                                                                                                                         │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ Document Conversion: Converting unstructured documents, such as PDF files, into a machine-readable format is a challenging task in AI. Early strategies for document conversion were based on geometric layout │\n",
       "│ analysis (Cattoni et al. 2000; Breuel 2002). Thanks to the availability of large annotated datasets (PubLayNet (Zhong et al. 2019), DocBank (Li et al. 2020), DocLayNet (Pfitzmann et al. 2022; Auer et al.    │\n",
       "│ 2023), deep learning-based methods are routinely used. Modern approaches for recovering the structure of a document can be broadly divided into two categories: image-based or PDF representation-based .      │\n",
       "│ Imagebased methods usually employ Transformer or CNN architectures on the images of pages (Zhang et al. 2023; Li et al. 2022; Huang et al. 2022). On the other hand, deep learning-                            │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ Figure 1: System architecture: Simplified sketch of document question-answering pipeline.                                                                                                                      │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ &lt;!-- image --&gt;                                                                                                                                                                                                 │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ based language processing methods are applied on the native PDF content (generated by a single PDF printing command) (Auer et al. 2022; Livathinos et al. 2021; Staar et al. 2018).                            │\n",
       "│                                                                                                                                                                                                                │\n",
       "│                                                                                                                                                                                                                │\n",
       "╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\n",
       "</pre>\n"
      ],
      "text/plain": [
       "╭────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮\n",
       "│ Copyright © 2024, Association for the Advancement of Artificial Intelligence (www.aaai.org). All rights reserved.                                                                                              │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ | Report         | Question                                                         | Answer                                                                                                          |        │\n",
       "│ |----------------|------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------|        │\n",
       "│ | IBM 2022       | How many hours were spent on employee learning in 2021?          | 22.5 million hours                                                                                              |        │\n",
       "│ | IBM 2022       | What was the rate of fatalities in 2021?                         | The rate of fatalities in 2021 was 0.0016.                                                                      |        │\n",
       "│ | IBM 2022       | How many full audits were con- ducted in 2022 in India?          | 2                                                                                                               |        │\n",
       "│ | Starbucks 2022 | What is the percentage of women in the Board of Directors?       | 25%                                                                                                             |        │\n",
       "│ | Starbucks 2022 | What was the total energy con- sumption in 2021?                 | According to the table, the total energy consumption in 2021 was 2,491,543 MWh.                                 |        │\n",
       "│ | Starbucks 2022 | How much packaging material was made from renewable mate- rials? | According to the given data, 31% of packaging materials were made from recycled or renewable materials in FY22. |        │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ Table 1: Example question answers from the ESG reports of IBM and Starbucks using Deep Search DocQA system.                                                                                                    │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ ESG report in our library via our QA conversational assistant. Our assistant generates answers and also presents the information (paragraph or table), in the ESG report, from which it has generated the      │\n",
       "│ response.                                                                                                                                                                                                      │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ ## Related Work                                                                                                                                                                                                │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ The DocQA integrates multiple AI technologies, namely:                                                                                                                                                         │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ Document Conversion: Converting unstructured documents, such as PDF files, into a machine-readable format is a challenging task in AI. Early strategies for document conversion were based on geometric layout │\n",
       "│ analysis (Cattoni et al. 2000; Breuel 2002). Thanks to the availability of large annotated datasets (PubLayNet (Zhong et al. 2019), DocBank (Li et al. 2020), DocLayNet (Pfitzmann et al. 2022; Auer et al.    │\n",
       "│ 2023), deep learning-based methods are routinely used. Modern approaches for recovering the structure of a document can be broadly divided into two categories: image-based or PDF representation-based .      │\n",
       "│ Imagebased methods usually employ Transformer or CNN architectures on the images of pages (Zhang et al. 2023; Li et al. 2022; Huang et al. 2022). On the other hand, deep learning-                            │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ Figure 1: System architecture: Simplified sketch of document question-answering pipeline.                                                                                                                      │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ <!-- image -->                                                                                                                                                                                                 │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ based language processing methods are applied on the native PDF content (generated by a single PDF printing command) (Auer et al. 2022; Livathinos et al. 2021; Staar et al. 2018).                            │\n",
       "│                                                                                                                                                                                                                │\n",
       "│                                                                                                                                                                                                                │\n",
       "╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\n"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from docling_core.transforms.serializer.markdown import MarkdownDocSerializer\n",
    "\n",
    "serializer = MarkdownDocSerializer(doc=doc)\n",
    "ser_result = serializer.serialize()\n",
    "ser_text = ser_result.text\n",
    "\n",
    "print_in_console(ser_text[ser_text.find(start_cue) : ser_text.find(stop_cue)])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Configuring a serializer"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's now assume we would like to reconfigure the Markdown serialization such that:\n",
    "- it uses a different component serializer, e.g. if we'd prefer tables to be printed in a triplet format (which could potentially improve the vector representation compared to Markdown tables)\n",
    "- it uses specific user-defined parameters, e.g. if we'd prefer a different image placeholder text than the default one\n",
    "\n",
    "Check out the following configuration and notice the serialization differences in the output further below:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">╭────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮\n",
       "│ Copyright © 2024, Association for the Advancement of Artificial Intelligence (www.aaai.org). All rights reserved.                                                                                              │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ IBM 2022, Question = How many hours were spent on employee learning in 2021?. IBM 2022, Answer = 22.5 million hours. IBM 2022, Question = What was the rate of fatalities in 2021?. IBM 2022, Answer = The     │\n",
       "│ rate of fatalities in 2021 was 0.0016.. IBM 2022, Question = How many full audits were con- ducted in 2022 in India?. IBM 2022, Answer = 2. Starbucks 2022, Question = What is the percentage of women in the  │\n",
       "│ Board of Directors?. Starbucks 2022, Answer = 25%. Starbucks 2022, Question = What was the total energy con- sumption in 2021?. Starbucks 2022, Answer = According to the table, the total energy consumption  │\n",
       "│ in 2021 was 2,491,543 MWh.. Starbucks 2022, Question = How much packaging material was made from renewable mate- rials?. Starbucks 2022, Answer = According to the given data, 31% of packaging materials were │\n",
       "│ made from recycled or renewable materials in FY22.                                                                                                                                                             │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ Table 1: Example question answers from the ESG reports of IBM and Starbucks using Deep Search DocQA system.                                                                                                    │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ ESG report in our library via our QA conversational assistant. Our assistant generates answers and also presents the information (paragraph or table), in the ESG report, from which it has generated the      │\n",
       "│ response.                                                                                                                                                                                                      │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ ## Related Work                                                                                                                                                                                                │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ The DocQA integrates multiple AI technologies, namely:                                                                                                                                                         │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ Document Conversion: Converting unstructured documents, such as PDF files, into a machine-readable format is a challenging task in AI. Early strategies for document conversion were based on geometric layout │\n",
       "│ analysis (Cattoni et al. 2000; Breuel 2002). Thanks to the availability of large annotated datasets (PubLayNet (Zhong et al. 2019), DocBank (Li et al. 2020), DocLayNet (Pfitzmann et al. 2022; Auer et al.    │\n",
       "│ 2023), deep learning-based methods are routinely used. Modern approaches for recovering the structure of a document can be broadly divided into two categories: image-based or PDF representation-based .      │\n",
       "│ Imagebased methods usually employ Transformer or CNN architectures on the images of pages (Zhang et al. 2023; Li et al. 2022; Huang et al. 2022). On the other hand, deep learning-                            │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ Figure 1: System architecture: Simplified sketch of document question-answering pipeline.                                                                                                                      │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ &lt;!-- demo picture placeholder --&gt;                                                                                                                                                                              │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ based language processing methods are applied on the native PDF content (generated by a single PDF printing command) (Auer et al. 2022; Livathinos et al. 2021; Staar et al. 2018).                            │\n",
       "│                                                                                                                                                                                                                │\n",
       "│                                                                                                                                                                                                                │\n",
       "╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\n",
       "</pre>\n"
      ],
      "text/plain": [
       "╭────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮\n",
       "│ Copyright © 2024, Association for the Advancement of Artificial Intelligence (www.aaai.org). All rights reserved.                                                                                              │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ IBM 2022, Question = How many hours were spent on employee learning in 2021?. IBM 2022, Answer = 22.5 million hours. IBM 2022, Question = What was the rate of fatalities in 2021?. IBM 2022, Answer = The     │\n",
       "│ rate of fatalities in 2021 was 0.0016.. IBM 2022, Question = How many full audits were con- ducted in 2022 in India?. IBM 2022, Answer = 2. Starbucks 2022, Question = What is the percentage of women in the  │\n",
       "│ Board of Directors?. Starbucks 2022, Answer = 25%. Starbucks 2022, Question = What was the total energy con- sumption in 2021?. Starbucks 2022, Answer = According to the table, the total energy consumption  │\n",
       "│ in 2021 was 2,491,543 MWh.. Starbucks 2022, Question = How much packaging material was made from renewable mate- rials?. Starbucks 2022, Answer = According to the given data, 31% of packaging materials were │\n",
       "│ made from recycled or renewable materials in FY22.                                                                                                                                                             │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ Table 1: Example question answers from the ESG reports of IBM and Starbucks using Deep Search DocQA system.                                                                                                    │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ ESG report in our library via our QA conversational assistant. Our assistant generates answers and also presents the information (paragraph or table), in the ESG report, from which it has generated the      │\n",
       "│ response.                                                                                                                                                                                                      │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ ## Related Work                                                                                                                                                                                                │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ The DocQA integrates multiple AI technologies, namely:                                                                                                                                                         │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ Document Conversion: Converting unstructured documents, such as PDF files, into a machine-readable format is a challenging task in AI. Early strategies for document conversion were based on geometric layout │\n",
       "│ analysis (Cattoni et al. 2000; Breuel 2002). Thanks to the availability of large annotated datasets (PubLayNet (Zhong et al. 2019), DocBank (Li et al. 2020), DocLayNet (Pfitzmann et al. 2022; Auer et al.    │\n",
       "│ 2023), deep learning-based methods are routinely used. Modern approaches for recovering the structure of a document can be broadly divided into two categories: image-based or PDF representation-based .      │\n",
       "│ Imagebased methods usually employ Transformer or CNN architectures on the images of pages (Zhang et al. 2023; Li et al. 2022; Huang et al. 2022). On the other hand, deep learning-                            │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ Figure 1: System architecture: Simplified sketch of document question-answering pipeline.                                                                                                                      │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ <!-- demo picture placeholder -->                                                                                                                                                                              │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ based language processing methods are applied on the native PDF content (generated by a single PDF printing command) (Auer et al. 2022; Livathinos et al. 2021; Staar et al. 2018).                            │\n",
       "│                                                                                                                                                                                                                │\n",
       "│                                                                                                                                                                                                                │\n",
       "╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\n"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from docling_core.transforms.chunker.hierarchical_chunker import TripletTableSerializer\n",
    "from docling_core.transforms.serializer.markdown import MarkdownParams\n",
    "\n",
    "serializer = MarkdownDocSerializer(\n",
    "    doc=doc,\n",
    "    table_serializer=TripletTableSerializer(),\n",
    "    params=MarkdownParams(\n",
    "        image_placeholder=\"<!-- demo picture placeholder -->\",\n",
    "        # ...\n",
    "    ),\n",
    ")\n",
    "ser_result = serializer.serialize()\n",
    "ser_text = ser_result.text\n",
    "\n",
    "print_in_console(ser_text[ser_text.find(start_cue) : ser_text.find(stop_cue)])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Creating a custom serializer"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the examples above, we were able to reuse existing implementations for our desired\n",
    "serialization strategy, but let's now assume we want to define a custom serialization\n",
    "logic, e.g. we would like picture serialization to include any available picture\n",
    "description (captioning) annotations.\n",
    "\n",
    "To that end, we first need to revisit our conversion and include all pipeline options\n",
    "needed for\n",
    "[picture description enrichment](https://docling-project.github.io/docling/usage/enrichments/#picture-description)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/pva/work/github.com/DS4SD/docling/.venv/lib/python3.13/site-packages/torch/utils/data/dataloader.py:683: UserWarning: 'pin_memory' argument is set as true but not supported on MPS now, then device pinned memory won't be used.\n",
      "  warnings.warn(warn_msg)\n"
     ]
    }
   ],
   "source": [
    "from docling.datamodel.base_models import InputFormat\n",
    "from docling.datamodel.pipeline_options import (\n",
    "    PdfPipelineOptions,\n",
    "    PictureDescriptionVlmOptions,\n",
    ")\n",
    "from docling.document_converter import DocumentConverter, PdfFormatOption\n",
    "\n",
    "pipeline_options = PdfPipelineOptions(\n",
    "    do_picture_description=True,\n",
    "    picture_description_options=PictureDescriptionVlmOptions(\n",
    "        repo_id=\"HuggingFaceTB/SmolVLM-256M-Instruct\",\n",
    "        prompt=\"Describe this picture in three to five sentences. Be precise and concise.\",\n",
    "    ),\n",
    "    generate_picture_images=True,\n",
    "    images_scale=2,\n",
    ")\n",
    "\n",
    "converter = DocumentConverter(\n",
    "    format_options={InputFormat.PDF: PdfFormatOption(pipeline_options=pipeline_options)}\n",
    ")\n",
    "doc = converter.convert(source=DOC_SOURCE).document"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can then define our custom picture serializer:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import Any, Optional\n",
    "\n",
    "from docling_core.transforms.serializer.base import (\n",
    "    BaseDocSerializer,\n",
    "    SerializationResult,\n",
    ")\n",
    "from docling_core.transforms.serializer.common import create_ser_result\n",
    "from docling_core.transforms.serializer.markdown import (\n",
    "    MarkdownParams,\n",
    "    MarkdownPictureSerializer,\n",
    ")\n",
    "from docling_core.types.doc.document import (\n",
    "    DoclingDocument,\n",
    "    ImageRefMode,\n",
    "    PictureDescriptionData,\n",
    "    PictureItem,\n",
    ")\n",
    "from typing_extensions import override\n",
    "\n",
    "\n",
    "class AnnotationPictureSerializer(MarkdownPictureSerializer):\n",
    "    @override\n",
    "    def serialize(\n",
    "        self,\n",
    "        *,\n",
    "        item: PictureItem,\n",
    "        doc_serializer: BaseDocSerializer,\n",
    "        doc: DoclingDocument,\n",
    "        separator: Optional[str] = None,\n",
    "        **kwargs: Any,\n",
    "    ) -> SerializationResult:\n",
    "        text_parts: list[str] = []\n",
    "\n",
    "        # reusing the existing result:\n",
    "        parent_res = super().serialize(\n",
    "            item=item,\n",
    "            doc_serializer=doc_serializer,\n",
    "            doc=doc,\n",
    "            **kwargs,\n",
    "        )\n",
    "        text_parts.append(parent_res.text)\n",
    "\n",
    "        # appending annotations:\n",
    "        for annotation in item.annotations:\n",
    "            if isinstance(annotation, PictureDescriptionData):\n",
    "                text_parts.append(f\"<!-- Picture description: {annotation.text} -->\")\n",
    "\n",
    "        text_res = (separator or \"\\n\").join(text_parts)\n",
    "        return create_ser_result(text=text_res, span_source=item)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Last but not least, we define a new doc serializer which leverages our custom picture\n",
    "serializer.\n",
    "\n",
    "Notice the picture description annotations in the output below:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">╭────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮\n",
       "│ Copyright © 2024, Association for the Advancement of Artificial Intelligence (www.aaai.org). All rights reserved.                                                                                              │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ | Report         | Question                                                         | Answer                                                                                                          |        │\n",
       "│ |----------------|------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------|        │\n",
       "│ | IBM 2022       | How many hours were spent on employee learning in 2021?          | 22.5 million hours                                                                                              |        │\n",
       "│ | IBM 2022       | What was the rate of fatalities in 2021?                         | The rate of fatalities in 2021 was 0.0016.                                                                      |        │\n",
       "│ | IBM 2022       | How many full audits were con- ducted in 2022 in India?          | 2                                                                                                               |        │\n",
       "│ | Starbucks 2022 | What is the percentage of women in the Board of Directors?       | 25%                                                                                                             |        │\n",
       "│ | Starbucks 2022 | What was the total energy con- sumption in 2021?                 | According to the table, the total energy consumption in 2021 was 2,491,543 MWh.                                 |        │\n",
       "│ | Starbucks 2022 | How much packaging material was made from renewable mate- rials? | According to the given data, 31% of packaging materials were made from recycled or renewable materials in FY22. |        │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ Table 1: Example question answers from the ESG reports of IBM and Starbucks using Deep Search DocQA system.                                                                                                    │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ ESG report in our library via our QA conversational assistant. Our assistant generates answers and also presents the information (paragraph or table), in the ESG report, from which it has generated the      │\n",
       "│ response.                                                                                                                                                                                                      │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ ## Related Work                                                                                                                                                                                                │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ The DocQA integrates multiple AI technologies, namely:                                                                                                                                                         │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ Document Conversion: Converting unstructured documents, such as PDF files, into a machine-readable format is a challenging task in AI. Early strategies for document conversion were based on geometric layout │\n",
       "│ analysis (Cattoni et al. 2000; Breuel 2002). Thanks to the availability of large annotated datasets (PubLayNet (Zhong et al. 2019), DocBank (Li et al. 2020), DocLayNet (Pfitzmann et al. 2022; Auer et al.    │\n",
       "│ 2023), deep learning-based methods are routinely used. Modern approaches for recovering the structure of a document can be broadly divided into two categories: image-based or PDF representation-based .      │\n",
       "│ Imagebased methods usually employ Transformer or CNN architectures on the images of pages (Zhang et al. 2023; Li et al. 2022; Huang et al. 2022). On the other hand, deep learning-                            │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ Figure 1: System architecture: Simplified sketch of document question-answering pipeline.                                                                                                                      │\n",
       "│ &lt;!-- Picture description: The image depicts a document conversion process. It is a sequence of steps that includes document conversion, information retrieval, and response generation. The document           │\n",
       "│ conversion step involves converting the document from a text format to a markdown format. The information retrieval step involves retrieving the document from a database or other source. The response        │\n",
       "│ generation step involves generating a response from the information retrieval step. --&gt;                                                                                                                        │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ based language processing methods are applied on the native PDF content (generated by a single PDF printing command) (Auer et al. 2022; Livathinos et al. 2021; Staar et al. 2018).                            │\n",
       "│                                                                                                                                                                                                                │\n",
       "│                                                                                                                                                                                                                │\n",
       "╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\n",
       "</pre>\n"
      ],
      "text/plain": [
       "╭────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮\n",
       "│ Copyright © 2024, Association for the Advancement of Artificial Intelligence (www.aaai.org). All rights reserved.                                                                                              │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ | Report         | Question                                                         | Answer                                                                                                          |        │\n",
       "│ |----------------|------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------|        │\n",
       "│ | IBM 2022       | How many hours were spent on employee learning in 2021?          | 22.5 million hours                                                                                              |        │\n",
       "│ | IBM 2022       | What was the rate of fatalities in 2021?                         | The rate of fatalities in 2021 was 0.0016.                                                                      |        │\n",
       "│ | IBM 2022       | How many full audits were con- ducted in 2022 in India?          | 2                                                                                                               |        │\n",
       "│ | Starbucks 2022 | What is the percentage of women in the Board of Directors?       | 25%                                                                                                             |        │\n",
       "│ | Starbucks 2022 | What was the total energy con- sumption in 2021?                 | According to the table, the total energy consumption in 2021 was 2,491,543 MWh.                                 |        │\n",
       "│ | Starbucks 2022 | How much packaging material was made from renewable mate- rials? | According to the given data, 31% of packaging materials were made from recycled or renewable materials in FY22. |        │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ Table 1: Example question answers from the ESG reports of IBM and Starbucks using Deep Search DocQA system.                                                                                                    │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ ESG report in our library via our QA conversational assistant. Our assistant generates answers and also presents the information (paragraph or table), in the ESG report, from which it has generated the      │\n",
       "│ response.                                                                                                                                                                                                      │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ ## Related Work                                                                                                                                                                                                │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ The DocQA integrates multiple AI technologies, namely:                                                                                                                                                         │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ Document Conversion: Converting unstructured documents, such as PDF files, into a machine-readable format is a challenging task in AI. Early strategies for document conversion were based on geometric layout │\n",
       "│ analysis (Cattoni et al. 2000; Breuel 2002). Thanks to the availability of large annotated datasets (PubLayNet (Zhong et al. 2019), DocBank (Li et al. 2020), DocLayNet (Pfitzmann et al. 2022; Auer et al.    │\n",
       "│ 2023), deep learning-based methods are routinely used. Modern approaches for recovering the structure of a document can be broadly divided into two categories: image-based or PDF representation-based .      │\n",
       "│ Imagebased methods usually employ Transformer or CNN architectures on the images of pages (Zhang et al. 2023; Li et al. 2022; Huang et al. 2022). On the other hand, deep learning-                            │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ Figure 1: System architecture: Simplified sketch of document question-answering pipeline.                                                                                                                      │\n",
       "│ <!-- Picture description: The image depicts a document conversion process. It is a sequence of steps that includes document conversion, information retrieval, and response generation. The document           │\n",
       "│ conversion step involves converting the document from a text format to a markdown format. The information retrieval step involves retrieving the document from a database or other source. The response        │\n",
       "│ generation step involves generating a response from the information retrieval step. -->                                                                                                                        │\n",
       "│                                                                                                                                                                                                                │\n",
       "│ based language processing methods are applied on the native PDF content (generated by a single PDF printing command) (Auer et al. 2022; Livathinos et al. 2021; Staar et al. 2018).                            │\n",
       "│                                                                                                                                                                                                                │\n",
       "│                                                                                                                                                                                                                │\n",
       "╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\n"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "serializer = MarkdownDocSerializer(\n",
    "    doc=doc,\n",
    "    picture_serializer=AnnotationPictureSerializer(),\n",
    "    params=MarkdownParams(\n",
    "        image_mode=ImageRefMode.PLACEHOLDER,\n",
    "        image_placeholder=\"\",\n",
    "    ),\n",
    ")\n",
    "ser_result = serializer.serialize()\n",
    "ser_text = ser_result.text\n",
    "\n",
    "print_in_console(ser_text[ser_text.find(start_cue) : ser_text.find(stop_cue)])"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
