Skip to content

Conversation

@alekszievr
Copy link
Contributor

@alekszievr alekszievr commented Feb 17, 2025

Description

DCO Affirmation

I affirm that all code in every commit of this pull request conforms to the terms of the Topoteretes Developer Certificate of Origin

Summary by CodeRabbit

  • New Features

    • Enhanced document chunk extraction for improved processing consistency across multiple formats.
  • Refactor

    • Streamlined the configuration for text chunking by replacing indirect mappings with a direct instantiation approach across document types.
    • Updated method signatures across various document classes to accept chunker class references instead of string identifiers.
  • Chores

    • Removed legacy configuration utilities related to document chunking to simplify processing.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 17, 2025

Walkthrough

The changes refactor how chunkers are instantiated across various modules. Instead of using string identifiers and a mapping configuration, all read methods now expect a class reference (e.g., TextChunker) passed as a parameter (renamed to chunker_cls). The API and task definitions are modified accordingly, and the obsolete mapping file has been removed. The updates also improve code readability in instantiating tasks and processing document chunks.

Changes

File(s) Change Summary
cognee/api/.../cognify_v2.py Added import for TextChunker and updated the Task instantiation in get_default_tasks to include chunker=TextChunker with improved parameter alignment.
cognee/modules/data/processing/document_types/AudioDocument.py, Document.py, ImageDocument.py, PdfDocument.py, TextDocument.py, UnstructuredDocument.py Updated the read method signatures by renaming the parameter from chunker (string) to chunker_cls (class reference) and removed the indirect instantiation via ChunkerConfig. In TextDocument.py, the unused import from ChunkerMapping was also removed.
cognee/modules/data/processing/document_types/ChunkerMapping.py Removed the file that contained the ChunkerConfig class and its chunker mapping functionality.
cognee/tasks/documents/extract_chunks_from_documents.py Changed the function signature to use TextChunker (via chunker_cls) instead of the string "text_chunker", adjusted the call to document.read, and added an explicit import for TextChunker.
cognee/tests/integration/documents/..._test.py Updated test files for AudioDocument, ImageDocument, PdfDocument, TextDocument, and UnstructuredDocument to replace chunker with chunker_cls (now taking TextChunker) in the read method calls, and added necessary imports for TextChunker.

Sequence Diagram(s)

sequenceDiagram
    participant TaskManager as Task Manager
    participant Extractor as extract_chunks_from_documents
    participant Document as Document.read
    participant Chunker as TextChunker

    TaskManager->>Extractor: Invoke extract_chunks_from_documents(documents, max_chunk_tokens, ..., TextChunker)
    Extractor->>Document: Call read(chunk_size, chunker_cls=TextChunker, max_chunk_tokens)
    Document->>Chunker: Instantiate and process chunking
    Chunker-->>Document: Return text chunks
    Document-->>Extractor: Yield processed chunks
    Extractor-->>TaskManager: Return aggregated chunks
Loading

Poem

I'm a rabbit, hopping with glee,
As chunks of text now dance free.
With TextChunker leading the way,
Our code leaps light into the day.
A tidy change, so swift and bright—
Hoppy coding, pure delight! 🐰✨

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (3)
cognee/modules/data/processing/document_types/Document.py (1)

12-12: Add type hint for chunker_cls parameter.

The base class should define the expected type for chunker_cls to ensure type safety across all document implementations.

-    def read(self, chunk_size: int, chunker_cls, max_chunk_tokens: Optional[int] = None) -> str:
+    def read(self, chunk_size: int, chunker_cls: type, max_chunk_tokens: Optional[int] = None) -> str:
cognee/modules/data/processing/document_types/ImageDocument.py (1)

17-19: Simplify the get_text lambda function.

The lambda function returning a single-item list could be simplified.

-            self, chunk_size=chunk_size, get_text=lambda: [text], max_chunk_tokens=max_chunk_tokens
+            self, chunk_size=chunk_size, get_text=lambda: iter([text]), max_chunk_tokens=max_chunk_tokens
cognee/tasks/documents/extract_chunks_from_documents.py (1)

32-38: Update docstring to reflect new chunker parameter type.

The docstring still implies string-based chunker configuration. Update it to clarify that chunker now expects a class reference.

    """
    Extracts chunks of data from a list of documents based on the specified chunking parameters.

    Notes:
        - The `read` method of the `Document` class must be implemented to support the chunking operation.
-        - The `chunker` parameter determines the chunking logic and should align with the document type.
+        - The `chunker` parameter expects a chunker class (e.g., TextChunker) that implements the chunking logic.
    """
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e4fd6a1 and af900ac.

📒 Files selected for processing (8)
  • cognee/api/v1/cognify/cognify_v2.py (2 hunks)
  • cognee/modules/data/processing/document_types/AudioDocument.py (1 hunks)
  • cognee/modules/data/processing/document_types/ChunkerMapping.py (0 hunks)
  • cognee/modules/data/processing/document_types/Document.py (1 hunks)
  • cognee/modules/data/processing/document_types/ImageDocument.py (1 hunks)
  • cognee/modules/data/processing/document_types/PdfDocument.py (1 hunks)
  • cognee/modules/data/processing/document_types/TextDocument.py (2 hunks)
  • cognee/tasks/documents/extract_chunks_from_documents.py (3 hunks)
💤 Files with no reviewable changes (1)
  • cognee/modules/data/processing/document_types/ChunkerMapping.py
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: lint (ubuntu-latest, 3.10.x)
  • GitHub Check: docker-compose-test
  • GitHub Check: Build Cognee Backend Docker App Image
🔇 Additional comments (5)
cognee/modules/data/processing/document_types/PdfDocument.py (1)

17-19: LGTM! Clean chunker instantiation.

The direct instantiation of the chunker class is cleaner and more maintainable than the previous string-based mapping approach.

cognee/modules/data/processing/document_types/TextDocument.py (1)

18-20: LGTM! Clean chunker instantiation.

The direct instantiation of the chunker class is cleaner and more maintainable than the previous string-based mapping approach.

cognee/modules/data/processing/document_types/AudioDocument.py (1)

15-22: LGTM! Clean refactoring of chunker instantiation.

The changes simplify the code by removing the string-based chunker mapping and directly using class references. The implementation maintains functionality while reducing indirection.

cognee/tasks/documents/extract_chunks_from_documents.py (1)

8-8: LGTM! Consistent refactoring of chunker instantiation.

The changes align with the broader refactoring effort:

  • TextChunker import added
  • Default chunker updated to use class reference
  • Parameter renamed in document.read call for consistency

Also applies to: 26-43

cognee/api/v1/cognify/cognify_v2.py (1)

28-28: LGTM! Task configuration updated correctly.

The changes properly integrate the new chunker class-based approach into the default task configuration:

  • TextChunker import added
  • Task instantiation updated with chunker parameter

Also applies to: 127-130

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
cognee/modules/data/processing/document_types/UnstructuredDocument.py (1)

31-33: Consider adding Protocol class for chunker interface.

The chunker instantiation is more flexible now, but we could improve type safety further.

Consider defining a Protocol class to enforce the chunker interface:

from typing import Protocol, Iterator

class ChunkerProtocol(Protocol):
    def __init__(self, document: Document, chunk_size: int, get_text: callable, max_chunk_tokens: int) -> None: ...
    def read(self) -> Iterator[str]: ...

def read(self, chunk_size: int, chunker_cls: type[ChunkerProtocol], max_chunk_tokens: int) -> str:
    ...
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between af900ac and 2dc0ba2.

