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

closes #12 #14

Closed
wants to merge 3 commits into from
Closed

closes #12 #14

wants to merge 3 commits into from

Conversation

NitikaBahl
Copy link

@NitikaBahl NitikaBahl commented Dec 13, 2024

Issue Number

Purpose

•	This PR modifies the data splitting functionality to handle multiple CSV files within a specified directory, and ensures that empty files are skipped. It also improves logging and error handling.

Technical Details

•	The function split_multiple_files was introduced to handle multiple CSV files in the input directory.
•	The code now checks if a file is empty before attempting to split it.
•	The split datasets (train/test) are saved to a new split directory.
•	Added more detailed print statements for clarity and error handling.

Testing Instructions

1.	Ensure the directory contains multiple .csv files (e.g., step1_1_storybook_learning_events.csv, step1_1_storybooks.csv).
2.	Run the script and verify that the data is split into train and test files for each CSV file.
3.	Check that empty files are skipped and a message is printed.
4.	Ensure that the split files are stored in the split directory within the input folder.

Screenshots

•	No UI changes have been made.

Summary by CodeRabbit

  • New Features

    • Added functionality for splitting multiple CSV files into training and testing datasets.
    • Introduced a new method for optimizing memory usage during data processing.
    • Included the tqdm package for progress tracking during file processing.
  • Bug Fixes

    • Resolved issues by uncommenting necessary code for data splitting functionality.
  • Chores

    • Updated the requirements file to include the scikit-learn and tqdm packages.

@NitikaBahl NitikaBahl requested a review from a team as a code owner December 13, 2024 18:57
Copy link

coderabbitai bot commented Dec 13, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The changes in this pull request involve modifications to three files. The requirements.txt file has been updated to include the scikit-learn and tqdm packages without specified versions, and it is missing a newline at the end. The run_all_steps.py script has been altered to enable data splitting functionality by uncommenting relevant code. Additionally, the step1_3_split_data.py file has been introduced, containing the split_multiple_files function, which includes enhanced error handling and memory optimization for splitting multiple CSV files into training and testing datasets.

Changes

File Change Summary
requirements.txt Added scikit-learn and tqdm packages; no versions specified; missing newline at the end.
run_all_steps.py Uncommented import statement for step1_3_split_data; enabled execution of data splitting step.
step1_prepare/step1_3_split_data.py Introduced split_multiple_files function with error handling and memory optimization for CSV files.

Assessment against linked issues

Objective Addressed Explanation
Split the preprocessed data into a training set and a test set. (#12)

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. This feature will be included in our Pro Plan when released.


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 822fcd2 and 5401689.

⛔ Files ignored due to path filters (2)
  • step1_prepare/split/test_step1_1_storybook_learning_events.csv is excluded by !**/*.csv
  • step1_prepare/split/train_step1_1_storybook_learning_events.csv is excluded by !**/*.csv
📒 Files selected for processing (3)
  • requirements.txt (1 hunks)
  • run_all_steps.py (1 hunks)
  • step1_prepare/step1_3_split_data.py (1 hunks)

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

@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: 4

🧹 Outside diff range and nitpick comments (1)
step1_prepare/step1_3_split_data.py (1)

1-5: Add type hints and docstring for better code documentation

Consider adding type hints and a comprehensive docstring to improve code maintainability and documentation.

 import os
 import pandas as pd
 from sklearn.model_selection import train_test_split
 
-def split_multiple_files(input_directory, train_ratio=0.8):
+def split_multiple_files(input_directory: str, train_ratio: float = 0.8) -> None:
+    """Split multiple CSV files into training and testing datasets.
+    
+    Args:
+        input_directory: Directory containing CSV files to split
+        train_ratio: Ratio of data to use for training (default: 0.8)
+    
+    Raises:
+        ValueError: If train_ratio is not between 0 and 1
+    """
+    if not 0 < train_ratio < 1:
+        raise ValueError("train_ratio must be between 0 and 1")
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5b8791b and 822fcd2.

⛔ Files ignored due to path filters (4)
  • step1_prepare/split/test_step1_1_storybook_learning_events.csv is excluded by !**/*.csv
  • step1_prepare/split/test_step1_1_storybooks.csv is excluded by !**/*.csv
  • step1_prepare/split/train_step1_1_storybook_learning_events.csv is excluded by !**/*.csv
  • step1_prepare/split/train_step1_1_storybooks.csv is excluded by !**/*.csv
📒 Files selected for processing (3)
  • requirements.txt (1 hunks)
  • run_all_steps.py (1 hunks)
  • step1_prepare/step1_3_split_data.py (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • requirements.txt

run_all_steps.py Outdated

# Step 1.3 Split Data
import step1_prepare.step1_3_split_data
step1_prepare.step1_3_split_data.split_multiple_files(input_directory='/Users/nitikabahl/story recemonder/ml-storybook-recommender/step1_prepare/')
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Replace hardcoded absolute path with relative path

The current implementation uses a hardcoded absolute path that:

  1. Contains spaces which could cause issues
  2. Is specific to a user's local machine
  3. Won't work in different environments

Consider using a relative path instead:

-step1_prepare.step1_3_split_data.split_multiple_files(input_directory='/Users/nitikabahl/story recemonder/ml-storybook-recommender/step1_prepare/')
+step1_prepare.step1_3_split_data.split_multiple_files(input_directory='.')
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
step1_prepare.step1_3_split_data.split_multiple_files(input_directory='/Users/nitikabahl/story recemonder/ml-storybook-recommender/step1_prepare/')
step1_prepare.step1_3_split_data.split_multiple_files(input_directory='.')

Comment on lines 44 to 46
if __name__ == "__main__":
# Example usage for splitting multiple files in a directory
split_multiple_files(input_directory='/Users/nitikabahl/story recemonder/ml-storybook-recommender/step1_prepare/')
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove hardcoded path from example usage

The example usage contains the same hardcoded path issue as in run_all_steps.py.

 if __name__ == "__main__":
     # Example usage for splitting multiple files in a directory
-    split_multiple_files(input_directory='/Users/nitikabahl/story recemonder/ml-storybook-recommender/step1_prepare/')
+    split_multiple_files(input_directory='.')
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if __name__ == "__main__":
# Example usage for splitting multiple files in a directory
split_multiple_files(input_directory='/Users/nitikabahl/story recemonder/ml-storybook-recommender/step1_prepare/')
if __name__ == "__main__":
# Example usage for splitting multiple files in a directory
split_multiple_files(input_directory='.')

Comment on lines 6 to 12
# Get list of all CSV files in the directory
csv_files = [f for f in os.listdir(input_directory) if f.endswith('.csv')]

# Check if any CSV files were found
if not csv_files:
print("No CSV files found in the directory.")
return
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Enhance input validation and error handling

The current implementation needs more robust input validation and error handling:

  1. Directory existence check
  2. Permission validation
  3. Case-insensitive CSV extension matching
 def split_multiple_files(input_directory: str, train_ratio: float = 0.8) -> None:
+    # Validate directory
+    if not os.path.isdir(input_directory):
+        raise ValueError(f"Directory not found: {input_directory}")
+
     # Get list of all CSV files in the directory
-    csv_files = [f for f in os.listdir(input_directory) if f.endswith('.csv')]
+    try:
+        csv_files = [f for f in os.listdir(input_directory) 
+                    if f.lower().endswith('.csv')]
+    except PermissionError:
+        raise PermissionError(f"Permission denied accessing: {input_directory}")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
# Get list of all CSV files in the directory
csv_files = [f for f in os.listdir(input_directory) if f.endswith('.csv')]
# Check if any CSV files were found
if not csv_files:
print("No CSV files found in the directory.")
return
# Validate directory
if not os.path.isdir(input_directory):
raise ValueError(f"Directory not found: {input_directory}")
# Get list of all CSV files in the directory
try:
csv_files = [f for f in os.listdir(input_directory)
if f.lower().endswith('.csv')]
except PermissionError:
raise PermissionError(f"Permission denied accessing: {input_directory}")
# Check if any CSV files were found
if not csv_files:
print("No CSV files found in the directory.")
return

Comment on lines 15 to 42
for file in csv_files:
input_file = os.path.join(input_directory, file)

# Load dataset
print(f"Loading data from {input_file}...")
data = pd.read_csv(input_file)

# Check if the dataset is empty
if data.empty:
print(f"Warning: {file} is empty. Skipping...")
continue

# Split data
print(f"Splitting data into {int(train_ratio*100)}% train and {int((1-train_ratio)*100)}% test sets.")
train_data, test_data = train_test_split(data, test_size=(1 - train_ratio), random_state=42)

# Save splits
output_dir = os.path.join(input_directory, 'split')
os.makedirs(output_dir, exist_ok=True)

train_output = os.path.join(output_dir, f"train_{file}")
test_output = os.path.join(output_dir, f"test_{file}")

# Save the split datasets to CSV
train_data.to_csv(train_output, index=False)
test_data.to_csv(test_output, index=False)

print(f"Data from {file} split and saved successfully.")
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve error handling and memory efficiency

The main processing loop needs several improvements:

  1. Error handling for file operations
  2. Memory optimization for large files
  3. Progress tracking for multiple files
+    total_files = len(csv_files)
+    for idx, file in enumerate(csv_files, 1):
         input_file = os.path.join(input_directory, file)
         
         # Load dataset
-        print(f"Loading data from {input_file}...")
+        print(f"Processing file {idx}/{total_files}: {file}")
+        try:
             data = pd.read_csv(input_file)
+        except Exception as e:
+            print(f"Error reading {file}: {str(e)}")
+            continue
         
         # Check if the dataset is empty
         if data.empty:
             print(f"Warning: {file} is empty. Skipping...")
             continue
         
+        # Validate data structure
+        if len(data.columns) == 0:
+            print(f"Warning: {file} has no columns. Skipping...")
+            continue
+
         # Split data
         print(f"Splitting data into {int(train_ratio*100)}% train and {int((1-train_ratio)*100)}% test sets.")
-        train_data, test_data = train_test_split(data, test_size=(1 - train_ratio), random_state=42)
+        try:
+            # Process in chunks for large files
+            chunk_size = 100000  # Adjust based on available memory
+            if len(data) > chunk_size:
+                train_chunks = []
+                test_chunks = []
+                for chunk in pd.read_csv(input_file, chunksize=chunk_size):
+                    train_chunk, test_chunk = train_test_split(
+                        chunk, test_size=(1 - train_ratio), random_state=42
+                    )
+                    train_chunks.append(train_chunk)
+                    test_chunks.append(test_chunk)
+                train_data = pd.concat(train_chunks)
+                test_data = pd.concat(test_chunks)
+            else:
+                train_data, test_data = train_test_split(
+                    data, test_size=(1 - train_ratio), random_state=42
+                )
+        except Exception as e:
+            print(f"Error splitting {file}: {str(e)}")
+            continue

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

@NitikaBahl NitikaBahl closed this Dec 14, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Split data
1 participant