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:multilang_match #646

Merged
merged 3 commits into from
Jan 29, 2025
Merged

feat:multilang_match #646

merged 3 commits into from
Jan 29, 2025

Conversation

JarbasAl
Copy link
Member

@JarbasAl JarbasAl commented Jan 28, 2025

if enabled attempt to match intents across all configured langs

this allows OVOS to match even if lang was incorrectly tagged, as long as the transcription is correct

use cases aretext chatbots (eg, matrix hivemind both) or misclassifications of audio transformer plugins

example config

{
  "lang": "en-US",
  "secondary_langs": [
    "pt-PT", "fr-FR"
  ],
  "intents": {
     "multilingual_matching": true
   }
 }

Summary by CodeRabbit

  • New Features

    • Enhanced multilingual intent matching support
    • Improved language processing for intent recognition
  • Bug Fixes

    • Expanded language matching capabilities to support multiple language configurations
  • Chores

    • Updated logging for language-specific intent matching process
    • Added language context to match messages

if enabled attempt to match intents across all configured langs

this allows OVOS to match even if lang was incorrectly tagged, as long as the transcription is correct

use cases aretext chatbots (eg, matrix hivemind both) or misclassifications of audio transformer plugins
@JarbasAl JarbasAl requested a review from goldyfruit January 28, 2025 15:15
Copy link

coderabbitai bot commented Jan 28, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

The changes enhance the handle_utterance method in the IntentService class to support multilingual intent matching. The implementation now allows for matching utterances across multiple languages when configured for multilingual support. A list of languages is dynamically constructed, starting with the primary language and including additional valid languages. The matching process iterates over this list, maintaining the existing core logic while improving flexibility in language handling.

Changes

File Change Summary
ovos_core/intent_services/__init__.py Enhanced handle_utterance method for multilingual intent matching; updated _emit_match_message method to include language parameter.

Sequence Diagram

sequenceDiagram
    participant IntentService
    participant MatchFunction
    participant Message

    IntentService->>IntentService: Prepare language list
    loop For each language
        IntentService->>MatchFunction: Attempt intent match
        alt Match found
            IntentService->>IntentService: Process match
        else No match
            IntentService->>IntentService: Log debug message
        end
    end
Loading

Poem

🐰 Multilingual Matcher, oh so bright,
Languages dancing in coding delight!
From primary tongue to distant shore,
Intents now travel where they've not before
A rabbit's dream of linguistic glee 🌍
Matching words with playful spree! 🎉


📜 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 1f05583 and d4ac797.

📒 Files selected for processing (1)
  • ovos_core/intent_services/__init__.py (5 hunks)
✨ 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.

@github-actions github-actions bot added feature and removed feature labels Jan 28, 2025
Copy link

codecov bot commented Jan 28, 2025

Codecov Report

Attention: Patch coverage is 65.51724% with 10 lines in your changes missing coverage. Please review.

Project coverage is 70.98%. Comparing base (23f0bab) to head (d4ac797).
Report is 171 commits behind head on dev.

Files with missing lines Patch % Lines
ovos_core/intent_services/__init__.py 65.51% 10 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##              dev     #646      +/-   ##
==========================================
- Coverage   75.33%   70.98%   -4.36%     
==========================================
  Files          15       15              
  Lines        3094     1651    -1443     
