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

Forecast routes with batch processing and enhanced health tips #4110

Closed
wants to merge 5 commits into from

Conversation

Baalmart
Copy link
Contributor

@Baalmart Baalmart commented Dec 21, 2024

Description

Optimise forecast routes with batch processing and enhanced health tips handling

Changes Made

  • Implemented centralized error handling via custom decorator for forecast routes
  • Added batch processing for multiple site forecasts to improve memory management
  • Optimized health tips fetching to reduce API calls
  • Added type hints for better code maintainability
  • Separated forecast processing logic into modular functions
  • Created cached version of health tips handler to improve performance
  • Standardized response format across all forecast endpoints
  • Improved error handling and logging for forecast processing
  • Maintained existing caching strategies while optimizing data reuse

Testing

  • Tested locally
  • Tested against staging environment
  • Relevant tests passed: [List test names]

Affected Services

  • Which services were modified:
    • Predict

Endpoints Ready for Testing

  • New endpoints ready for testing:
    • get daily forecasts
    • get hourly forecasts

API Documentation Updated?

  • Yes, API documentation was updated
  • No, API documentation does not need updating

Summary by CodeRabbit

  • New Features

    • Introduced centralized configuration for Air Quality Index (AQI) ranges and default health tips.
    • Enhanced health tips retrieval with improved error handling and validation.
    • Added functionality to process forecasts more efficiently, including batch processing.
    • Implemented a fallback mechanism for retrieving health tips from static sources.
  • Bug Fixes

    • Improved error handling across various forecast-related endpoints for more consistent responses.
  • Documentation

    • Added type hints for better code clarity and maintainability.

Copy link
Contributor

coderabbitai bot commented Dec 21, 2024

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

📝 Walkthrough
📝 Walkthrough
📝 Walkthrough
📝 Walkthrough
📝 Walkthrough

Walkthrough

This pull request introduces comprehensive enhancements to air quality forecast processing and health tips retrieval. The changes centralize AQI range configurations, improve error handling for health tips API interactions, and optimize forecast processing. The modifications focus on creating more robust, flexible methods for retrieving and presenting air quality health recommendations across different scenarios.

Changes

File Change Summary
src/predict/api/helpers.py - Added AQI_RANGES and DEFAULT_HEALTH_TIPS constants
- Enhanced get_health_tips with improved error handling
- Introduced get_static_health_tip and add_forecast_health_tips_cached functions
src/predict/api/prediction.py - Added DEFAULT_HEALTH_TIPS constant
- Introduced handle_forecast_response decorator
- Added process_forecasts, process_single_site, and process_multiple_sites functions

Sequence Diagram

sequenceDiagram
    participant Client
    participant ForecastAPI
    participant HealthTipsAPI
    participant ProcessingLogic

    Client->>ForecastAPI: Request Forecast
    ForecastAPI-->>ProcessingLogic: Return Forecast Data
    ProcessingLogic->>HealthTipsAPI: Fetch Health Tips
    alt Health Tips API Success
        HealthTipsAPI-->>ProcessingLogic: Return Health Tips
    else Health Tips API Failure
        ProcessingLogic->>ProcessingLogic: Use Static Health Tips
    end
    ProcessingLogic-->>Client: Enhanced Forecast with Health Tips
Loading

Possibly related PRs

Suggested labels

ready for review, priority-high

Suggested reviewers

  • sserurich
  • Mnoble-19

Poem

🌬️ Whispers of Air, Data's Embrace
Health tips dancing with grace
AQI ranges, a digital song
Processing forecasts, nothing wrong
Code's poetry, clean and bright! 🌈


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.

@Baalmart Baalmart marked this pull request as draft December 21, 2024 08:25
Copy link

codecov bot commented Dec 21, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 11.88%. Comparing base (cd6b7f6) to head (9580dac).
Report is 270 commits behind head on staging.

Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff            @@
##           staging    #4110   +/-   ##
========================================
  Coverage    11.88%   11.88%           
========================================
  Files          117      117           
  Lines        15549    15549           
  Branches       319      319           
========================================
  Hits          1848     1848           
  Misses       13701    13701           

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 (4)
src/predict/api/prediction.py (2)

7-7: Remove unused import “Optional”.
The symbol 'Optional' is never used in the file. Consider removing it to keep imports clean.

-from typing import Dict, List, Optional, Union, Callable
+from typing import Dict, List, Union, Callable
🧰 Tools
🪛 Ruff (0.8.2)

7-7: typing.Optional imported but unused

Remove unused import: typing.Optional

(F401)


157-157: Remove extraneous f-string prefix.
This f-string has no placeholder and can be converted to a normal string.

- "message": f"Forecasts successfully retrieved.",
+ "message": "Forecasts successfully retrieved.",
🧰 Tools
🪛 Ruff (0.8.2)

157-157: f-string without any placeholders

Remove extraneous f prefix

(F541)

src/predict/api/helpers.py (2)

566-569: Combine conditional branches with a logical or.
Merging these if statements improves readability by reducing nested conditionals.

