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

Update fix/consolidated data cleanup #4203

Conversation

NicholasTurner23
Copy link
Contributor

@NicholasTurner23 NicholasTurner23 commented Jan 18, 2025

Description

This PR removes redundant code by centralizing data functionality in a single file.

Related Issues

  • JIRA cards:
    • OPS-332

Summary by CodeRabbit

Release Notes

  • Refactor

    • Replaced AirQoDataUtils with a new DataUtils class across multiple workflows
    • Updated data extraction and processing methods with improved error handling and logging
    • Introduced a new configuration mapping for data sources and table references
  • Bug Fixes

    • Enhanced error handling during data extraction and formatting processes
    • Updated BigQuery table references for more accurate data retrieval
  • New Features

    • Added dynamic data source configuration with DataSource dictionary
    • Implemented more flexible data formatting method for BigQuery interactions

Copy link
Contributor

coderabbitai bot commented Jan 18, 2025

📝 Walkthrough

Walkthrough

This pull request introduces significant refactoring of data extraction and processing utilities in the AirQo ETL workflows. The changes primarily involve consolidating data handling methods from AirQoDataUtils into a new DataUtils class, updating data source configurations, and enhancing logging capabilities. The modifications streamline data extraction processes across multiple DAGs, introducing more dynamic configuration management and improved error handling.

Changes

