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

feat(ml): predict reading level during epub import #1822

Conversation

jo-elimu
Copy link
Member

@jo-elimu jo-elimu commented Aug 16, 2024

@jo-elimu jo-elimu self-assigned this Aug 16, 2024
@jo-elimu jo-elimu requested a review from a team as a code owner August 16, 2024 07:54
@jo-elimu jo-elimu linked an issue Aug 16, 2024 that may be closed by this pull request
Copy link
Contributor

coderabbitai bot commented Aug 16, 2024

Walkthrough

The recent changes introduce a feature in the StoryBookCreateFromEPubController that utilizes a machine learning model to automatically predict the reading level of storybooks. A new method processes data input, employs a PMML model for predictions, and updates the corresponding storybook object in the database.

Changes

Files Change Summary
src/main/java/ai/elimu/web/content/storybook/StoryBookCreateFromEPubController.java Added predictReadingLevel method to handle reading level predictions using a PMML model.
src/main/resources/ai/elimu/web/content/storybook/step2_2_model.pmml Introduced a PMML file containing a regression model built with DecisionTreeRegressor for predictions.

Assessment against linked issues

Objective Addressed Explanation
Use machine learning model to predict storybook reading level (#1821)

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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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: 0

Outside diff range, codebase verification and nitpick comments (1)
src/main/java/ai/elimu/web/content/storybook/StoryBookCreateFromEPubController.java (1)

529-567: Enhance Error Handling in predictReadingLevel Method

The predictReadingLevel method currently lacks error handling for potential issues such as file not found or model prediction errors. Consider adding try-catch blocks to handle exceptions related to file access and model prediction to ensure robustness. This will prevent the application from crashing and allow for graceful error handling.

  • Add error handling for file access issues when loading the model.
  • Include error handling for potential prediction errors or invalid input features.
Analysis chain

Review the predictReadingLevel method for correctness and best practices.

The method loads a PMML model and uses it to predict the reading level of a StoryBook. Ensure that:

  • The model file path is correctly resolved.
  • Input features are correctly prepared and match the model's expectations.
  • Predictions are correctly interpreted and mapped to the ReadingLevel enum.
  • Consider adding error handling for potential issues like file not found or model prediction errors.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the correctness of the `predictReadingLevel` method.

# Test: Ensure the model file path is resolved correctly.
rg 'getResource("step2_2_model.pmml")' -A 3 src/main/java/ai/elimu/web/content/storybook/StoryBookCreateFromEPubController.java

# Test: Check if the `predictReadingLevel` method is called correctly in the codebase.
ast-grep --lang java --pattern $'predictReadingLevel($_)' src/main/java/ai/elimu/web/content/storybook/StoryBookCreateFromEPubController.java

Length of output: 441


Script:

#!/bin/bash
# Check for error handling related to file access and model prediction in the predictReadingLevel method.
rg 'try|catch|exception' -A 5 src/main/java/ai/elimu/web/content/storybook/StoryBookCreateFromEPubController.java

Length of output: 2760

coderabbitai[bot]
coderabbitai bot previously approved these changes Aug 16, 2024
Copy link

codecov bot commented Aug 16, 2024

Codecov Report

Attention: Patch coverage is 0% with 45 lines in your changes missing coverage. Please review.

Project coverage is 15.10%. Comparing base (883f279) to head (8db044f).
Report is 5 commits behind head on main.

Files Patch % Lines
...t/storybook/StoryBookCreateFromEPubController.java 0.00% 45 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##               main    #1822      +/-   ##
============================================
- Coverage     15.19%   15.10%   -0.09%     
  Complexity      450      450              
============================================
  Files           249      249              
  Lines          7627     7672      +45     
  Branches        798      800       +2     
============================================
  Hits           1159     1159              
- Misses         6418     6463      +45     
  Partials         50       50              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

coderabbitai[bot]
coderabbitai bot previously approved these changes Aug 17, 2024
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

Comment on lines +540 to +580
private ReadingLevel predictReadingLevel(int chapterCount, int paragraphCount, int wordCount) {
logger.info("predictReadingLevel");

// Load the machine learning model (https://github.com/elimu-ai/ml-storybook-reading-level)
String modelFilePath = getClass().getResource("step2_2_model.pmml").getFile();
logger.info("modelFilePath: " + modelFilePath);
org.pmml4s.model.Model model = org.pmml4s.model.Model.fromFile(modelFilePath);
logger.info("model: " + model);

// Prepare values (features) to pass to the model
Map<String, Double> values = Map.of(
"chapter_count", Double.valueOf(chapterCount),
"paragraph_count", Double.valueOf(paragraphCount),
"word_count", Double.valueOf(wordCount)
);
logger.info("values: " + values);

// Make prediction
logger.info("Arrays.toString(model.inputNames()): " + Arrays.toString(model.inputNames()));
Object[] valuesMap = Arrays.stream(model.inputNames())
.map(values::get)
.toArray();
logger.info("valuesMap: " + valuesMap);
Object[] results = model.predict(valuesMap);
logger.info("results: " + results);
logger.info("Arrays.toString(results): " + Arrays.toString(results));
Object result = results[0];
logger.info("result: " + result);
logger.info("result.getClass().getSimpleName(): " + result.getClass().getSimpleName());
Double resultAsDouble = (Double) result;
logger.info("resultAsDouble: " + resultAsDouble);
Integer resultAsInteger = resultAsDouble.intValue();
logger.info("resultAsInteger: " + resultAsInteger);

// Convert from number to ReadingLevel enum (e.g. "LEVEL2")
String readingLevelAsString = "LEVEL" + resultAsInteger;
logger.info("readingLevelAsString: " + readingLevelAsString);
ReadingLevel readingLevel = ReadingLevel.valueOf(readingLevelAsString);
logger.info("readingLevel: " + readingLevel);
return readingLevel;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Enhance error handling and logging.

The predictReadingLevel method effectively handles the prediction process. However, consider adding error handling for potential issues like file not found or invalid model predictions. Additionally, improve logging by including more context about the prediction process.

try {
    org.pmml4s.model.Model model = org.pmml4s.model.Model.fromFile(modelFilePath);
    // Existing logic
} catch (FileNotFoundException e) {
    logger.error("Model file not found: " + modelFilePath, e);
    throw new RuntimeException("Model file not found", e);
} catch (Exception e) {
    logger.error("Error during model prediction", e);
    throw new RuntimeException("Error during model prediction", e);
}

@nya-elimu nya-elimu merged commit fd22181 into main Aug 20, 2024
7 of 9 checks passed
@nya-elimu nya-elimu deleted the 1821-use-machine-learning-model-to-predict-storybook-reading-level branch August 20, 2024 12:17
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.

Use machine learning model to predict storybook reading level
2 participants