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

translation fix for action #1621

Merged
merged 2 commits into from
Dec 10, 2024
Merged

Conversation

hasinaxp
Copy link
Contributor

@hasinaxp hasinaxp commented Dec 9, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced translation process for action configurations.
    • Introduced serialization and deserialization for action data.
  • Bug Fixes

    • Improved robustness in handling non-existent action types during translation.
  • Tests

    • Added tests for translating action configurations, including edge cases for empty configurations and missing fields.

Copy link

coderabbitai bot commented Dec 9, 2024

Walkthrough

The changes in this pull request primarily focus on enhancing the handling of action configurations within the kairon/multilingual/processor.py file. Key updates include the introduction of the ActionSerializer for serializing and deserializing action data, modifications to the create_multilingual_bot method, and improved logic for translating action responses. Additionally, new test cases have been added to the multilingual_processor_test.py to ensure comprehensive coverage of the translation functionalities and edge cases.

Changes

File Change Summary
kairon/multilingual/processor.py Updated __save_bot_files method to accept an optional other_collections parameter. Introduced ActionSerializer for action serialization. Modified translation logic to check for existing action types.
kairon/shared/data/action_serializer.py Added serialize(bot: str) and deserialize(bot: str, user: str, actions: dict, other_collections_data: dict, overwrite: bool) methods in ActionSerializer.
tests/unit_test/multilingual/multilingual_processor_test.py Added tests: test_translate_responses, test_empty_action_config, and test_translate_actions_missing_fields to cover translation functionalities.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant MultilingualTranslator
    participant ActionSerializer

    User->>MultilingualTranslator: create_multilingual_bot()
    MultilingualTranslator->>ActionSerializer: serialize()
    ActionSerializer-->>MultilingualTranslator: serialized actions
    MultilingualTranslator->>MultilingualTranslator: __save_bot_files()
    MultilingualTranslator->>User: Bot created successfully
Loading

🐇 "In the meadow, actions play,
With translations bright as day.
Serializer hops with glee,
Making bots as smart as can be!
Empty configs, no need to fret,
Our tests ensure no bug is met!" 🌼


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. (Experiment)
  • @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: 1

🧹 Outside diff range and nitpick comments (2)
tests/unit_test/multilingual/multilingual_processor_test.py (2)

675-675: Remove unused variable expected

The variable expected is assigned but never used, which can be removed to clean up the code.

Apply this diff:

     action_config = {
         "http_action": [{"response": {}}],
         "email_action": [{}],
     }

-    expected = {
-        "http_action": [{"response": {}}],
-        "email_action": [{}],
-    }

     s_lang = "en"
     d_lang = "fr"
🧰 Tools
🪛 Ruff (0.8.0)

675-675: Local variable expected is assigned to but never used

Remove assignment to unused variable expected

(F841)


683-683: Remove unused variable result

The variable result is assigned but never used. Since we're only checking that an exception is raised, the assignment can be removed.

Apply this diff:

     with pytest.raises(KeyError):
-        result = MultilingualTranslator._MultilingualTranslator__translate_actions(action_config, s_lang, d_lang)
+        MultilingualTranslator._MultilingualTranslator__translate_actions(action_config, s_lang, d_lang)
🧰 Tools
🪛 Ruff (0.8.0)

683-683: Local variable result is assigned to but never used

Remove assignment to unused variable result

(F841)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b3e781f and f3cf41f.

📒 Files selected for processing (2)
  • kairon/multilingual/processor.py (5 hunks)
  • tests/unit_test/multilingual/multilingual_processor_test.py (1 hunks)
🧰 Additional context used
🪛 Ruff (0.8.0)
tests/unit_test/multilingual/multilingual_processor_test.py

675-675: Local variable expected is assigned to but never used

Remove assignment to unused variable expected

(F841)


682-682: pytest.raises(Exception) should be considered evil

(B017)


683-683: Local variable result is assigned to but never used

Remove assignment to unused variable result

(F841)

🔇 Additional comments (6)
kairon/multilingual/processor.py (6)

12-12: Importing ActionSerializer for action serialization

The addition of ActionSerializer improves the way actions are serialized and deserialized, enhancing code modularity and maintainability.


128-145: Enhance robustness by checking action types before translation

The added checks for the existence of specific action types in the action_config dictionary before translation prevent potential KeyError exceptions and improve code reliability.


159-164: Use ActionSerializer.deserialize for action deserialization

Replacing the direct call to save_integrated_actions with ActionSerializer.deserialize standardizes the action deserialization process and promotes reuse of serialization logic.


200-201: Serialize actions using ActionSerializer.serialize