==========================================
- Hits         2331     1172    -1159     
+ Misses        763      479     -284     
Flag Coverage Δ
end2end 54.51% <65.51%> (?)
unittests 47.54% <3.44%> (-27.80%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

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

@JarbasAl JarbasAl marked this pull request as ready for review January 28, 2025 15:22
@github-actions github-actions bot added feature and removed feature labels Jan 28, 2025
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

🧹 Nitpick comments (3)
ovos_core/intent_services/__init__.py (3)

413-417: Consider optimizing the multilingual matching implementation.

The current implementation could be improved in terms of efficiency and robustness:

  1. Cache the valid languages list to avoid repeated computation
  2. Allow configuring specific secondary languages instead of using all valid languages
  3. Validate language support for each matcher function

Consider this implementation:

+    def _get_matching_languages(self, primary_lang):
+        """Get ordered list of languages to attempt matching against."""
+        if not hasattr(self, '_valid_languages'):
+            self._valid_languages = get_valid_languages()
+        
+        # Use configured languages or fall back to all valid languages
+        secondary_langs = self.config.get("secondary_languages") or \
+            [l for l in self._valid_languages if l != primary_lang]
+        
+        return [primary_lang] + secondary_langs

     # In handle_utterance method:
-    langs = [lang]
-    if self.config.get("multilingual_matching"):
-        # if multilingual matching is enabled, attempt to match all user languages if main fails
-        langs += [l for l in get_valid_languages() if l != lang]
+    langs = [lang]
+    if self.config.get("multilingual_matching"):
+        langs = self._get_matching_languages(lang)

418-437: Enhance observability and error handling in the language matching loop.

The language iteration logic could benefit from improved logging and error handling to aid in debugging and monitoring:

  1. Log attempted languages for better debugging
  2. Add specific exception handling
  3. Include performance metrics per language attempt

Consider this implementation:

     for l in langs:
+        LOG.debug(f"Attempting match with language: {l}")
+        match_start = time.time()
         match = match_func(utterances, l, message)
+        match_duration = time.time() - match_start
+        LOG.debug(f"Match attempt for {l} took {match_duration:.3f}s")
         if match:
             LOG.info(f"{pipeline} match ({l}): {match}")
             if match.skill_id and match.skill_id in sess.blacklisted_skills:
                 LOG.debug(
                     f"ignoring match, skill_id '{match.skill_id}' blacklisted by Session '{sess.session_id}'")
                 continue
             if isinstance(match, IntentHandlerMatch) and match.match_type in sess.blacklisted_intents:
                 LOG.debug(
                     f"ignoring match, intent '{match.match_type}' blacklisted by Session '{sess.session_id}'")
                 continue
             try:
                 self._emit_match_message(match, message)
                 break
-            except:
+            except Exception as e:
+                LOG.exception(f"{match_func} returned an invalid match: {str(e)}")
                 LOG.exception(f"{match_func} returned an invalid match")
     else:
-        LOG.debug(f"no match from {match_func}")
+        LOG.debug(f"no match from {match_func} for languages: {langs}")
         continue

413-437: Add documentation for the multilingual matching feature.

The implementation successfully adds multilingual matching capability, but would benefit from documentation explaining:

  1. Configuration options
  2. Language selection behavior
  3. Performance implications

Consider adding a docstring like this:

"""
Attempt to match intents across multiple languages when enabled.

The matching process will:
1. First attempt to match in the primary language
2. If no match is found and multilingual_matching is enabled,
   attempt to match in configured secondary languages

Configuration:
    multilingual_matching (bool): Enable/disable multilingual matching
    secondary_languages (list): Optional list of secondary languages to try.
                              If not specified, all valid languages are used.

Example config:
    {
        "multilingual_matching": true,
        "secondary_languages": ["pt-PT", "fr-FR"]
    }
"""
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6bc1cca and 23e562e.

📒 Files selected for processing (1)
  • ovos_core/intent_services/__init__.py (1 hunks)

@github-actions github-actions bot added feature and removed feature labels Jan 29, 2025
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

🧹 Nitpick comments (2)
ovos_core/intent_services/__init__.py (2)

Line range hint 270-281: Ensure docstring clarity for the new lang parameter.
This additional parameter and docstring entry align with the PR's goal of enabling multilingual matching. Consider refining the docstring to convey how this parameter is determined (e.g., primary vs. secondary language) and whether it can differ from what’s in message.context.


416-419: Rename ambiguous variable l to improve clarity.
Using l can trigger readability warnings. Renaming it avoids confusion.

- langs += [l for l in get_valid_languages() if l != lang]
+ langs += [lang_code for lang_code in get_valid_languages() if lang_code != lang]
🧰 Tools
🪛 Ruff (0.8.2)

419-419: Ambiguous variable name: l

(E741)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 23e562e and 1f05583.

📒 Files selected for processing (1)
  • ovos_core/intent_services/__init__.py (5 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
ovos_core/intent_services/__init__.py

419-419: Ambiguous variable name: l

(E741)


435-435: Do not use bare except

(E722)

⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: end2end_tests (3.9)
  • GitHub Check: mycroft_tests (3.9)
  • GitHub Check: unit_tests (3.9)
  • GitHub Check: license_tests
🔇 Additional comments (3)
ovos_core/intent_services/__init__.py (3)

300-300: Session language update looks correct.
Updating sess.lang to match the detected language is consistent with the overall multilingual design. No concerns here.


315-315: Storing language in reply data is consistent.
Assigning reply.data["lang"] helps downstream consumers understand the matched language context.


420-434: Review matching order for best results.
The loop prioritizes an immediate match in one language over potentially better matches in others. If desired, you could gather all possible matches across languages and then compare them by confidence. For now, this straightforward approach aligns with the PR objectives.

ovos_core/intent_services/__init__.py Show resolved Hide resolved
@JarbasAl JarbasAl merged commit 7a44903 into dev Jan 29, 2025
5 of 6 checks passed
@JarbasAl JarbasAl deleted the feat/multilang_match branch January 29, 2025 18:06
@coderabbitai coderabbitai bot mentioned this pull request Jan 31, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant