Skip to content
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

Fix dlt for metadata #247

Merged
merged 3 commits into from
Dec 4, 2024
Merged

Fix dlt for metadata #247

merged 3 commits into from
Dec 4, 2024

Conversation

dexters1
Copy link
Collaborator

@dexters1 dexters1 commented Dec 4, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced data ingestion process for improved handling of file paths and metadata.
    • Introduced a new asynchronous function for data storage, streamlining the interaction with the database.
  • Bug Fixes

    • Improved type-checking logic for data items related to the llama_index module.
  • Refactor

    • Restructured the data ingestion control flow for better modularity and clarity.

Resolve issue caused by dlt for ingest_data_with_metadata task

Fix
Resolve issue with llama index type resolution

Fix
Copy link
Contributor

coderabbitai bot commented Dec 4, 2024

Walkthrough

The pull request introduces significant modifications to the data ingestion process in the ingest_data_with_metadata function and related components. The data_resources function now accepts file paths as strings, iterating over them to yield metadata dictionaries. A new asynchronous function, data_storing, is added to manage data item storage and metadata handling, improving modularity. Additionally, the save_data_item_with_metadata_to_storage function refines its type-checking logic for data_item related to the llama_index module, while the overall control flow remains unchanged.

Changes

File Path Change Summary
cognee/tasks/ingestion/ingest_data_with_metadata.py - Modified ingest_data_with_metadata function logic.
- Changed data_resources to accept file_paths as a string.
- Introduced new async function data_storing for data storage.
cognee/tasks/ingestion/save_data_item_with_metadata_to_storage.py - Updated type-checking logic for data_item related to llama_index.
- Rearranged comments in the function.

Possibly related PRs

  • Cog 337 llama index support #186: The changes in the main PR involve significant modifications to the ingest_data_with_metadata function, which includes data ingestion and storage processes. While the retrieved PR focuses on the add function in a different file, it does not directly relate to the ingestion or storage logic, thus no strong connection is established.

Suggested reviewers

  • Vasilije1990
  • 0xideas
  • borisarzentar

🐰 In the fields where data flows,
A rabbit hops where knowledge grows.
With paths anew, we store with care,
Metadata dances in the air!
Ingesting files, a joyful feat,
Our code now sings, oh, what a treat! 🌼


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 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.

@Vasilije1990 Vasilije1990 self-requested a review December 4, 2024 10:58
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: 2

🧹 Outside diff range and nitpick comments (4)
cognee/tasks/ingestion/ingest_data_with_metadata.py (4)

28-29: Use asynchronous file I/O for better performance in data_resources.

Since data_resources is an asynchronous function, using asynchronous file operations can improve performance and avoid blocking the event loop.

Consider using aiofiles for asynchronous file handling:

import aiofiles

async with aiofiles.open(file_path.replace("file://", ""), mode="rb") as file:
    classified_data = ingestion.classify(file)
    # Rest of the code...

Ensure that aiofiles is added to your project's dependencies.


Line range hint 41-99: Refactor to eliminate duplication between data_storing and data_resources.

Both functions process files and extract metadata. To adhere to the DRY (Don't Repeat Yourself) principle, consider extracting the shared logic into a separate function.

For example, create a helper function:

async def process_file(file_path: str):
    with open(file_path.replace("file://", ""), mode="rb") as file:
        classified_data = ingestion.classify(file)
        data_id = ingestion.identify(classified_data)
        file_metadata = classified_data.get_metadata()
    return data_id, file_metadata

Then update data_storing and data_resources to use this function.


Line range hint 55-99: Add error handling to data_storing function.

Exceptions during file processing or database operations may cause the function to fail silently. Adding try-except blocks with proper logging will enhance robustness.

Consider wrapping critical sections with exception handling:

import logging

# Initialize logger
logger = logging.getLogger(__name__)

# Inside data_storing function
try:
    # Existing code...
except Exception as e:
    logger.error(f"An error occurred while processing data: {e}")
    # Handle exception as needed

Ensure that the logging configuration is set up appropriately in your application.


103-125: Simplify pipeline.run calls to reduce code duplication.

The two pipeline.run calls differ only in the dataset_name parameter. Streamline the code by setting dataset_name conditionally and making a single call.

Apply this refactor:

if db_engine.engine.dialect.name == "sqlite":
    dataset_name_for_run = "main"  # SQLite doesn't support schemas
else:
    dataset_name_for_run = dataset_name

run_info = pipeline.run(
    data_resources(file_paths),
    table_name="file_metadata",
    dataset_name=dataset_name_for_run,
    write_disposition="merge",
)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 4678aae and c505ee5.

📒 Files selected for processing (2)
  • cognee/tasks/ingestion/ingest_data_with_metadata.py (2 hunks)
  • cognee/tasks/ingestion/save_data_item_with_metadata_to_storage.py (1 hunks)

@dlt.resource(standalone = True, merge_key = "id")
async def data_resources(data: Any, user: User):
@dlt.resource(standalone=True, merge_key="id")
async def data_resources(file_paths: str):
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Correct the type annotation for file_paths in data_resources.

The file_paths parameter should be annotated as a list of strings (List[str]), not str, since it is iterated over in the function.

Apply this diff to fix the type annotation:

-from typing import Any
+from typing import Any, List

 @dlt.resource(standalone=True, merge_key="id")
-async def data_resources(file_paths: str):
+async def data_resources(file_paths: List[str]):

Committable suggestion skipped: line range outside the PR's diff.

# Check if data is of type Document or any of it's subclasses
if str(type(data_item)).startswith("llama_index"):

if "llama_index" in str(type(data_item)):
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve type checking for data_item to avoid using str(type(data_item)).

Using str(type(data_item)) for type checking is not robust and can lead to maintenance issues. Consider using isinstance, duck typing, or checking for specific attributes.

Since llama_index is an optional dependency, you can perform type checking as follows:

try:
    from llama_index import LlamaIndexType  # Replace with the actual type
except ImportError:
    LlamaIndexType = None

if LlamaIndexType and isinstance(data_item, LlamaIndexType):
    # Process data_item

Alternatively, use attribute checks:

if hasattr(data_item, 'some_unique_attribute'):
    # Process data_item

This approach is more reliable and easier to maintain.

@Vasilije1990 Vasilije1990 merged commit 1a963f1 into main Dec 4, 2024
37 of 38 checks passed
@Vasilije1990 Vasilije1990 deleted the fix-dlt-for-metadata branch December 4, 2024 11:05
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.

2 participants