Utilizing ActionSerializer.serialize for serializing actions and other collections ensures consistency and encapsulates serialization logic within a dedicated class.


233-233: Pass other_collections to __save_bot_files

Including other_collections when saving bot files ensures that all necessary collections are preserved in the new multilingual bot.


150-150: 🛠️ Refactor suggestion

Update method signature to include other_collections

The method __save_bot_files now accepts an additional parameter other_collections. Ensure that all calls to this method have been updated accordingly throughout the codebase.

Run the following script to verify all calls to __save_bot_files are updated:

✅ Verification successful

Note: Corrected the syntax by using -t py instead of --python flag for ripgrep to search Python files.


All calls to __save_bot_files are properly updated

The verification shows that there is only one call to __save_bot_files in the codebase, and it correctly includes the other_collections parameter. The method call matches the updated signature perfectly, so no further changes are needed.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all usages of __save_bot_files and check for the correct parameters

rg --python --multiline 'def __save_bot_files\(.*\):' -A3

# Find all calls to __save_bot_files
rg --python 'self\.__save_bot_files\(' -A5

Length of output: 926


Script:

#!/bin/bash
# Description: Find all usages of __save_bot_files and check for the correct parameters

# Find method definition
rg -t py 'def __save_bot_files.*:' -A3

# Find all calls to __save_bot_files
rg -t py 'self\.__save_bot_files\(' -A5

Length of output: 1028

actions = actions,
other_collections_data=other_collections,
overwrite=True)
# self.mp.save_integrated_actions(actions=actions, bot=new_bot_id, user=self.user)
Copy link
Collaborator

Choose a reason for hiding this comment

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

remove the comments

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

🧹 Outside diff range and nitpick comments (2)
kairon/multilingual/processor.py (2)

128-145: Consider refactoring repetitive action translation logic

The current implementation has repetitive patterns for each action type. Consider refactoring this into a more maintainable structure.

Here's a suggested refactor to reduce duplication:

-        if action_config.get(ActionType.http_action.value):
-            action_config[ActionType.http_action.value] = translate_responses_for_http_actions(
-            action_config[ActionType.http_action.value])
-        if action_config.get(ActionType.email_action.value):
-            action_config[ActionType.email_action.value] = translate_responses(action_config[ActionType.email_action.value])
-        # ... more similar conditions ...
+        action_translation_config = {
+            ActionType.http_action.value: {'translator': translate_responses_for_http_actions},
+            ActionType.email_action.value: {'translator': translate_responses},
+            ActionType.jira_action.value: {'translator': translate_responses},
+            ActionType.zendesk_action.value: {'translator': translate_responses},
+            ActionType.pipedrive_leads_action.value: {'translator': translate_responses},
+            ActionType.google_search_action.value: {
+                'translator': translate_responses,
+                'fields': ['failure_response']
+            },
+            ActionType.form_validation_action.value: {
+                'translator': translate_responses,
+                'fields': ['valid_response', 'invalid_response']
+            }
+        }
+        
+        for action_type, config in action_translation_config.items():
+            if action_config.get(action_type):
+                translator_func = config['translator']
+                fields = config.get('fields')
+                if fields:
+                    action_config[action_type] = translator_func(
+                        action_config[action_type], fields)
+                else:
+                    action_config[action_type] = translator_func(
+                        action_config[action_type])

159-163: Fix indentation in ActionSerializer.deserialize call

The indentation of the parameters in the deserialize call is inconsistent.

-        ActionSerializer.deserialize(bot=new_bot_id,
-                                     user=self.user,
-                                     actions = actions,
-                                     other_collections_data=other_collections,
-                                     overwrite=True)
+        ActionSerializer.deserialize(
+            bot=new_bot_id,
+            user=self.user,
+            actions=actions,
+            other_collections_data=other_collections,
+            overwrite=True
+        )
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f3cf41f and 20811b3.

📒 Files selected for processing (1)
  • kairon/multilingual/processor.py (5 hunks)
🔇 Additional comments (2)
kairon/multilingual/processor.py (2)

12-12: LGTM: Import addition is appropriate

The ActionSerializer import is correctly placed and aligns with the module's requirements.


199-199: LGTM: Improved bot creation process

The changes to use ActionSerializer and handle other collections improve the robustness of the bot creation process. The error handling and logging are comprehensive.

Also applies to: 231-231

Copy link
Collaborator

@hiteshghuge hiteshghuge left a comment

Choose a reason for hiding this comment

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

reviewed

@hiteshghuge hiteshghuge merged commit 95a009e into digiteinfotech:master Dec 10, 2024
7 of 8 checks passed
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