📒 Files selected for processing (6)
  • cognee/modules/data/processing/document_types/AudioDocument.py (1 hunks)
  • cognee/modules/data/processing/document_types/Document.py (1 hunks)
  • cognee/modules/data/processing/document_types/ImageDocument.py (1 hunks)
  • cognee/modules/data/processing/document_types/PdfDocument.py (1 hunks)
  • cognee/modules/data/processing/document_types/TextDocument.py (2 hunks)
  • cognee/modules/data/processing/document_types/UnstructuredDocument.py (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • cognee/modules/data/processing/document_types/Document.py
  • cognee/modules/data/processing/document_types/PdfDocument.py
  • cognee/modules/data/processing/document_types/ImageDocument.py
  • cognee/modules/data/processing/document_types/TextDocument.py
⏰ Context from checks skipped due to timeout of 90000ms (22)
  • GitHub Check: run_notebook_test / test
  • GitHub Check: Test on macos-15
  • GitHub Check: run_eval_framework_test / test
  • GitHub Check: Test on macos-13
  • GitHub Check: run_dynamic_steps_example_test / test
  • GitHub Check: Test on macos-13
  • GitHub Check: run_simple_example_test / test
  • GitHub Check: run_multimedia_example_test / test
  • GitHub Check: run_notebook_test / test
  • GitHub Check: test
  • GitHub Check: test
  • GitHub Check: test
  • GitHub Check: test
  • GitHub Check: test
  • GitHub Check: Test on macos-13
  • GitHub Check: run_notebook_test / test
  • GitHub Check: windows-latest
  • GitHub Check: test
  • GitHub Check: test
  • GitHub Check: Build Cognee Backend Docker App Image
  • GitHub Check: docker-compose-test
  • GitHub Check: profiler
🔇 Additional comments (2)
cognee/modules/data/processing/document_types/AudioDocument.py (2)

13-13: LGTM! The signature change improves type safety.

The parameter change from chunker: str to chunker_cls: type is a good improvement that:

  • Makes the code more type-safe by expecting a class reference instead of a string
  • Provides better IDE support for code completion and type checking
  • Makes the parameter's purpose clearer through its naming

18-20: LGTM! The chunker instantiation is now more straightforward.

The direct instantiation of the chunker class simplifies the code by:

  • Removing the unnecessary indirection through ChunkerConfig
  • Maintaining a clean interface for passing the text content via lambda
  • Preserving all necessary parameters (chunk_size, get_text, max_chunk_tokens)

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
cognee/tests/integration/documents/UnstructuredDocument_test.py (1)

71-73: LGTM! Consistent parameter updates across document types.

The read() method calls have been consistently updated to use chunker_cls=TextChunker across all document types while maintaining existing chunking parameters.

Consider adding test cases for invalid chunker classes to ensure proper error handling:

def test_UnstructuredDocument_invalid_chunker():
    document = UnstructuredDocument(
        id=uuid.uuid4(),
        name="example.txt",
        raw_data_location="test.txt",
        external_metadata="",
        mime_type="text/plain",
    )
    
    # Test with invalid chunker class
    with pytest.raises(TypeError, match="chunker_cls must be a valid chunker class"):
        for _ in document.read(chunk_size=1024, chunker_cls=str, max_chunk_tokens=1024):
            pass

Also applies to: 81-83, 91-93, 103-105

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2dc0ba2 and 95e942b.

📒 Files selected for processing (5)
  • cognee/tests/integration/documents/AudioDocument_test.py (2 hunks)
  • cognee/tests/integration/documents/ImageDocument_test.py (2 hunks)
  • cognee/tests/integration/documents/PdfDocument_test.py (2 hunks)
  • cognee/tests/integration/documents/TextDocument_test.py (2 hunks)
  • cognee/tests/integration/documents/UnstructuredDocument_test.py (5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (28)
  • GitHub Check: Test on macos-15
  • GitHub Check: test
  • GitHub Check: Test on macos-13
  • GitHub Check: Test on macos-15
  • GitHub Check: Test on ubuntu-22.04
  • GitHub Check: Test on macos-13
  • GitHub Check: Test on macos-15
  • GitHub Check: Test on ubuntu-22.04
  • GitHub Check: Test on macos-13
  • GitHub Check: Test on ubuntu-22.04
  • GitHub Check: test
  • GitHub Check: test
  • GitHub Check: test
  • GitHub Check: test
  • GitHub Check: run_eval_framework_test / test
  • GitHub Check: windows-latest
  • GitHub Check: run_dynamic_steps_example_test / test
  • GitHub Check: test
  • GitHub Check: run_notebook_test / test
  • GitHub Check: run_notebook_test / test
  • GitHub Check: run_multimedia_example_test / test
  • GitHub Check: run_notebook_test / test
  • GitHub Check: run_simple_example_test / test
  • GitHub Check: test
  • GitHub Check: profiler
  • GitHub Check: docker-compose-test
  • GitHub Check: profiler
  • GitHub Check: Build Cognee Backend Docker App Image
🔇 Additional comments (9)
cognee/tests/integration/documents/TextDocument_test.py (2)

5-5: LGTM! Clean import addition.

The explicit import of TextChunker class improves code clarity and enables static type checking.


41-41: LGTM! Improved type safety in chunker specification.

The change from string identifier to class reference (chunker_cls=TextChunker) is a good improvement that:

  • Enables better IDE support and static type checking
  • Reduces the risk of runtime errors from invalid string identifiers
  • Makes the code more maintainable by making dependencies explicit
cognee/tests/integration/documents/PdfDocument_test.py (2)

3-3: LGTM! Import change aligns with the new chunker approach.

The explicit import of TextChunker is appropriate for the new class-based chunker implementation.


28-28: LGTM! Test updated correctly for new chunker API.

The test has been properly adapted to use the new class-based chunker approach while maintaining its effectiveness in validating document processing.

cognee/tests/integration/documents/AudioDocument_test.py (2)

3-3: LGTM!

The import of TextChunker aligns with the refactoring to use class references instead of string identifiers for chunker instantiation.


38-38: LGTM!

The update to use chunker_cls=TextChunker instead of a string identifier is consistent with the PR's objective to externalize chunker instantiation. The test's validation logic remains robust and comprehensive.

cognee/tests/integration/documents/UnstructuredDocument_test.py (1)

3-3: LGTM! Import aligns with chunker externalization.

The import of TextChunker class follows Python conventions and supports the transition from string-based to class-based chunker instantiation.

cognee/tests/integration/documents/ImageDocument_test.py (2)

3-3: LGTM!

The import of TextChunker aligns with the PR's objective of externalizing chunkers and is correctly used in the test.


26-27:

Details

✅ Verification successful

LGTM! Verify consistency across document types.

The change from chunker to chunker_cls=TextChunker aligns with the PR's objective and maintains the test's functionality.

Let's verify that this pattern is consistently applied across all document types:


🏁 Script executed:

#!/bin/bash
# Description: Check for consistent usage of chunker_cls parameter across document types

# Search for read method definitions in document types
echo "Checking read method signatures in document types:"
ast-grep --pattern 'def read(self, $$$, chunker_cls, $$$)'

# Search for read method calls to ensure consistent usage
echo "Checking read method calls:"
rg -A 2 'read\(' | rg 'chunker_cls'

Length of output: 2428


LGTM! Consistency verified across document types.

The updated call in cognee/tests/integration/documents/ImageDocument_test.py—using chunker_cls=TextChunker—is consistent with calls in the other document tests (Text, Audio, Pdf, and Unstructured) as well as with the corresponding method signatures in the document classes. One minor point: in cognee/tasks/documents/extract_chunks_from_documents.py, the call passes chunker_cls=chunker. If this was intentional (i.e., if the variable chunker already refers to the desired class type), then no changes are needed. Otherwise, please verify that this usage aligns with the standardized pattern across the codebase.

@alekszievr alekszievr self-assigned this Feb 17, 2025
Copy link
Member

@borisarzentar borisarzentar left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added 35 lines, removed 57, created more flexible solution. Beautiful.

@borisarzentar borisarzentar changed the title externalize chunker [cog-1354] feat: externalize chunkers [cog-1354] Feb 19, 2025
@alekszievr alekszievr merged commit 2a167fa into dev Feb 19, 2025
35 of 36 checks passed
@alekszievr alekszievr deleted the feat/cog-1354-externalize-chunker branch February 19, 2025 12:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants