Merge branch 'main' into docx-markdown-formatting

This commit is contained in:
SimJeg 2025-03-31 10:56:32 +02:00
commit 806a090e65
20 changed files with 1149 additions and 339 deletions

View File

@ -37,10 +37,10 @@ class HTMLDocumentBackend(DeclarativeDocumentBackend):
try:
if isinstance(self.path_or_stream, BytesIO):
text_stream = self.path_or_stream.getvalue().decode("utf-8")
text_stream = self.path_or_stream.getvalue()
self.soup = BeautifulSoup(text_stream, "html.parser")
if isinstance(self.path_or_stream, Path):
with open(self.path_or_stream, "r", encoding="utf-8") as f:
with open(self.path_or_stream, "rb") as f:
html_content = f.read()
self.soup = BeautifulSoup(html_content, "html.parser")
except Exception as e:

View File

@ -16,7 +16,7 @@ from docling_core.types.doc import (
TableCell,
TableData,
)
from PIL import Image
from PIL import Image, UnidentifiedImageError
from pptx import Presentation
from pptx.enum.shapes import MSO_SHAPE_TYPE, PP_PLACEHOLDER
@ -120,6 +120,7 @@ class MsPowerpointDocumentBackend(DeclarativeDocumentBackend, PaginatedDocumentB
bullet_type = "None"
list_text = ""
list_label = GroupLabel.LIST
doc_label = DocItemLabel.LIST_ITEM
prov = self.generate_prov(shape, slide_ind, shape.text.strip())
# Identify if shape contains lists
@ -276,6 +277,7 @@ class MsPowerpointDocumentBackend(DeclarativeDocumentBackend, PaginatedDocumentB
im_dpi, _ = image.dpi
# Open it with PIL
try:
pil_image = Image.open(BytesIO(image_bytes))
# shape has picture
@ -286,6 +288,8 @@ class MsPowerpointDocumentBackend(DeclarativeDocumentBackend, PaginatedDocumentB
caption=None,
prov=prov,
)
except (UnidentifiedImageError, OSError) as e:
_log.warning(f"Warning: image cannot be loaded by Pillow: {e}")
return
def handle_tables(self, shape, parent_slide, slide_ind, doc):

View File

@ -164,6 +164,11 @@ def convert(
to_formats: List[OutputFormat] = typer.Option(
None, "--to", help="Specify output formats. Defaults to Markdown."
),
headers: str = typer.Option(
None,
"--headers",
help="Specify http request headers used when fetching url input sources in the form of a JSON string",
),
image_export_mode: Annotated[
ImageRefMode,
typer.Option(
@ -279,12 +284,19 @@ def convert(
if from_formats is None:
from_formats = [e for e in InputFormat]
parsed_headers: Optional[Dict[str, str]] = None
if headers is not None:
headers_t = TypeAdapter(Dict[str, str])
parsed_headers = headers_t.validate_json(headers)
with tempfile.TemporaryDirectory() as tempdir:
input_doc_paths: List[Path] = []
for src in input_sources:
try:
# check if we can fetch some remote url
source = resolve_source_to_path(source=src, workdir=Path(tempdir))
source = resolve_source_to_path(
source=src, headers=parsed_headers, workdir=Path(tempdir)
)
input_doc_paths.append(source)
except FileNotFoundError:
err_console.print(
@ -390,7 +402,7 @@ def convert(
start_time = time.time()
conv_results = doc_converter.convert_all(
input_doc_paths, raises_on_error=abort_on_error
input_doc_paths, headers=parsed_headers, raises_on_error=abort_on_error
)
output.mkdir(parents=True, exist_ok=True)

View File

@ -227,13 +227,18 @@ class _DummyBackend(AbstractDocumentBackend):
class _DocumentConversionInput(BaseModel):
path_or_stream_iterator: Iterable[Union[Path, str, DocumentStream]]
headers: Optional[Dict[str, str]] = None
limits: Optional[DocumentLimits] = DocumentLimits()
def docs(
self, format_options: Dict[InputFormat, "FormatOption"]
) -> Iterable[InputDocument]:
for item in self.path_or_stream_iterator:
obj = resolve_source_to_stream(item) if isinstance(item, str) else item
obj = (
resolve_source_to_stream(item, self.headers)
if isinstance(item, str)
else item
)
format = self._guess_format(obj)
backend: Type[AbstractDocumentBackend]
if format not in format_options.keys():

View File

@ -176,6 +176,7 @@ class DocumentConverter:
def convert(
self,
source: Union[Path, str, DocumentStream], # TODO review naming
headers: Optional[Dict[str, str]] = None,
raises_on_error: bool = True,
max_num_pages: int = sys.maxsize,
max_file_size: int = sys.maxsize,
@ -185,6 +186,7 @@ class DocumentConverter:
raises_on_error=raises_on_error,
max_num_pages=max_num_pages,
max_file_size=max_file_size,
headers=headers,
)
return next(all_res)
@ -192,6 +194,7 @@ class DocumentConverter:
def convert_all(
self,
source: Iterable[Union[Path, str, DocumentStream]], # TODO review naming
headers: Optional[Dict[str, str]] = None,
raises_on_error: bool = True, # True: raises on first conversion error; False: does not raise on conv error
max_num_pages: int = sys.maxsize,
max_file_size: int = sys.maxsize,
@ -201,8 +204,7 @@ class DocumentConverter:
max_file_size=max_file_size,
)
conv_input = _DocumentConversionInput(
path_or_stream_iterator=source,
limits=limits,
path_or_stream_iterator=source, limits=limits, headers=headers
)
conv_res_iter = self._convert(conv_input, raises_on_error=raises_on_error)

View File

@ -4,7 +4,30 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"# Hybrid Chunking"
"# Hybrid chunking"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Overview"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Hybrid chunking applies tokenization-aware refinements on top of document-based hierarchical chunking.\n",
"\n",
"For more details, see [here](../../concepts/chunking#hybrid-chunker)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Setup"
]
},
{
@ -21,7 +44,7 @@
}
],
"source": [
"%pip install -qU 'docling-core[chunking]' sentence-transformers transformers lancedb"
"%pip install -qU 'docling-core[chunking]' sentence-transformers transformers"
]
},
{
@ -48,16 +71,12 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"## Chunking"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Notice how `tokenizer` and `embed_model` further below are single-sourced from `EMBED_MODEL_ID`.\n",
"## Chunking\n",
"\n",
"This is important for making sure the chunker and the embedding model are using the same tokenizer."
"### Basic usage\n",
"\n",
"For a basic usage scenario, we can just instantiate a `HybridChunker`, which will use\n",
"the default parameters."
]
},
{
@ -65,20 +84,102 @@
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"from docling.chunking import HybridChunker\n",
"\n",
"chunker = HybridChunker()\n",
"chunk_iter = chunker.chunk(dl_doc=doc)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note that the text you would typically want to embed is the context-enriched one as\n",
"returned by the `serialize()` method:"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"=== 0 ===\n",
"chunk.text:\n",
"'International Business Machines Corporation (using the trademark IBM), nicknamed Big Blue, is an American multinational technology company headquartered in Armonk, New York and present in over 175 countries.\\nIt is a publicly traded company and one of the 30 companies in the Dow Jones Industrial Aver…'\n",
"chunker.serialize(chunk):\n",
"'IBM\\nInternational Business Machines Corporation (using the trademark IBM), nicknamed Big Blue, is an American multinational technology company headquartered in Armonk, New York and present in over 175 countries.\\nIt is a publicly traded company and one of the 30 companies in the Dow Jones Industrial …'\n",
"\n",
"=== 1 ===\n",
"chunk.text:\n",
"'IBM originated with several technological innovations developed and commercialized in the late 19th century. Julius E. Pitrap patented the computing scale in 1885;[17] Alexander Dey invented the dial recorder (1888);[18] Herman Hollerith patented the Electric Tabulating Machine (1889);[19] and Willa…'\n",
"chunker.serialize(chunk):\n",
"'IBM\\n1910s1950s\\nIBM originated with several technological innovations developed and commercialized in the late 19th century. Julius E. Pitrap patented the computing scale in 1885;[17] Alexander Dey invented the dial recorder (1888);[18] Herman Hollerith patented the Electric Tabulating Machine (1889…'\n",
"\n",
"=== 2 ===\n",
"chunk.text:\n",
"'Collectively, the companies manufactured a wide array of machinery for sale and lease, ranging from commercial scales and industrial time recorders, meat and cheese slicers, to tabulators and punched cards. Thomas J. Watson, Sr., fired from the National Cash Register Company by John Henry Patterson,…'\n",
"chunker.serialize(chunk):\n",
"'IBM\\n1910s1950s\\nCollectively, the companies manufactured a wide array of machinery for sale and lease, ranging from commercial scales and industrial time recorders, meat and cheese slicers, to tabulators and punched cards. Thomas J. Watson, Sr., fired from the National Cash Register Company by John …'\n",
"\n",
"=== 3 ===\n",
"chunk.text:\n",
"'In 1961, IBM developed the SABRE reservation system for American Airlines and introduced the highly successful Selectric typewriter.…'\n",
"chunker.serialize(chunk):\n",
"'IBM\\n1960s1980s\\nIn 1961, IBM developed the SABRE reservation system for American Airlines and introduced the highly successful Selectric typewriter.…'\n",
"\n"
]
}
],
"source": [
"for i, chunk in enumerate(chunk_iter):\n",
" print(f\"=== {i} ===\")\n",
" print(f\"chunk.text:\\n{repr(f'{chunk.text[:300]}…')}\")\n",
"\n",
" enriched_text = chunker.serialize(chunk=chunk)\n",
" print(f\"chunker.serialize(chunk):\\n{repr(f'{enriched_text[:300]}…')}\")\n",
"\n",
" print()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Advanced usage\n",
"\n",
"For more control on the chunking, we can parametrize through the `HybridChunker`\n",
"arguments illustrated below.\n",
"\n",
"Notice how `tokenizer` and `embed_model` further below are single-sourced from\n",
"`EMBED_MODEL_ID`.\n",
"This is important for making sure the chunker and the embedding model are using the same\n",
"tokenizer."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"from transformers import AutoTokenizer\n",
"\n",
"from docling.chunking import HybridChunker\n",
"\n",
"EMBED_MODEL_ID = \"sentence-transformers/all-MiniLM-L6-v2\"\n",
"MAX_TOKENS = 64\n",
"MAX_TOKENS = 64 # set to a small number for illustrative purposes\n",
"\n",
"tokenizer = AutoTokenizer.from_pretrained(EMBED_MODEL_ID)\n",
"\n",
"chunker = HybridChunker(\n",
" tokenizer=tokenizer, # can also just pass model name instead of tokenizer instance\n",
" tokenizer=tokenizer, # instance or model name, defaults to \"sentence-transformers/all-MiniLM-L6-v2\"\n",
" max_tokens=MAX_TOKENS, # optional, by default derived from `tokenizer`\n",
" # merge_peers=True, # optional, defaults to True\n",
" merge_peers=True, # optional, defaults to True\n",
")\n",
"chunk_iter = chunker.chunk(dl_doc=doc)\n",
"chunks = list(chunk_iter)"
@ -88,7 +189,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"Points to notice:\n",
"Points to notice looking at the output chunks below:\n",
"- Where possible, we fit the limit of 64 tokens for the metadata-enriched serialization form (see chunk 2)\n",
"- Where neeeded, we stop before the limit, e.g. see cases of 63 as it would otherwise run into a comma (see chunk 6)\n",
"- Where possible, we merge undersized peer chunks (see chunk 0)\n",
@ -97,7 +198,7 @@
},
{
"cell_type": "code",
"execution_count": 4,
"execution_count": 6,
"metadata": {},
"outputs": [
{
@ -245,174 +346,6 @@
"\n",
" print()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Vector Retrieval"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...\n",
"To disable this warning, you can either:\n",
"\t- Avoid using `tokenizers` before the fork if possible\n",
"\t- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)\n"
]
}
],
"source": [
"from sentence_transformers import SentenceTransformer\n",
"\n",
"embed_model = SentenceTransformer(EMBED_MODEL_ID)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>vector</th>\n",
" <th>text</th>\n",
" <th>headings</th>\n",
" <th>captions</th>\n",
" <th>_distance</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>[-0.1269039, -0.01948185, -0.07718097, -0.1116...</td>\n",
" <td>language, and the UPC barcode. The company has...</td>\n",
" <td>[IBM]</td>\n",
" <td>None</td>\n",
" <td>1.164613</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td>[-0.10198064, 0.0055981805, -0.05095279, -0.13...</td>\n",
" <td>IBM originated with several technological inno...</td>\n",
" <td>[IBM, 1910s1950s]</td>\n",
" <td>None</td>\n",
" <td>1.245144</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td>[-0.057121325, -0.034115084, -0.018113216, -0....</td>\n",
" <td>As one of the world's oldest and largest techn...</td>\n",
" <td>[IBM]</td>\n",
" <td>None</td>\n",
" <td>1.355586</td>\n",
" </tr>\n",
" <tr>\n",
" <th>3</th>\n",
" <td>[-0.04429054, -0.058111433, -0.009330196, -0.0...</td>\n",
" <td>IBM is the largest industrial research organiz...</td>\n",
" <td>[IBM]</td>\n",
" <td>None</td>\n",
" <td>1.398617</td>\n",
" </tr>\n",
" <tr>\n",
" <th>4</th>\n",
" <td>[-0.11920792, 0.053496413, -0.042391937, -0.03...</td>\n",
" <td>Awards.[16]</td>\n",
" <td>[IBM]</td>\n",
" <td>None</td>\n",
" <td>1.446295</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" vector \\\n",
"0 [-0.1269039, -0.01948185, -0.07718097, -0.1116... \n",
"1 [-0.10198064, 0.0055981805, -0.05095279, -0.13... \n",
"2 [-0.057121325, -0.034115084, -0.018113216, -0.... \n",
"3 [-0.04429054, -0.058111433, -0.009330196, -0.0... \n",
"4 [-0.11920792, 0.053496413, -0.042391937, -0.03... \n",
"\n",
" text headings \\\n",
"0 language, and the UPC barcode. The company has... [IBM] \n",
"1 IBM originated with several technological inno... [IBM, 1910s1950s] \n",
"2 As one of the world's oldest and largest techn... [IBM] \n",
"3 IBM is the largest industrial research organiz... [IBM] \n",
"4 Awards.[16] [IBM] \n",
"\n",
" captions _distance \n",
"0 None 1.164613 \n",
"1 None 1.245144 \n",
"2 None 1.355586 \n",
"3 None 1.398617 \n",
"4 None 1.446295 "
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from pathlib import Path\n",
"from tempfile import mkdtemp\n",
"\n",
"import lancedb\n",
"\n",
"\n",
"def make_lancedb_index(db_uri, index_name, chunks, embedding_model):\n",
" db = lancedb.connect(db_uri)\n",
" data = []\n",
" for chunk in chunks:\n",
" embeddings = embedding_model.encode(chunker.serialize(chunk=chunk))\n",
" data_item = {\n",
" \"vector\": embeddings,\n",
" \"text\": chunk.text,\n",
" \"headings\": chunk.meta.headings,\n",
" \"captions\": chunk.meta.captions,\n",
" }\n",
" data.append(data_item)\n",
" tbl = db.create_table(index_name, data=data, exist_ok=True)\n",
" return tbl\n",
"\n",
"\n",
"db_uri = str(Path(mkdtemp()) / \"docling.db\")\n",
"index = make_lancedb_index(db_uri, doc.name, chunks, embed_model)\n",
"\n",
"sample_query = \"invent\"\n",
"sample_embedding = embed_model.encode(sample_query)\n",
"results = index.search(sample_embedding).limit(5)\n",
"\n",
"results.to_pandas()"
]
}
],
"metadata": {

View File

@ -14,6 +14,17 @@
"# RAG with Haystack"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"| Step | Tech | Execution | \n",
"| --- | --- | --- |\n",
"| Embedding | Hugging Face / Sentence Transformers | 💻 Local |\n",
"| Vector store | Milvus | 💻 Local |\n",
"| Gen AI | Hugging Face Inference API | 🌐 Remote | "
]
},
{
"cell_type": "markdown",
"metadata": {},
@ -26,7 +37,7 @@
"metadata": {},
"source": [
"This example leverages the\n",
"[Haystack Docling extension](https://github.com/DS4SD/docling-haystack), along with\n",
"[Haystack Docling extension](../../integrations/haystack/), along with\n",
"Milvus-based document store and retriever instances, as well as sentence-transformers\n",
"embeddings.\n",
"\n",
@ -90,6 +101,7 @@
"from docling_haystack.converter import ExportType\n",
"from dotenv import load_dotenv\n",
"\n",
"\n",
"def _get_env_from_colab_or_os(key):\n",
" try:\n",
" from google.colab import userdata\n",
@ -102,6 +114,7 @@
" pass\n",
" return os.getenv(key)\n",
"\n",
"\n",
"load_dotenv()\n",
"HF_TOKEN = _get_env_from_colab_or_os(\"HF_TOKEN\")\n",
"PATHS = [\"https://arxiv.org/pdf/2408.09869\"] # Docling Technical Report\n",

View File

@ -4,7 +4,25 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"# RAG with LangChain 🦜🔗"
"# RAG with LangChain"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"| Step | Tech | Execution | \n",
"| --- | --- | --- |\n",
"| Embedding | Hugging Face / Sentence Transformers | 💻 Local |\n",
"| Vector store | Milvus | 💻 Local |\n",
"| Gen AI | Hugging Face Inference API | 🌐 Remote |"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Setup"
]
},
{
@ -49,13 +67,6 @@
"load_dotenv()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Setup"
]
},
{
"cell_type": "markdown",
"metadata": {},
@ -85,6 +96,7 @@
"\n",
"from docling.document_converter import DocumentConverter\n",
"\n",
"\n",
"class DoclingPDFLoader(BaseLoader):\n",
"\n",
" def __init__(self, file_path: str | list[str]) -> None:\n",
@ -298,7 +310,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.4"
"version": "3.12.7"
}
},
"nbformat": 4,