File Change Summary
src/workflows/airqo_etl_utils/airqo_utils.py Removed multiple BigQuery-related methods including extract_data_from_bigquery, format_data_for_bigquery, and process_*_data_for_bigquery. Updated clean_bam_data to use a different table reference.
src/workflows/airqo_etl_utils/config.py Added new DataSource dictionary for mapping data types, device categories, and frequencies to BigQuery tables.
src/workflows/airqo_etl_utils/datautils.py Added logging, introduced new format_data_for_bigquery method, enhanced error handling for data extraction.
src/workflows/dags/*_measurements.py Replaced AirQoDataUtils method calls with DataUtils, updated data type and frequency parameters.

Possibly related PRs

Suggested Labels

ready for review

Suggested Reviewers

  • Baalmart
  • Mnoble-19
  • BenjaminSsempala
  • Psalmz777

Poem

🌟 Data flows like rivers wild,
Refactored code, no longer riled
BigQuery tables dance and sing
As utils find their new wing! 🚀
Efficiency blooms, errors take flight

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)
src/workflows/airqo_etl_utils/datautils.py (2)

105-110: Add type hints to the static method decorator.

The method is missing the @staticmethod decorator and return type hint.

Apply this diff:

+    @staticmethod
     def format_data_for_bigquery(
         data: pd.DataFrame,
         datatype: DataType,
         device_category: DeviceCategory,
         frequency: Frequency,
-    ) -> pd.DataFrame:
+    ) -> pd.DataFrame:

Line range hint 242-243: Address the TODO comment and consider moving parameter mappings to configuration.

The TODO comment about cleaning up the code should be addressed, and the parameter mappings could be moved to the configuration file for better maintainability.

Would you like me to:

  1. Generate a cleaner implementation of this method?
  2. Create a configuration structure for the parameter mappings?
  3. Open a GitHub issue to track this cleanup task?
src/workflows/airqo_etl_utils/config.py (1)

389-410: Add docstring to explain the DataSource configuration structure.

The DataSource dictionary would benefit from documentation explaining its structure and usage.

Add this docstring above the DataSource dictionary:

+    """
+    Mapping of data types to their corresponding BigQuery tables.
+    
+    Structure:
+    DataSource = {
+        DataType: {
+            DeviceCategory: {
+                Frequency: table_name
+            }
+        }
+    }
+    """
     DataSource = {
         DataType.RAW: {
             DeviceCategory.GENERAL: {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b3a838a and a4e9bcd.

📒 Files selected for processing (6)
  • src/workflows/airqo_etl_utils/airqo_utils.py (1 hunks)
  • src/workflows/airqo_etl_utils/config.py (2 hunks)
  • src/workflows/airqo_etl_utils/datautils.py (4 hunks)
  • src/workflows/dags/airqo_bam_measurements.py (5 hunks)
  • src/workflows/dags/airqo_measurements.py (7 hunks)
  • src/workflows/dags/daily_measurements.py (4 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
src/workflows/airqo_etl_utils/datautils.py

82-82: Local variable e is assigned to but never used

Remove assignment to unused variable e

(F841)


86-86: Local variable e is assigned to but never used

Remove assignment to unused variable e

(F841)


133-133: Local variable e is assigned to but never used

Remove assignment to unused variable e

(F841)


137-137: Local variable e is assigned to but never used

Remove assignment to unused variable e

(F841)

src/workflows/dags/airqo_measurements.py

483-483: Undefined name data

(F821)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (10)
src/workflows/airqo_etl_utils/airqo_utils.py (1)

473-473: Ensure consistency in table references for BAM data.

The table reference in the clean_bam_data method has been updated to bam_hourly_measurements_table. Please verify that all occurrences of bam_measurements_table have been updated across the codebase to maintain consistency.

Run the following script to check for any remaining references to the old table name:

src/workflows/dags/daily_measurements.py (3)

38-42: Update data extraction to use DataUtils with device category parameter.

The extract function now utilizes DataUtils.extract_data_from_bigquery with device_category set to DeviceCategory.GENERAL. This change aligns with the refactored data utilities and ensures proper categorization of devices during data extraction.


74-78: Duplicate of previous comment regarding DataUtils usage.


113-117: Duplicate of previous comment regarding DataUtils usage.

src/workflows/dags/airqo_bam_measurements.py (6)

41-42: Switch to DataUtils.format_data_for_bigquery for data formatting.

The code now uses DataUtils.format_data_for_bigquery to format data before loading into BigQuery, providing consistency across data processing tasks.


56-57: Duplicate of previous comment regarding DataUtils usage.


103-104: Duplicate of previous comment regarding DataUtils usage.


123-124: Duplicate of previous comment regarding DataUtils usage.


129-129: Ensure consistency in BAM table references.

The table reference has been updated to bam_hourly_measurements_table. Please verify that all instances of bam_measurements_table have been updated throughout the codebase to maintain consistency.

Run the following script to find any remaining references to the old table name:


62-62: Ensure consistency in BAM table references.

The table reference has been updated to bam_hourly_measurements_table. Please verify that all instances of bam_measurements_table have been updated throughout the codebase to maintain consistency.

Run the following script to find any remaining references to the old table name:

Comment on lines +79 to +87
try:
source = configuration.DataSource.get(datatype)
table = source.get(device_category).get(frequency)
except KeyError as e:
logger.exception(
f"Invalid combination: {datatype}, {device_category}, {frequency}"
)
except Exception as e:
logger.exception("An unexpected error occurred during column retrieval")
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

Enhance error handling by including original error messages.

The current error handling loses valuable context by not including the original error message in the logs.

Apply this diff to improve error handling:

 try:
     source = configuration.DataSource.get(datatype)
     table = source.get(device_category).get(frequency)
 except KeyError as e:
     logger.exception(
-        f"Invalid combination: {datatype}, {device_category}, {frequency}"
+        f"Invalid combination: {datatype}, {device_category}, {frequency}. Error: {str(e)}"
     )
+    raise
 except Exception as e:
     logger.exception("An unexpected error occurred during column retrieval")
+    raise
📝 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
try:
source = configuration.DataSource.get(datatype)
table = source.get(device_category).get(frequency)
except KeyError as e:
logger.exception(
f"Invalid combination: {datatype}, {device_category}, {frequency}"
)
except Exception as e:
logger.exception("An unexpected error occurred during column retrieval")
try:
source = configuration.DataSource.get(datatype)
table = source.get(device_category).get(frequency)
except KeyError as e:
logger.exception(
f"Invalid combination: {datatype}, {device_category}, {frequency}. Error: {str(e)}"
)
raise
except Exception as e:
logger.exception("An unexpected error occurred during column retrieval")
raise
🧰 Tools
🪛 Ruff (0.8.2)

82-82: Local variable e is assigned to but never used

Remove assignment to unused variable e

(F841)


86-86: Local variable e is assigned to but never used

Remove assignment to unused variable e

(F841)

Comment on lines +130 to +140
try:
datasource = configuration.DataSource
cols = datasource.get(datatype).get(device_category).get(frequency)
except KeyError as e:
logger.exception(
f"Invalid combination: {datatype}, {device_category}, {frequency}"
)
except Exception as e:
logger.exception("An unexpected error occurred during column retrieval")

return Utils.populate_missing_columns(data=data, columns=cols)
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

Initialize cols variable and improve error handling.

The cols variable could be undefined if an exception occurs, and the error handling could be more informative.

Apply this diff:

+        cols = []
         try:
             datasource = configuration.DataSource
             cols = datasource.get(datatype).get(device_category).get(frequency)
         except KeyError as e:
             logger.exception(
-                f"Invalid combination: {datatype}, {device_category}, {frequency}"
+                f"Invalid combination: {datatype}, {device_category}, {frequency}. Error: {str(e)}"
             )
+            raise
         except Exception as e:
             logger.exception("An unexpected error occurred during column retrieval")
+            raise

         return Utils.populate_missing_columns(data=data, columns=cols)
📝 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
try:
datasource = configuration.DataSource
cols = datasource.get(datatype).get(device_category).get(frequency)
except KeyError as e:
logger.exception(
f"Invalid combination: {datatype}, {device_category}, {frequency}"
)
except Exception as e:
logger.exception("An unexpected error occurred during column retrieval")
return Utils.populate_missing_columns(data=data, columns=cols)
cols = []
try:
datasource = configuration.DataSource
cols = datasource.get(datatype).get(device_category).get(frequency)
except KeyError as e:
logger.exception(
f"Invalid combination: {datatype}, {device_category}, {frequency}. Error: {str(e)}"
)
raise
except Exception as e:
logger.exception("An unexpected error occurred during column retrieval")
raise
return Utils.populate_missing_columns(data=data, columns=cols)
🧰 Tools
🪛 Ruff (0.8.2)

133-133: Local variable e is assigned to but never used

Remove assignment to unused variable e

(F841)


137-137: Local variable e is assigned to but never used

Remove assignment to unused variable e

(F841)

Comment on lines +482 to +484
data = DataUtils.format_data_for_bigquery(
data, DataType.AVERAGED, DeviceCategory.GENERAL, Frequency.HOURLY
)
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

Fix undefined variable in send_hourly_measurements_to_bigquery.

The variable 'data' is undefined. It should be 'airqo_data' based on the method parameter.

Apply this diff:

-        data = DataUtils.format_data_for_bigquery(
-            data, DataType.AVERAGED, DeviceCategory.GENERAL, Frequency.HOURLY
+        data = DataUtils.format_data_for_bigquery(
+            airqo_data, DataType.AVERAGED, DeviceCategory.GENERAL, Frequency.HOURLY
         )
📝 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
data = DataUtils.format_data_for_bigquery(
data, DataType.AVERAGED, DeviceCategory.GENERAL, Frequency.HOURLY
)
data = DataUtils.format_data_for_bigquery(
airqo_data, DataType.AVERAGED, DeviceCategory.GENERAL, Frequency.HOURLY
)
🧰 Tools
🪛 Ruff (0.8.2)

483-483: Undefined name data

(F821)

@Baalmart Baalmart merged commit 3ab8f93 into airqo-platform:staging Jan 18, 2025
46 checks passed
@Baalmart Baalmart mentioned this pull request Jan 18, 2025
2 tasks
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.

2 participants