-for category, range_info in aqi_ranges.items():
-    if range_info['max'] is None and pm2_5_value >= range_info['min']:
-        return DEFAULT_HEALTH_TIPS.get(category, {})
-    elif range_info['max'] is not None and range_info['min'] <= pm2_5_value <= range_info['max']:
-        return DEFAULT_HEALTH_TIPS.get(category, {})
+for category, range_info in aqi_ranges.items():
+    if (
+        (range_info['max'] is None and pm2_5_value >= range_info['min'])
+        or
+        (range_info['max'] is not None and range_info['min'] <= pm2_5_value <= range_info['max'])
+    ):
+        return DEFAULT_HEALTH_TIPS.get(category, {})
🧰 Tools
🪛 Ruff (0.8.2)

566-569: Combine if branches using logical or operator

Combine if branches

(SIM114)


590-590: Rename “site_id” to “_site_id” if it’s unused.
The loop variable “site_id” is unused inside the loop body. Renaming it to “_site_id” clarifies it’s unused.

Example fix for lines around 590 and 629:

-for site_id, forecasts in results.items():
+for _site_id, forecasts in results.items():
    for forecast in forecasts:
        ...

Also applies to: 629-629

🧰 Tools
🪛 Ruff (0.8.2)

590-590: Loop control variable site_id not used within loop body

Rename unused site_id to _site_id

(B007)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between cd6b7f6 and 06cecf3.

📒 Files selected for processing (2)
  • src/predict/api/helpers.py (3 hunks)
  • src/predict/api/prediction.py (5 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
src/predict/api/prediction.py

7-7: typing.Optional imported but unused

Remove unused import: typing.Optional

(F401)


157-157: f-string without any placeholders

Remove extraneous f prefix

(F541)

src/predict/api/helpers.py

566-569: Combine if branches using logical or operator

Combine if branches

(SIM114)


590-590: Loop control variable site_id not used within loop body

Rename unused site_id to _site_id

(B007)


621-621: Undefined name Dict

(F821)


622-622: Undefined name List

(F821)


624-624: Undefined name Dict

(F821)


629-629: Loop control variable site_id not used within loop body

Rename unused site_id to _site_id

(B007)

Comment on lines +621 to +624
results: Dict,
cached_health_tips: List,
language: str
) -> Dict:
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

Add import for Dict and List.
Python’s typing “Dict” and “List” references are undefined. Ensure they are imported properly.

+from typing import Dict, List

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

🧰 Tools
🪛 Ruff (0.8.2)

621-621: Undefined name Dict

(F821)


622-622: Undefined name List

(F821)


624-624: Undefined name Dict

(F821)

Copy link
Contributor

Predict service changes in this PR available for preview here

Copy link
Contributor

Predict service changes in this PR available for preview here

Comment on lines +171 to +175
return jsonify({
"message": "An error occurred processing the forecast.",
"error": str(e), # Include the exception message for debugging
"success": False,
}), 500

Check warning

Code scanning / CodeQL

Information exposure through an exception Medium

Stack trace information
flows to this location and may be exposed to an external user.

Copilot Autofix AI 22 days ago

To fix the problem, we should modify the handle_error function to return a generic error message to the user instead of including the exception message. The detailed error information should still be logged on the server for debugging purposes. This way, we can prevent sensitive information from being exposed to external users while still retaining the ability to debug issues.

Suggested changeset 1
src/predict/api/prediction.py

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/src/predict/api/prediction.py b/src/predict/api/prediction.py
--- a/src/predict/api/prediction.py
+++ b/src/predict/api/prediction.py
@@ -164,13 +164,12 @@
 
-def handle_error(e: Exception) -> tuple:
-    """ Handle errors by logging and returning a standardized error response. """
-    # Log the error with detailed information
-    current_app.logger.error(f"Error processing forecast: {str(e)}", exc_info=True)
-    
-    # Return a detailed error response including the exception message
-    return jsonify({
-        "message": "An error occurred processing the forecast.",
-        "error": str(e),  # Include the exception message for debugging
-        "success": False,
-    }), 500
+def handle_error(e: Exception) -> tuple:
+    """ Handle errors by logging and returning a standardized error response. """
+    # Log the error with detailed information
+    current_app.logger.error(f"Error processing forecast: {str(e)}", exc_info=True)
+    
+    # Return a generic error response without the exception message
+    return jsonify({
+        "message": "An error occurred processing the forecast.",
+        "success": False,
+    }), 500
 
EOF
@@ -164,13 +164,12 @@

def handle_error(e: Exception) -> tuple:
""" Handle errors by logging and returning a standardized error response. """
# Log the error with detailed information
current_app.logger.error(f"Error processing forecast: {str(e)}", exc_info=True)

# Return a detailed error response including the exception message
return jsonify({
"message": "An error occurred processing the forecast.",
"error": str(e), # Include the exception message for debugging
"success": False,
}), 500
def handle_error(e: Exception) -> tuple:
""" Handle errors by logging and returning a standardized error response. """
# Log the error with detailed information
current_app.logger.error(f"Error processing forecast: {str(e)}", exc_info=True)

# Return a generic error response without the exception message
return jsonify({
"message": "An error occurred processing the forecast.",
"success": False,
}), 500

Copilot is powered by AI and may make mistakes. Always verify output.
Positive Feedback
Negative Feedback

Provide additional feedback

Please help us improve GitHub Copilot by sharing more details about this comment.

Please select one or more of the options
Copy link
Contributor

Predict service changes in this PR available for preview here

Copy link
Contributor

Predict service changes in this PR available for preview here

@Baalmart Baalmart closed this Jan 3, 2025
@Baalmart Baalmart deleted the optimize-forecast-routes branch January 3, 2025 18:27
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.

1 participant