View File

@ -11,7 +11,18 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"# RAG with LlamaIndex 🦙"
"# RAG with LlamaIndex"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"| Step | Tech | Execution | \n",
"| --- | --- | --- |\n",
"| Embedding | Hugging Face / Sentence Transformers | 💻 Local |\n",
"| Vector store | Milvus | 💻 Local |\n",
"| Gen AI | Hugging Face Inference API | 🌐 Remote | "
]
},
{
@ -462,7 +473,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.4"
"version": "3.12.7"
}
},
"nbformat": 4,

View File

@ -0,0 +1,752 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/DS4SD/docling/blob/main/docs/examples/rag_weaviate.ipynb)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Ag9kcX2B_atc"
},
"source": [
"# RAG with Weaviate"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"| Step | Tech | Execution | \n",
"| --- | --- | --- |\n",
"| Embedding | Open AI | 🌐 Remote |\n",
"| Vector store | Weavieate | 💻 Local |\n",
"| Gen AI | Open AI | 🌐 Remote |\n",
"\n",
"## A recipe 🧑‍🍳 🐥 💚\n",
"\n",
"This is a code recipe that uses [Weaviate](https://weaviate.io/) to perform RAG over PDF documents parsed by [Docling](https://ds4sd.github.io/docling/).\n",
"\n",
"In this notebook, we accomplish the following:\n",
"* Parse the top machine learning papers on [arXiv](https://arxiv.org/) using Docling\n",
"* Perform hierarchical chunking of the documents using Docling\n",
"* Generate text embeddings with OpenAI\n",
"* Perform RAG using [Weaviate](https://weaviate.io/developers/weaviate/search/generative)\n",
"\n",
"To run this notebook, you'll need:\n",
"* An [OpenAI API key](https://platform.openai.com/docs/quickstart)\n",
"* Access to GPU/s\n",
"\n",
"Note: For best results, please use **GPU acceleration** to run this notebook. Here are two options for running this notebook:\n",
"1. **Locally on a MacBook with an Apple Silicon chip.** Converting all documents in the notebook takes ~2 minutes on a MacBook M2 due to Docling's usage of MPS accelerators.\n",
"2. **Run this notebook on Google Colab.** Converting all documents in the notebook takes ~8 mintutes on a Google Colab T4 GPU."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "4YgT7tpXCUl0"
},
"source": [
"### Install Docling and Weaviate client\n",
"\n",
"Note: If Colab prompts you to restart the session after running the cell below, click \"restart\" and proceed with running the rest of the notebook."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": true,
"id": "u076oUSF_YUG"
},
"outputs": [],
"source": [
"%%capture\n",
"%pip install docling~=\"2.7.0\"\n",
"%pip install -U weaviate-client~=\"4.9.4\"\n",
"%pip install rich\n",
"%pip install torch\n",
"\n",
"import warnings\n",
"\n",
"warnings.filterwarnings(\"ignore\")\n",
"\n",
"import logging\n",
"\n",
"# Suppress Weaviate client logs\n",
"logging.getLogger(\"weaviate\").setLevel(logging.ERROR)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "2q2F9RUmR8Wj"
},
"source": [
"## 🐥 Part 1: Docling\n",
"\n",
"Part of what makes Docling so remarkable is the fact that it can run on commodity hardware. This means that this notebook can be run on a local machine with GPU acceleration. If you're using a MacBook with a silicon chip, Docling integrates seamlessly with Metal Performance Shaders (MPS). MPS provides out-of-the-box GPU acceleration for macOS, seamlessly integrating with PyTorch and TensorFlow, offering energy-efficient performance on Apple Silicon, and broad compatibility with all Metal-supported GPUs.\n",
"\n",
"The code below checks to see if a GPU is available, either via CUDA or MPS."
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"MPS GPU is enabled.\n"
]
}
],
"source": [
"import torch\n",
"\n",
"# Check if GPU or MPS is available\n",
"if torch.cuda.is_available():\n",
" device = torch.device(\"cuda\")\n",
" print(f\"CUDA GPU is enabled: {torch.cuda.get_device_name(0)}\")\n",
"elif torch.backends.mps.is_available():\n",
" device = torch.device(\"mps\")\n",
" print(\"MPS GPU is enabled.\")\n",
"else:\n",
" raise EnvironmentError(\n",
" \"No GPU or MPS device found. Please check your environment and ensure GPU or MPS support is configured.\"\n",
" )"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "wHTsy4a8JFPl"
},
"source": [
"Here, we've collected 10 influential machine learning papers published as PDFs on arXiv. Because Docling does not yet have title extraction for PDFs, we manually add the titles in a corresponding list.\n",
"\n",
"Note: Converting all 10 papers should take around 8 minutes with a T4 GPU."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"id": "Vy5SMPiGDMy-"
},
"outputs": [],
"source": [
"# Influential machine learning papers\n",
"source_urls = [\n",
" \"https://arxiv.org/pdf/1706.03762\",\n",
" \"https://arxiv.org/pdf/1810.04805\",\n",
" \"https://arxiv.org/pdf/1406.2661\",\n",
" \"https://arxiv.org/pdf/1409.0473\",\n",
" \"https://arxiv.org/pdf/1412.6980\",\n",
" \"https://arxiv.org/pdf/1312.6114\",\n",
" \"https://arxiv.org/pdf/1312.5602\",\n",
" \"https://arxiv.org/pdf/1512.03385\",\n",
" \"https://arxiv.org/pdf/1409.3215\",\n",
" \"https://arxiv.org/pdf/1301.3781\",\n",
"]\n",
"\n",
"# And their corresponding titles (because Docling doesn't have title extraction yet!)\n",
"source_titles = [\n",
" \"Attention Is All You Need\",\n",
" \"BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding\",\n",
" \"Generative Adversarial Nets\",\n",
" \"Neural Machine Translation by Jointly Learning to Align and Translate\",\n",
" \"Adam: A Method for Stochastic Optimization\",\n",
" \"Auto-Encoding Variational Bayes\",\n",
" \"Playing Atari with Deep Reinforcement Learning\",\n",
" \"Deep Residual Learning for Image Recognition\",\n",
" \"Sequence to Sequence Learning with Neural Networks\",\n",
" \"A Neural Probabilistic Language Model\",\n",
"]"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "5fi8wzHrCoLa"
},
"source": [
"### Convert PDFs to Docling documents\n",
"\n",
"Here we use Docling's `.convert_all()` to parse a batch of PDFs. The result is a list of Docling documents that we can use for text extraction.\n",
"\n",
"Note: Please ignore the `ERR#` message."
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 67,
"referenced_widgets": [
"6d049f786a2f4ad7857a6cf2d95b5ba2",
"db2a7b9f549e4f0fb1ff3fce655d76a2",
"630967a2db4c4714b4c15d1358a0fcae",
"b3da9595ab7c4995a00e506e7b5202e3",
"243ecaf36ee24cafbd1c33d148f2ca78",
"5b7e22df1b464ca894126736e6f72207",
"02f6af5993bb4a6a9dbca77952f675d2",
"dea323b3de0e43118f338842c94ac065",
"bd198d2c0c4c4933a6e6544908d0d846",
"febd5c498e4f4f5dbde8dec3cd935502",
"ab4f282c0d37451092c60e6566e8e945"
]
},
"id": "Sr44xGR1PNSc",
"outputId": "b5cca9ee-d7c0-4c8f-c18a-0ac4787984e9"
},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Fetching 9 files: 100%|██████████| 9/9 [00:00<00:00, 84072.91it/s]\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"ERR#: COULD NOT CONVERT TO RS THIS TABLE TO COMPUTE SPANS\n"
]
}
],
"source": [
"from docling.datamodel.document import ConversionResult\n",
"from docling.document_converter import DocumentConverter\n",
"\n",
"# Instantiate the doc converter\n",
"doc_converter = DocumentConverter()\n",
"\n",
"# Directly pass list of files or streams to `convert_all`\n",
"conv_results_iter = doc_converter.convert_all(source_urls) # previously `convert`\n",
"\n",
"# Iterate over the generator to get a list of Docling documents\n",
"docs = [result.document for result in conv_results_iter]"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "xHun_P-OCtKd"
},
"source": [
"### Post-process extracted document data\n",
"#### Perform hierarchical chunking on documents\n",
"\n",
"We use Docling's `HierarchicalChunker()` to perform hierarchy-aware chunking of our list of documents. This is meant to preserve some of the structure and relationships within the document, which enables more accurate and relevant retrieval in our RAG pipeline."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"id": "L17ju9xibuIo"
},
"outputs": [],
"source": [
"from docling_core.transforms.chunker import HierarchicalChunker\n",
"\n",
"# Initialize lists for text, and titles\n",
"texts, titles = [], []\n",
"\n",
"chunker = HierarchicalChunker()\n",
"\n",
"# Process each document in the list\n",
"for doc, title in zip(docs, source_titles): # Pair each document with its title\n",
" chunks = list(\n",
" chunker.chunk(doc)\n",
" ) # Perform hierarchical chunking and get text from chunks\n",
" for chunk in chunks:\n",
" texts.append(chunk.text)\n",
" titles.append(title)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "khbU9R1li2Kj"
},
"source": [
"Because we're splitting the documents into chunks, we'll concatenate the article title to the beginning of each chunk for additional context."
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"id": "HNwYV9P57OwF"
},
"outputs": [],
"source": [
"# Concatenate title and text\n",
"for i in range(len(texts)):\n",
" texts[i] = f\"{titles[i]} {texts[i]}\""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "uhLlCpQODaT3"
},
"source": [
"## 💚 Part 2: Weaviate\n",
"### Create and configure an embedded Weaviate collection"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ho7xYQTZK5Wk"
},
"source": [
"We'll be using the OpenAI API for both generating the text embeddings and for the generative model in our RAG pipeline. The code below dynamically fetches your API key based on whether you're running this notebook in Google Colab and running it as a regular Jupyter notebook. All you need to do is replace `openai_api_key_var` with the name of your environmental variable name or Colab secret name for the API key.\n",
"\n",
"If you're running this notebook in Google Colab, make sure you [add](https://medium.com/@parthdasawant/how-to-use-secrets-in-google-colab-450c38e3ec75) your API key as a secret."
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"id": "PD53jOT4roj2"
},
"outputs": [],
"source": [
"# OpenAI API key variable name\n",
"openai_api_key_var = \"OPENAI_API_KEY\" # Replace with the name of your secret/env var\n",
"\n",
"# Fetch OpenAI API key\n",
"try:\n",
" # If running in Colab, fetch API key from Secrets\n",
" import google.colab\n",
" from google.colab import userdata\n",
"\n",
" openai_api_key = userdata.get(openai_api_key_var)\n",
" if not openai_api_key:\n",
" raise ValueError(f\"Secret '{openai_api_key_var}' not found in Colab secrets.\")\n",
"except ImportError:\n",
" # If not running in Colab, fetch API key from environment variable\n",
" import os\n",
"\n",
" openai_api_key = os.getenv(openai_api_key_var)\n",
" if not openai_api_key:\n",
" raise EnvironmentError(\n",
" f\"Environment variable '{openai_api_key_var}' is not set. \"\n",
" \"Please define it before running this script.\"\n",
" )"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "8G5jZSh6ti3e"
},
"source": [
"[Embedded Weaviate](https://weaviate.io/developers/weaviate/installation/embedded) allows you to spin up a Weaviate instance directly from your application code, without having to use a Docker container. If you're interested in other deployment methods, like using Docker-Compose or Kubernetes, check out this [page](https://weaviate.io/developers/weaviate/installation) in the Weaviate docs."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "hFUBEZiJUMic",
"outputId": "0b6534c9-66c9-4a47-9754-103bcc030019"
},
"outputs": [],
"source": [
"import weaviate\n",
"\n",
"# Connect to Weaviate embedded\n",
"client = weaviate.connect_to_embedded(headers={\"X-OpenAI-Api-Key\": openai_api_key})"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "4nu9qM75hrsd"
},
"outputs": [],
"source": [
"import weaviate.classes.config as wc\n",
"from weaviate.classes.config import DataType, Property\n",
"\n",
"# Define the collection name\n",
"collection_name = \"docling\"\n",
"\n",
"# Delete the collection if it already exists\n",
"if client.collections.exists(collection_name):\n",
" client.collections.delete(collection_name)\n",
"\n",
"# Create the collection\n",
"collection = client.collections.create(\n",
" name=collection_name,\n",
" vectorizer_config=wc.Configure.Vectorizer.text2vec_openai(\n",
" model=\"text-embedding-3-large\", # Specify your embedding model here\n",
" ),\n",
" # Enable generative model from Cohere\n",
" generative_config=wc.Configure.Generative.openai(\n",
" model=\"gpt-4o\" # Specify your generative model for RAG here\n",
" ),\n",
" # Define properties of metadata\n",
" properties=[\n",
" wc.Property(name=\"text\", data_type=wc.DataType.TEXT),\n",
" wc.Property(name=\"title\", data_type=wc.DataType.TEXT, skip_vectorization=True),\n",
" ],\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "RgMcZDB9Dzfs"
},
"source": [
"### Wrangle data into an acceptable format for Weaviate\n",
"\n",
"Transform our data from lists to a list of dictionaries for insertion into our Weaviate collection."
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"id": "kttDgwZEsIJQ"
},
"outputs": [],
"source": [
"# Initialize the data object\n",
"data = []\n",
"\n",
"# Create a dictionary for each row by iterating through the corresponding lists\n",
"for text, title in zip(texts, titles):\n",
" data_point = {\n",
" \"text\": text,\n",
" \"title\": title,\n",
" }\n",
" data.append(data_point)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "-4amqRaoD5g0"
},
"source": [
"### Insert data into Weaviate and generate embeddings\n",
"\n",
"Embeddings will be generated upon insertion to our Weaviate collection."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "g8VCYnhbaxcz",
"outputId": "cc900e56-9fb6-4d4e-ab18-ebd12b1f4201"
},
"outputs": [],
"source": [
"# Insert text chunks and metadata into vector DB collection\n",
"response = collection.data.insert_many(data)\n",
"\n",
"if response.has_errors:\n",
" print(response.errors)\n",
"else:\n",
" print(\"Insert complete.\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "KI01PxjuD_XR"
},
"source": [
"### Query the data\n",
"\n",
"Here, we perform a simple similarity search to return the most similar embedded chunks to our search query."
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "zbz6nWJc5CSj",
"outputId": "16aced21-4496-4c91-cc12-d5c9ac983351"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'text': 'BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding A distinctive feature of BERT is its unified architecture across different tasks. There is mini-', 'title': 'BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding'}\n",
"0.6578550338745117\n",
"{'text': 'BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding We introduce a new language representation model called BERT , which stands for B idirectional E ncoder R epresentations from T ransformers. Unlike recent language representation models (Peters et al., 2018a; Radford et al., 2018), BERT is designed to pretrain deep bidirectional representations from unlabeled text by jointly conditioning on both left and right context in all layers. As a result, the pre-trained BERT model can be finetuned with just one additional output layer to create state-of-the-art models for a wide range of tasks, such as question answering and language inference, without substantial taskspecific architecture modifications.', 'title': 'BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding'}\n",
"0.6696287989616394\n"
]
}
],
"source": [
"from weaviate.classes.query import MetadataQuery\n",
"\n",
"response = collection.query.near_text(\n",
" query=\"bert\",\n",
" limit=2,\n",
" return_metadata=MetadataQuery(distance=True),\n",
" return_properties=[\"text\", \"title\"],\n",
")\n",
"\n",
"for o in response.objects:\n",
" print(o.properties)\n",
" print(o.metadata.distance)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "elo32iMnEC18"
},
"source": [
"### Perform RAG on parsed articles\n",
"\n",
"Weaviate's `generate` module allows you to perform RAG over your embedded data without having to use a separate framework.\n",
"\n",
"We specify a prompt that includes the field we want to search through in the database (in this case it's `text`), a query that includes our search term, and the number of retrieved results to use in the generation."
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 233
},
"id": "7r2LMSX9bO4y",
"outputId": "84639adf-7783-4d43-94d9-711fb313a168"
},
"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\"><span style=\"color: #800000; text-decoration-color: #800000; font-weight: bold\">╭──────────────────────────────────────────────────── Prompt ─────────────────────────────────────────────────────╮</span>\n",
"<span style=\"color: #800000; text-decoration-color: #800000; font-weight: bold\">│</span> Explain how bert works, using only the retrieved context. <span style=\"color: #800000; text-decoration-color: #800000; font-weight: bold\">│</span>\n",
"<span style=\"color: #800000; text-decoration-color: #800000; font-weight: bold\">╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯</span>\n",
"</pre>\n"
],
"text/plain": [
"\u001b[1;31m╭─\u001b[0m\u001b[1;31m───────────────────────────────────────────────────\u001b[0m\u001b[1;31m Prompt \u001b[0m\u001b[1;31m────────────────────────────────────────────────────\u001b[0m\u001b[1;31m─╮\u001b[0m\n",
"\u001b[1;31m│\u001b[0m Explain how bert works, using only the retrieved context. \u001b[1;31m│\u001b[0m\n",
"\u001b[1;31m╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\u001b[0m\n"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">╭─────────────────────────────────────────────── Generated Content ───────────────────────────────────────────────╮</span>\n",
"<span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">│</span> BERT, which stands for Bidirectional Encoder Representations from Transformers, is a language representation <span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">│</span>\n",
"<span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">│</span> model designed to pretrain deep bidirectional representations from unlabeled text. It conditions on both left <span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">│</span>\n",
"<span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">│</span> and right context in all layers, unlike traditional left-to-right or right-to-left language models. This <span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">│</span>\n",
"<span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">│</span> pre-training involves two unsupervised tasks. The pre-trained BERT model can then be fine-tuned with just one <span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">│</span>\n",
"<span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">│</span> additional output layer to create state-of-the-art models for various tasks, such as question answering and <span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">│</span>\n",
"<span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">│</span> language inference, without needing substantial task-specific architecture modifications. A distinctive feature <span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">│</span>\n",
"<span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">│</span> of BERT is its unified architecture across different tasks. <span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">│</span>\n",
"<span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯</span>\n",
"</pre>\n"
],
"text/plain": [
"\u001b[1;32m╭─\u001b[0m\u001b[1;32m──────────────────────────────────────────────\u001b[0m\u001b[1;32m Generated Content \u001b[0m\u001b[1;32m──────────────────────────────────────────────\u001b[0m\u001b[1;32m─╮\u001b[0m\n",
"\u001b[1;32m│\u001b[0m BERT, which stands for Bidirectional Encoder Representations from Transformers, is a language representation \u001b[1;32m│\u001b[0m\n",
"\u001b[1;32m│\u001b[0m model designed to pretrain deep bidirectional representations from unlabeled text. It conditions on both left \u001b[1;32m│\u001b[0m\n",
"\u001b[1;32m│\u001b[0m and right context in all layers, unlike traditional left-to-right or right-to-left language models. This \u001b[1;32m│\u001b[0m\n",
"\u001b[1;32m│\u001b[0m pre-training involves two unsupervised tasks. The pre-trained BERT model can then be fine-tuned with just one \u001b[1;32m│\u001b[0m\n",
"\u001b[1;32m│\u001b[0m additional output layer to create state-of-the-art models for various tasks, such as question answering and \u001b[1;32m│\u001b[0m\n",
"\u001b[1;32m│\u001b[0m language inference, without needing substantial task-specific architecture modifications. A distinctive feature \u001b[1;32m│\u001b[0m\n",
"\u001b[1;32m│\u001b[0m of BERT is its unified architecture across different tasks. \u001b[1;32m│\u001b[0m\n",
"\u001b[1;32m╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\u001b[0m\n"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"from rich.console import Console\n",
"from rich.panel import Panel\n",
"\n",
"# Create a prompt where context from the Weaviate collection will be injected\n",
"prompt = \"Explain how {text} works, using only the retrieved context.\"\n",
"query = \"bert\"\n",
"\n",
"response = collection.generate.near_text(\n",
" query=query, limit=3, grouped_task=prompt, return_properties=[\"text\", \"title\"]\n",
")\n",
"\n",
"# Prettify the output using Rich\n",
"console = Console()\n",
"\n",
"console.print(\n",
" Panel(f\"{prompt}\".replace(\"{text}\", query), title=\"Prompt\", border_style=\"bold red\")\n",
")\n",
"console.print(\n",
" Panel(response.generated, title=\"Generated Content\", border_style=\"bold green\")\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 233
},
"id": "Dtju3oCiDOdD",
"outputId": "2f0f0cf8-0305-40cc-8409-07036c101938"
},
"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\"><span style=\"color: #800000; text-decoration-color: #800000; font-weight: bold\">╭──────────────────────────────────────────────────── Prompt ─────────────────────────────────────────────────────╮</span>\n",
"<span style=\"color: #800000; text-decoration-color: #800000; font-weight: bold\">│</span> Explain how a generative adversarial net works, using only the retrieved context. <span style=\"color: #800000; text-decoration-color: #800000; font-weight: bold\">│</span>\n",
"<span style=\"color: #800000; text-decoration-color: #800000; font-weight: bold\">╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯</span>\n",
"</pre>\n"
],
"text/plain": [
"\u001b[1;31m╭─\u001b[0m\u001b[1;31m───────────────────────────────────────────────────\u001b[0m\u001b[1;31m Prompt \u001b[0m\u001b[1;31m────────────────────────────────────────────────────\u001b[0m\u001b[1;31m─╮\u001b[0m\n",
"\u001b[1;31m│\u001b[0m Explain how a generative adversarial net works, using only the retrieved context. \u001b[1;31m│\u001b[0m\n",
"\u001b[1;31m╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\u001b[0m\n"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">╭─────────────────────────────────────────────── Generated Content ───────────────────────────────────────────────╮</span>\n",
"<span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">│</span> Generative Adversarial Nets (GANs) operate within an adversarial framework where two models are trained <span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">│</span>\n",
"<span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">│</span> simultaneously: a generative model (G) and a discriminative model (D). The generative model aims to capture the <span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">│</span>\n",
"<span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">│</span> data distribution and generate samples that mimic real data, while the discriminative model's task is to <span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">│</span>\n",
"<span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">│</span> distinguish between samples from the real data and those generated by G. This setup is akin to a game where the <span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">│</span>\n",
"<span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">│</span> generative model acts like counterfeiters trying to produce indistinguishable fake currency, and the <span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">│</span>\n",
"<span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">│</span> discriminative model acts like the police trying to detect these counterfeits. <span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">│</span>\n",
"<span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">│</span> <span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">│</span>\n",
"<span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">│</span> The training process involves a minimax two-player game where G tries to maximize the probability of D making a <span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">│</span>\n",
"<span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">│</span> mistake, while D tries to minimize it. When both models are defined by multilayer perceptrons, they can be <span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">│</span>\n",
"<span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">│</span> trained using backpropagation without the need for Markov chains or approximate inference networks. The <span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">│</span>\n",
"<span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">│</span> ultimate goal is for G to perfectly replicate the training data distribution, making D's output equal to 1/2 <span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">│</span>\n",
"<span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">│</span> everywhere, indicating it cannot distinguish between real and generated data. This framework allows for <span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">│</span>\n",
"<span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">│</span> specific training algorithms and optimization techniques, such as backpropagation and dropout, to be <span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">│</span>\n",
"<span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">│</span> effectively utilized. <span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">│</span>\n",
"<span style=\"color: #008000; text-decoration-color: #008000; font-weight: bold\">╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯</span>\n",
"</pre>\n"
],
"text/plain": [
"\u001b[1;32m╭─\u001b[0m\u001b[1;32m──────────────────────────────────────────────\u001b[0m\u001b[1;32m Generated Content \u001b[0m\u001b[1;32m──────────────────────────────────────────────\u001b[0m\u001b[1;32m─╮\u001b[0m\n",
"\u001b[1;32m│\u001b[0m Generative Adversarial Nets (GANs) operate within an adversarial framework where two models are trained \u001b[1;32m│\u001b[0m\n",
"\u001b[1;32m│\u001b[0m simultaneously: a generative model (G) and a discriminative model (D). The generative model aims to capture the \u001b[1;32m│\u001b[0m\n",
"\u001b[1;32m│\u001b[0m data distribution and generate samples that mimic real data, while the discriminative model's task is to \u001b[1;32m│\u001b[0m\n",
"\u001b[1;32m│\u001b[0m distinguish between samples from the real data and those generated by G. This setup is akin to a game where the \u001b[1;32m│\u001b[0m\n",
"\u001b[1;32m│\u001b[0m generative model acts like counterfeiters trying to produce indistinguishable fake currency, and the \u001b[1;32m│\u001b[0m\n",
"\u001b[1;32m│\u001b[0m discriminative model acts like the police trying to detect these counterfeits. \u001b[1;32m│\u001b[0m\n",
"\u001b[1;32m│\u001b[0m \u001b[1;32m│\u001b[0m\n",
"\u001b[1;32m│\u001b[0m The training process involves a minimax two-player game where G tries to maximize the probability of D making a \u001b[1;32m│\u001b[0m\n",
"\u001b[1;32m│\u001b[0m mistake, while D tries to minimize it. When both models are defined by multilayer perceptrons, they can be \u001b[1;32m│\u001b[0m\n",
"\u001b[1;32m│\u001b[0m trained using backpropagation without the need for Markov chains or approximate inference networks. The \u001b[1;32m│\u001b[0m\n",
"\u001b[1;32m│\u001b[0m ultimate goal is for G to perfectly replicate the training data distribution, making D's output equal to 1/2 \u001b[1;32m│\u001b[0m\n",
"\u001b[1;32m│\u001b[0m everywhere, indicating it cannot distinguish between real and generated data. This framework allows for \u001b[1;32m│\u001b[0m\n",
"\u001b[1;32m│\u001b[0m specific training algorithms and optimization techniques, such as backpropagation and dropout, to be \u001b[1;32m│\u001b[0m\n",
"\u001b[1;32m│\u001b[0m effectively utilized. \u001b[1;32m│\u001b[0m\n",
"\u001b[1;32m╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\u001b[0m\n"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"# Create a prompt where context from the Weaviate collection will be injected\n",
"prompt = \"Explain how {text} works, using only the retrieved context.\"\n",
"query = \"a generative adversarial net\"\n",
"\n",
"response = collection.generate.near_text(\n",
" query=query, limit=3, grouped_task=prompt, return_properties=[\"text\", \"title\"]\n",
")\n",
"\n",
"# Prettify the output using Rich\n",
"console = Console()\n",
"\n",
"console.print(\n",
" Panel(f\"{prompt}\".replace(\"{text}\", query), title=\"Prompt\", border_style=\"bold red\")\n",
")\n",
"console.print(\n",
" Panel(response.generated, title=\"Generated Content\", border_style=\"bold green\")\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "7tGz49nfUegG"
},
"source": [
"We can see that our RAG pipeline performs relatively well for simple queries, especially given the small size of the dataset. Scaling this method for converting a larger sample of PDFs would require more compute (GPUs) and a more advanced deployment of Weaviate (like Docker, Kubernetes, or Weaviate Cloud). For more information on available Weaviate configurations, check out the [documetation](https://weaviate.io/developers/weaviate/starter-guides/which-weaviate)."
]
}
],
"metadata": {
"accelerator": "GPU",
"colab": {
"gpuType": "T4",
"provenance": []
},
"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.12.7"
}
},
"nbformat": 4,
"nbformat_minor": 0
}

View File

@ -12,7 +12,17 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"# Hybrid RAG with Qdrant"
"# Retrieval with Qdrant"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"| Step | Tech | Execution | \n",
"| --- | --- | --- |\n",
"| Embedding | FastEmbed | 💻 Local |\n",
"| Vector store | Qdrant | 💻 Local |"
]
},
{
@ -47,22 +57,19 @@
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m24.2\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m24.3.1\u001b[0m\n",
"\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpip install --upgrade pip\u001b[0m\n",
"Note: you may need to restart the kernel to use updated packages.\n"
]
}
],
"source": [
"%pip install --no-warn-conflicts -q qdrant-client docling docling-core fastembed"
"%pip install --no-warn-conflicts -q qdrant-client docling fastembed"
]
},
{
@ -74,13 +81,13 @@
},
{
"cell_type": "code",
"execution_count": 1,
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"from docling_core.transforms.chunker import HierarchicalChunker\n",
"from qdrant_client import QdrantClient\n",
"\n",
"from docling.chunking import HybridChunker\n",
"from docling.datamodel.base_models import InputFormat\n",
"from docling.document_converter import DocumentConverter"
]
@ -95,36 +102,16 @@
},
{
"cell_type": "code",
"execution_count": 2,
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "c1077c6634d9434584c41cc12f9107c9",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Fetching 5 files: 0%| | 0/5 [00:00<?, ?it/s]"
"name": "stderr",
"output_type": "stream",
"text": [
"/Users/pva/work/github.com/DS4SD/docling/.venv/lib/python3.12/site-packages/huggingface_hub/utils/tqdm.py:155: UserWarning: Cannot enable progress bars: environment variable `HF_HUB_DISABLE_PROGRESS_BARS=1` is set and has priority.\n",
" warnings.warn(\n"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "67069c07b73448d491944452159d10bc",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Fetching 29 files: 0%| | 0/29 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
@ -149,7 +136,7 @@
},
{
"cell_type": "code",
"execution_count": 3,
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
@ -157,7 +144,7 @@
" \"https://www.sagacify.com/news/a-guide-to-chunking-strategies-for-retrieval-augmented-generation-rag\"\n",
")\n",
"documents, metadatas = [], []\n",
"for chunk in HierarchicalChunker().chunk(result.document):\n",
"for chunk in HybridChunker().chunk(result.document):\n",
" documents.append(chunk.text)\n",
" metadatas.append(chunk.meta.export_json_dict())"
]
@ -173,95 +160,119 @@
},
{
"cell_type": "code",
"execution_count": 4,
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['e74ae15be5eb4805858307846318e784',\n",
" 'f83f6125b0fa4a0595ae6a0777c9d90d',\n",
" '9cf63c7f30764715bf3804a19db36d7d',\n",
" '007dbe6d355b4b49af3b736cbd63a4d8',\n",
" 'e5e31f21f2e84aa68beca0dfc532cbe9',\n",
" '69c10816af204bb28630a1f957d8dd3e',\n",
" 'b63546b9b1744063bdb076b234d883ca',\n",
" '90ad15ba8fa6494489e1d3221e30bfcf',\n",
" '13517debb483452ea40fc7aa04c08c50',\n",
" '84ccab5cfab74e27a55acef1c63e3fad',\n",
" 'e8aa2ef46d234c5a8a9da64b701d60b4',\n",
" '190bea5ba43c45e792197c50898d1d90',\n",
" 'a730319ea65645ca81e735ace0bcc72e',\n",
" '415e7f6f15864e30b836e23ae8d71b43',\n",
" '5569bce4e65541868c762d149c6f491e',\n",
" '74d9b234e9c04ebeb8e4e1ca625789ac',\n",
" '308b1c5006a94a679f4c8d6f2396993c',\n",
" 'aaa5ec6d385a418388e660c425bf1dbe',\n",
" '630be8e43e4e4472a9cdb9af9462a43a',\n",
" '643b316224de4770a5349bf69cf93471',\n",
" 'da9265e6f6c2485493d15223eefdf411',\n",
" 'a916e447d52c4084b5ce81a0c5a65b07',\n",
" '2883c620858e4e728b88e127155a4f2c',\n",
" '2a998f0e9c124af99027060b94027874',\n",
" 'be551fbd2b9e42f48ebae0cbf1f481bc',\n",
" '95b7f7608e974ca6847097ee4590fba1',\n",
" '309db4f3863b4e3aaf16d5f346c309f3',\n",
" 'c818383267f64fd68b2237b024bd724e',\n",
" '1f16e78338c94238892171b400051cd4',\n",
" '25c680c3e064462cab071ea9bf1bad8c',\n",
" 'f41ab7e480a248c6bb87019341c7ca74',\n",
" 'd440128bed6d4dcb987152b48ecd9a8a',\n",
" 'c110d5dfdc5849808851788c2404dd15']"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"outputs": [],
"source": [
"client.add(COLLECTION_NAME, documents=documents, metadata=metadatas, batch_size=64)"
"_ = client.add(\n",
" collection_name=COLLECTION_NAME,\n",
" documents=documents,\n",
" metadata=metadatas,\n",
" batch_size=64,\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Query Documents"
"## Retrieval"
]
},
{
"cell_type": "code",
"execution_count": 5,
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"points = client.query(\n",
" collection_name=COLLECTION_NAME,\n",
" query_text=\"Can I split documents?\",\n",
" limit=10,\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<=== Retrieved documents ===>\n",
"Document Specific Chunking is a strategy that respects the document's structure. Rather than using a set number of characters or a recursive process, it creates chunks that align with the logical sections of the document, like paragraphs or subsections. This approach maintains the original author's organization of content and helps keep the text coherent. It makes the retrieved information more relevant and useful, particularly for structured documents with clearly defined sections.\n",
"Document Specific Chunking can handle a variety of document formats, such as:\n",
"Consequently, there are also splitters available for this purpose.\n",
"=== 0 ===\n",
"Have you ever wondered how we, humans, would chunk? Here's a breakdown of a possible way a human would process a new document:\n",
"1. We start at the top of the document, treating the first part as a chunk.\n",
"   2. We continue down the document, deciding if a new sentence or piece of information belongs with the first chunk or should start a new one.\n",
"    3. We keep this up until we reach the end of the document.\n",
"Have you ever wondered how we, humans, would chunk? Here's a breakdown of a possible way a human would process a new document:\n",
"The goal of chunking is, as its name says, to chunk the information into multiple smaller pieces in order to store it in a more efficient and meaningful way. This allows the retrieval to capture pieces of information that are more related to the question at hand, and the generation to be more precise, but also less costly, as only a part of a document will be included in the LLM prompt, instead of the whole document.\n",
"To put these strategies into action, there's a whole array of tools and libraries at your disposal. For example, llama_index is a fantastic tool that lets you create document indices and retrieve chunked documents. Let's not forget LangChain, another remarkable tool that makes implementing chunking strategies a breeze, particularly when dealing with multi-language data. Diving into these tools and understanding how they can work in harmony with the chunking strategies we've discussed is a crucial part of mastering Retrieval Augmented Generation.\n",
"Semantic chunking involves taking the embeddings of every sentence in the document, comparing the similarity of all sentences with each other, and then grouping sentences with the most similar embeddings together.\n",
"The ultimate dream? Having an agent do this for you. But slow down! This approach is still being tested and isn't quite ready for the big leagues due to the time it takes to process multiple LLM calls and the cost of those calls. There's no implementation available in public libraries just yet. However, Greg Kamradt has his version available here.\n",
"\n",
"=== 1 ===\n",
"Document Specific Chunking is a strategy that respects the document's structure. Rather than using a set number of characters or a recursive process, it creates chunks that align with the logical sections of the document, like paragraphs or subsections. This approach maintains the original author's organization of content and helps keep the text coherent. It makes the retrieved information more relevant and useful, particularly for structured documents with clearly defined sections.\n",
"Document Specific Chunking can handle a variety of document formats, such as:\n",
"Markdown\n",
"HTML\n",
"Python\n",
"etc\n",
"Here well take Markdown as our example and use a modified version of our first sample text:\n",
"\n",
"The result is the following:\n",
"You can see here that with a chunk size of 105, the Markdown structure of the document is taken into account, and the chunks thus preserve the semantics of the text!\n",
"And there you have it! These chunking strategies are like a personal toolbox when it comes to implementing Retrieval Augmented Generation. They're a ton of ways to slice and dice text, each with its unique features and quirks. This variety gives you the freedom to pick the strategy that suits your project best, allowing you to tailor your approach to perfectly fit the unique needs of your work.\n"
"\n",
"=== 2 ===\n",
"And there you have it! These chunking strategies are like a personal toolbox when it comes to implementing Retrieval Augmented Generation. They're a ton of ways to slice and dice text, each with its unique features and quirks. This variety gives you the freedom to pick the strategy that suits your project best, allowing you to tailor your approach to perfectly fit the unique needs of your work.\n",
"To put these strategies into action, there's a whole array of tools and libraries at your disposal. For example, llama_index is a fantastic tool that lets you create document indices and retrieve chunked documents. Let's not forget LangChain, another remarkable tool that makes implementing chunking strategies a breeze, particularly when dealing with multi-language data. Diving into these tools and understanding how they can work in harmony with the chunking strategies we've discussed is a crucial part of mastering Retrieval Augmented Generation.\n",
"By the way, if you're eager to experiment with your own examples using the chunking visualisation tool featured in this blog, feel free to give it a try! You can access it right here. Enjoy, and happy chunking! 😉\n",
"\n",
"=== 3 ===\n",
"Retrieval Augmented Generation (RAG) has been a hot topic in understanding, interpreting, and generating text with AI for the last few months. It's like a wonderful union of retrieval-based and generative models, creating a playground for researchers, data scientists, and natural language processing enthusiasts, like you and me.\n",
"To truly control the results produced by our RAG, we need to understand chunking strategies and their role in the process of retrieving and generating text. Indeed, each chunking strategy enhances RAG's effectiveness in its unique way.\n",
"The goal of chunking is, as its name says, to chunk the information into multiple smaller pieces in order to store it in a more efficient and meaningful way. This allows the retrieval to capture pieces of information that are more related to the question at hand, and the generation to be more precise, but also less costly, as only a part of a document will be included in the LLM prompt, instead of the whole document.\n",
"Let's explore some chunking strategies together.\n",
"The methods mentioned in the article you're about to read usually make use of two key parameters. First, we have [chunk_size]— which controls the size of your text chunks. Then there's [chunk_overlap], which takes care of how much text overlaps between one chunk and the next.\n",
"\n",
"=== 4 ===\n",
"Semantic Chunking considers the relationships within the text. It divides the text into meaningful, semantically complete chunks. This approach ensures the information's integrity during retrieval, leading to a more accurate and contextually appropriate outcome.\n",
"Semantic chunking involves taking the embeddings of every sentence in the document, comparing the similarity of all sentences with each other, and then grouping sentences with the most similar embeddings together.\n",
"By focusing on the text's meaning and context, Semantic Chunking significantly enhances the quality of retrieval. It's a top-notch choice when maintaining the semantic integrity of the text is vital.\n",
"However, this method does require more effort and is notably slower than the previous ones.\n",
"On our example text, since it is quite short and does not expose varied subjects, this method would only generate a single chunk.\n",
"\n",
"=== 5 ===\n",
"Language models used in the rest of your possible RAG pipeline have a token limit, which should not be exceeded. When dividing your text into chunks, it's advisable to count the number of tokens. Plenty of tokenizers are available. To ensure accuracy, use the same tokenizer for counting tokens as the one used in the language model.\n",
"Consequently, there are also splitters available for this purpose.\n",
"For instance, by using the [SpacyTextSplitter] from LangChain, the following chunks are created:\n",
"\n",
"\n",
"=== 6 ===\n",
"First things first, we have Character Chunking. This strategy divides the text into chunks based on a fixed number of characters. Its simplicity makes it a great starting point, but it can sometimes disrupt the text's flow, breaking sentences or words in unexpected places. Despite its limitations, it's a great stepping stone towards more advanced methods.\n",
"Now lets see that in action with an example. Imagine a text that reads:\n",
"If we decide to set our chunk size to 100 and no chunk overlap, we'd end up with the following chunks. As you can see, Character Chunking can lead to some intriguing, albeit sometimes nonsensical, results, cutting some of the sentences in their middle.\n",
"By choosing a smaller chunk size,  we would obtain more chunks, and by setting a bigger chunk overlap, we could obtain something like this:\n",
"\n",
"Also, by default this method creates chunks character by character based on the empty character [ ]. But you can specify a different one in order to chunk on something else, even a complete word! For instance, by specifying [' '] as the separator, you can avoid cutting words in their middle.\n",
"\n",
"=== 7 ===\n",
"Next, let's take a look at Recursive Character Chunking. Based on the basic concept of Character Chunking, this advanced version takes it up a notch by dividing the text into chunks until a certain condition is met, such as reaching a minimum chunk size. This method ensures that the chunking process aligns with the text's structure, preserving more meaning. Its adaptability makes Recursive Character Chunking great for texts with varied structures.\n",
"Again, lets use the same example in order to illustrate this method. With a chunk size of 100, and the default settings for the other parameters, we obtain the following chunks:\n",
"\n"
]
}
],
"source": [
"points = client.query(COLLECTION_NAME, query_text=\"Can I split documents?\", limit=10)\n",
"\n",
"print(\"<=== Retrieved documents ===>\")\n",
"for point in points:\n",
" print(point.document)"
"for i, point in enumerate(points):\n",
" print(f\"=== {i} ===\")\n",
" print(point.document)\n",
" print()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
@ -280,7 +291,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.13.0"
"version": "3.12.7"
}
},
"nbformat": 4,

