-
Notifications
You must be signed in to change notification settings - Fork 7.1k
Feat/docling-support #1763
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Feat/docling-support #1763
Changes from all commits
Commits
Show all changes
26 commits
Select commit
Hold shift + click to select a range
04cb9af
added tool for docling support
lorenzejay 625c21d
docling support installation
lorenzejay a67ec7e
use file_paths instead of file_path
lorenzejay ee74ad0
fix import
lorenzejay 56172ec
organized imports
lorenzejay b14f6ff
run_type docs
lorenzejay 610ea40
needs to be list
lorenzejay f1c9caa
fixed logic
lorenzejay 054bc26
logged but file_path is backwards compatible
lorenzejay 76c640b
use file_paths instead of file_path 2
lorenzejay c2ed1f2
added test for multiple sources for file_paths
lorenzejay 356eb07
fix run-types
lorenzejay 10c04d5
enabling local files to work and type cleanup
lorenzejay 0921f71
linted
lorenzejay e14a49f
fix test and types
lorenzejay ef7a101
Merge branch 'main' of github.com:crewAIInc/crewAI into feat/docling
lorenzejay 7885c5f
fixed run types
lorenzejay 436a458
fix types
lorenzejay aedaf01
Merge branch 'main' of github.com:crewAIInc/crewAI into feat/docling
lorenzejay c3d31de
renamed to CrewDoclingSource
lorenzejay f380f8e
linted
lorenzejay bc230b4
Merge branch 'main' of github.com:crewAIInc/crewAI into feat/docling
lorenzejay 6faa031
added docs
lorenzejay 9dda698
Merge branch 'main' into feat/docling
bhancockio abdc713
Merge branch 'main' into feat/docling
bhancockio bebf8e9
resolve conflicts
bhancockio File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,120 @@ | ||
| from pathlib import Path | ||
| from typing import Iterator, List, Optional, Union | ||
| from urllib.parse import urlparse | ||
|
|
||
| from docling.datamodel.base_models import InputFormat | ||
| from docling.document_converter import DocumentConverter | ||
| from docling.exceptions import ConversionError | ||
| from docling_core.transforms.chunker.hierarchical_chunker import HierarchicalChunker | ||
| from docling_core.types.doc.document import DoclingDocument | ||
| from pydantic import Field | ||
|
|
||
| from crewai.knowledge.source.base_knowledge_source import BaseKnowledgeSource | ||
| from crewai.utilities.constants import KNOWLEDGE_DIRECTORY | ||
| from crewai.utilities.logger import Logger | ||
|
|
||
|
|
||
| class CrewDoclingSource(BaseKnowledgeSource): | ||
| """Default Source class for converting documents to markdown or json | ||
| This will auto support PDF, DOCX, and TXT, XLSX, Images, and HTML files without any additional dependencies and follows the docling package as the source of truth. | ||
| """ | ||
|
|
||
| _logger: Logger = Logger(verbose=True) | ||
|
|
||
| file_path: Optional[List[Union[Path, str]]] = Field(default=None) | ||
| file_paths: List[Union[Path, str]] = Field(default_factory=list) | ||
| chunks: List[str] = Field(default_factory=list) | ||
| safe_file_paths: List[Union[Path, str]] = Field(default_factory=list) | ||
| content: List[DoclingDocument] = Field(default_factory=list) | ||
| document_converter: DocumentConverter = Field( | ||
| default_factory=lambda: DocumentConverter( | ||
| allowed_formats=[ | ||
| InputFormat.MD, | ||
| InputFormat.ASCIIDOC, | ||
| InputFormat.PDF, | ||
| InputFormat.DOCX, | ||
| InputFormat.HTML, | ||
| InputFormat.IMAGE, | ||
| InputFormat.XLSX, | ||
| InputFormat.PPTX, | ||
| ] | ||
| ) | ||
| ) | ||
|
|
||
| def model_post_init(self, _) -> None: | ||
| if self.file_path: | ||
| self._logger.log( | ||
| "warning", | ||
| "The 'file_path' attribute is deprecated and will be removed in a future version. Please use 'file_paths' instead.", | ||
| color="yellow", | ||
| ) | ||
| self.file_paths = self.file_path | ||
| self.safe_file_paths = self.validate_content() | ||
| self.content = self._load_content() | ||
|
|
||
| def _load_content(self) -> List[DoclingDocument]: | ||
| try: | ||
| return self._convert_source_to_docling_documents() | ||
| except ConversionError as e: | ||
| self._logger.log( | ||
| "error", | ||
| f"Error loading content: {e}. Supported formats: {self.document_converter.allowed_formats}", | ||
| "red", | ||
| ) | ||
| raise e | ||
| except Exception as e: | ||
| self._logger.log("error", f"Error loading content: {e}") | ||
| raise e | ||
|
|
||
| def add(self) -> None: | ||
| if self.content is None: | ||
| return | ||
| for doc in self.content: | ||
| new_chunks_iterable = self._chunk_doc(doc) | ||
| self.chunks.extend(list(new_chunks_iterable)) | ||
| self._save_documents() | ||
|
|
||
| def _convert_source_to_docling_documents(self) -> List[DoclingDocument]: | ||
| conv_results_iter = self.document_converter.convert_all(self.safe_file_paths) | ||
| return [result.document for result in conv_results_iter] | ||
|
|
||
| def _chunk_doc(self, doc: DoclingDocument) -> Iterator[str]: | ||
| chunker = HierarchicalChunker() | ||
| for chunk in chunker.chunk(doc): | ||
| yield chunk.text | ||
|
|
||
| def validate_content(self) -> List[Union[Path, str]]: | ||
| processed_paths: List[Union[Path, str]] = [] | ||
| for path in self.file_paths: | ||
| if isinstance(path, str): | ||
| if path.startswith(("http://", "https://")): | ||
| try: | ||
| if self._validate_url(path): | ||
| processed_paths.append(path) | ||
| else: | ||
| raise ValueError(f"Invalid URL format: {path}") | ||
| except Exception as e: | ||
| raise ValueError(f"Invalid URL: {path}. Error: {str(e)}") | ||
| else: | ||
| local_path = Path(KNOWLEDGE_DIRECTORY + "/" + path) | ||
| if local_path.exists(): | ||
| processed_paths.append(local_path) | ||
| else: | ||
| raise FileNotFoundError(f"File not found: {local_path}") | ||
| else: | ||
| # this is an instance of Path | ||
| processed_paths.append(path) | ||
| return processed_paths | ||
|
|
||
| def _validate_url(self, url: str) -> bool: | ||
| try: | ||
| result = urlparse(url) | ||
| return all( | ||
| [ | ||
| result.scheme in ("http", "https"), | ||
| result.netloc, | ||
| len(result.netloc.split(".")) >= 2, # Ensure domain has TLD | ||
| ] | ||
| ) | ||
| except Exception: | ||
| return False |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.