View File

@ -31,6 +31,15 @@ Docling parses documents and exports them to the desired format with ease and sp
* 📝 Metadata extraction, including title, authors, references & language
* 🦜🔗 Native LangChain extension
## Get started
<div class="grid">
<a href="concepts/" class="card"><b>Concepts</b><br />Learn Docling fundamendals</a>
<a href="examples/" class="card"><b>Examples</b><br />Try out recipes for various use cases, including conversion, RAG, and more</a>
<a href="integrations/" class="card"><b>Integrations</b><br />Check out integrations with popular frameworks and tools</a>
<a href="reference/document_converter/" class="card"><b>Reference</b><br />See more API details</a>
</div>
## IBM ❤️ Open Source AI
Docling has been brought to you by IBM.

View File

@ -0,0 +1,10 @@
Docling is available in [CrewAI](https://www.crewai.com/) as the `CrewDoclingSource`
knowledge source.
- 💻 [Crew AI GitHub][github]
- 📖 [Crew AI knowledge docs][docs]
- 📦 [Crew AI PyPI][package]
[github]: https://github.com/crewAIInc/crewAI/
[docs]: https://docs.crewai.com/concepts/knowledge
[package]: https://pypi.org/project/crewai/

View File

@ -0,0 +1,11 @@
Docling is available as a converter in [Haystack](https://haystack.deepset.ai/):
- 📖 [Docling Haystack integration docs](https://haystack.deepset.ai/integrations/docling)
- 💻 [Docling Haystack integration GitHub][github]
- 🧑🏽‍🍳 [Docling Haystack integration example][example]
- 📦 [Docling Haystack integration PyPI][pypi]
[github]: https://github.com/DS4SD/docling-haystack
[docs]: https://haystack.deepset.ai/integrations/docling
[pypi]: https://pypi.org/project/docling-haystack
[example]: https://ds4sd.github.io/docling/examples/rag_haystack/

View File

@ -0,0 +1,6 @@
Docling is powering the NVIDIA *PDF to Podcast* agentic AI blueprint:
- [🏠 PDF to Podcast home](https://build.nvidia.com/nvidia/pdf-to-podcast)
- [💻 PDF to Podcast GitHub](https://github.com/NVIDIA-AI-Blueprints/pdf-to-podcast)
- [📣 PDF to Podcast announcement](https://nvidianews.nvidia.com/news/nvidia-launches-ai-foundation-models-for-rtx-ai-pcs)
- [✍️ PDF to Podcast blog post](https://blogs.nvidia.com/blog/agentic-ai-blueprints/)

View File

@ -0,0 +1,5 @@
Docling is available an ingestion engine for [OpenContracts](https://github.com/JSv4/OpenContracts), allowing you to use Docling's OCR engine(s), chunker(s), labels, etc. and load them into a platform supporting bulk data extraction, text annotating, and question-answering:
- 💻 [OpenContracts GitHub](https://github.com/JSv4/OpenContracts)
- 📖 [OpenContracts Docs](https://jsv4.github.io/OpenContracts/)
- ▶️ [OpenContracts x Docling PDF annotation screen capture](https://github.com/JSv4/OpenContracts/blob/main/docs/assets/images/gifs/PDF%20Annotation%20Flow.gif)

View File

@ -1,10 +1,8 @@
Docling is powering document processing in [Red Hat Enterprise Linux AI][home] (RHEL AI),
Docling is powering document processing in [Red Hat Enterprise Linux AI (RHEL AI)](https://rhel.ai),
enabling users to unlock the knowledge hidden in documents and present it to
InstructLab's fine-tuning for aligning AI models to the user's specific data.
More details can be found in this [blog post][blog].
- 🏠 [RHEL AI home][home]
[home]: https://www.redhat.com/en/technologies/linux-platforms/enterprise-linux/ai
[blog]: https://www.redhat.com/en/blog/docling-missing-document-processing-companion-generative-ai
- 📣 [RHEL AI 1.3 announcement](https://www.redhat.com/en/about/press-releases/red-hat-delivers-next-wave-gen-ai-innovation-new-red-hat-enterprise-linux-ai-capabilities)
- ✍️ RHEL blog posts:
- [RHEL AI 1.3 Docling context aware chunking: What you need to know](https://www.redhat.com/en/blog/rhel-13-docling-context-aware-chunking-what-you-need-know)
- [Docling: The missing document processing companion for generative AI](https://www.redhat.com/en/blog/docling-missing-document-processing-companion-generative-ai)

View File

@ -0,0 +1,5 @@
Docling is available as a document parser in [Vectara](https://www.vectara.com/).
- 💻 [Vectara GitHub org](https://github.com/vectara)
- [vectara-ingest GitHub repo](https://github.com/vectara/vectara-ingest)
- 📖 [Vectara docs](https://docs.vectara.com/)

View File

@ -32,6 +32,7 @@ This is an automatic generated API reference of the DoclingDocument type.
- CoordOrigin
- ImageRefMode
- Size
docstring_style: sphinx
show_if_no_docstring: true
show_submodules: true
docstring_section_style: list

View File

@ -65,7 +65,7 @@ nav:
- Chunking: concepts/chunking.md
- Examples:
- Examples: examples/index.md
- Conversion:
- 🔀 Conversion:
- "Simple conversion": examples/minimal.py
- "Custom conversion": examples/custom_convert.py
- "Batch conversion": examples/batch_convert.py
@ -76,27 +76,37 @@ nav:
- "Multimodal export": examples/export_multimodal.py
- "Force full page OCR": examples/full_page_ocr.py
- "Accelerator options": examples/run_with_accelerator.py
- Chunking:
- ✂️ Chunking:
- "Hybrid chunking": examples/hybrid_chunking.ipynb
- RAG / QA:
- "RAG with Haystack": examples/rag_haystack.ipynb
- "RAG with LlamaIndex 🦙": examples/rag_llamaindex.ipynb
- "RAG with LangChain 🦜🔗": examples/rag_langchain.ipynb
- "Hybrid RAG with Qdrant": examples/hybrid_rag_qdrant.ipynb
- 💬 RAG / QA:
- examples/rag_haystack.ipynb
- examples/rag_llamaindex.ipynb
- examples/rag_langchain.ipynb
- examples/rag_weaviate.ipynb
- RAG with Granite [↗]: https://github.com/ibm-granite-community/granite-snack-cookbook/blob/main/recipes/RAG/Granite_Docling_RAG.ipynb
- examples/retrieval_qdrant.ipynb
- Integrations:
- Integrations: integrations/index.md
- "🐝 Bee": integrations/bee.md
- "Cloudera": integrations/cloudera.md
- "Data Prep Kit": integrations/data_prep_kit.md
- "DocETL": integrations/docetl.md
- "🐶 InstructLab": integrations/instructlab.md
- "Kotaemon": integrations/kotaemon.md
- "🦙 LlamaIndex": integrations/llamaindex.md
- "Prodigy": integrations/prodigy.md
- "Red Hat Enterprise Linux AI": integrations/rhel_ai.md
- "spaCy": integrations/spacy.md
- 🤖 Agentic / AI dev frameworks:
- "Bee Agent Framework": integrations/bee.md
- "Crew AI": integrations/crewai.md
- "Haystack": integrations/haystack.md
# - "LangChain": integrations/langchain.md
- "LlamaIndex": integrations/llamaindex.md
- "txtai": integrations/txtai.md
# - "LangChain 🦜🔗": integrations/langchain.md
- ⭐️ Featured:
- "Data Prep Kit": integrations/data_prep_kit.md
- "InstructLab": integrations/instructlab.md
- "NVIDIA": integrations/nvidia.md
- "Prodigy": integrations/prodigy.md
- "RHEL AI": integrations/rhel_ai.md
- "spaCy": integrations/spacy.md
- 🗂️ More integrations:
- "Cloudera": integrations/cloudera.md
- "DocETL": integrations/docetl.md
- "Kotaemon": integrations/kotaemon.md
- "OpenContracts": integrations/opencontracts.md
- "Vectara": integrations/vectara.md
- Reference:
- Python API:
- Document Converter: reference/document_converter.md