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: extend dialog/intent templates #317

Merged
merged 4 commits into from
Dec 6, 2024
Merged

feat: extend dialog/intent templates #317

merged 4 commits into from
Dec 6, 2024

Conversation

JarbasAl
Copy link
Member

@JarbasAl JarbasAl commented Dec 6, 2024

closes #312

templates = [
    "[hello,] (call me|my name is) {name}",
    "Expand (alternative|choices) into a list of choices.",
    "sentences have [optional] words ",
    "alternative words can be (used|written)",
    "sentence[s] can have (pre|suf)fixes mid word too",
    "do( the | )thing(s|) (old|with) style and( no | )spaces",
    "[(this|that) is optional]",
    "tell me a [{joke_type}] joke",
    "play {query} [in ({device_name}|{skill_name}|{zone_name})]"
]
for template in templates:
    print("###", template)
    expanded_sentences = expand_template(template)
    for sentence in expanded_sentences:
        print("-", sentence)
    # ### [hello,] (call me|my name is) {name}
    # - call me {name}
    # - hello, call me {name}
    # - hello, my name is {name}
    # - my name is {name}
    # ### Expand (alternative|choices) into a list of choices.
    # - Expand alternative into a list of choices.
    # - Expand choices into a list of choices.
    # ### sentences have [optional] words
    # - sentences have  words
    # - sentences have optional words
    # ### alternative words can be (used|written)
    # - alternative words can be used
    # - alternative words can be written
    # ### sentence[s] can have (pre|suf)fixes mid word too
    # - sentence can have prefixes mid word too
    # - sentence can have suffixes mid word too
    # - sentences can have prefixes mid word too
    # - sentences can have suffixes mid word too
    # ### do( the | )thing(s|) (old|with) style and( no | )spaces
    # - do the thing old style and no spaces
    # - do the thing old style and spaces
    # - do the thing with style and no spaces
    # - do the thing with style and spaces
    # - do the things old style and no spaces
    # - do the things old style and spaces
    # - do the things with style and no spaces
    # - do the things with style and spaces
    # - do thing old style and no spaces
    # - do thing old style and spaces
    # - do thing with style and no spaces
    # - do thing with style and spaces
    # - do things old style and no spaces
    # - do things old style and spaces
    # - do things with style and no spaces
    # - do things with style and spaces
    # ### [(this|that) is optional]
    # -
    # - that is optional
    # - this is optional
    # ### tell me a [{joke_type}] joke
    # - tell me a  joke
    # - tell me a {joke_type} joke
    # ### play {query} [in ({device_name}|{skill_name}|{zone_name})]
    # - play {query}
    # - play {query} in {device_name}
    # - play {query} in {skill_name}
    # - play {query} in {zone_name}

also adds a new util if we want to generate text from .intent + .entity combinations

template = "change [the ]brightness to {brightness_level} and color to {color_name}"
slots = {
    "brightness_level": ["low", "medium", "high"],
    "color_name": ["red", "green", "blue"]
}

expanded_sentences = expand_slots(template, slots)
for sentence in expanded_sentences:
    print(sentence)
    # change the brightness to low and color to red
    # change the brightness to low and color to green
    # change the brightness to low and color to blue
    # change the brightness to medium and color to red
    # change the brightness to medium and color to green
    # change the brightness to medium and color to blue
    # change the brightness to high and color to red
    # change the brightness to high and color to green
    # change the brightness to high and color to blue
    # change brightness to low and color to red
    # change brightness to low and color to green
    # change brightness to low and color to blue
    # change brightness to medium and color to red
    # change brightness to medium and color to green
    # change brightness to medium and color to blue
    # change brightness to high and color to red
    # change brightness to high and color to green
    # change brightness to high and color to blue

Summary by CodeRabbit

  • New Features

    • Introduced expand_template function for enhanced template string processing.
    • Added expand_slots function to substitute placeholders with slot options.
  • Deprecated Features

    • Marked several functions and class constructors as deprecated, advising users to transition to the new expand_template method for sentence expansion tasks.
  • Bug Fixes

    • Updated dialog rendering to utilize the new expand_template method instead of the deprecated expand_options.
  • Testing Improvements

    • Updated test suite to reflect the broader focus on template expansion, including new tests for expand_template and expand_slots.

closes #312

new [optional] syntax

(new|old) way still work(s|)

(pre|suf)fixes are now allowed
closes #312

new [optional] syntax

(new|old) way still work(s|)

(pre|suf)fixes are now allowed
Copy link
Contributor

coderabbitai bot commented Dec 6, 2024

Walkthrough

The changes in this pull request primarily focus on enhancing the functionality of the ovos_utils/bracket_expansion.py file. New functions have been introduced to improve template expansion capabilities, including expand_template and expand_slots. These functions allow for more flexible handling of optional components and alternatives in templates. Additionally, several existing functions and constructors have been marked as deprecated, signaling a transition towards the new methods for sentence expansion tasks.

Changes

File Path Change Summary
ovos_utils/bracket_expansion.py - Added expand_template(template: str) -> List[str]
- Added expand_slots(template: str, slots: Dict[str, List[str]]) -> List[str]
- Deprecated expand_parentheses, expand_options, and constructors for Fragment, Word, Sentence, Options, and SentenceTreeParser classes.
test/unittests/test_bracket_expansion.py - Renamed class from TestBracketExpansion to TestTemplateExpansion
- Removed tests for deprecated functions and classes
- Added tests for expand_slots and expand_template functions.
ovos_utils/dialog.py - Updated import and method call from expand_options to expand_template in MustacheDialogRenderer.
ovos_utils/file_utils.py - Updated import and logic in read_vocab_file to use expand_template instead of expand_options.

Assessment against linked issues

Objective Addressed Explanation
Support optional syntax with square brackets
Support nesting with alternatives and keywords

🐇 In the garden, I hop and play,
New functions bloom, brightening the day!
Templates expand, options galore,
With brackets and slots, we’ll explore!
So let’s cheer for changes, both big and small,
In the world of code, we’ll have a ball! 🌼


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

codecov bot commented Dec 6, 2024

Codecov Report

Attention: Patch coverage is 91.22807% with 5 lines in your changes missing coverage. Please review.

Project coverage is 45.57%. Comparing base (32b9fe1) to head (4dc2fab).
Report is 33 commits behind head on dev.

Files with missing lines Patch % Lines
ovos_utils/bracket_expansion.py 92.45% 4 Missing ⚠️
ovos_utils/file_utils.py 50.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##              dev     #317      +/-   ##
==========================================
+ Coverage   44.74%   45.57%   +0.82%     
==========================================
  Files          33       33              
  Lines        3426     3467      +41     
==========================================
+ Hits         1533     1580      +47     
+ Misses       1893     1887       -6     

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

@github-actions github-actions bot added feature and removed feature labels Dec 6, 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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between bffe411 and d754009.

📒 Files selected for processing (1)
  • ovos_utils/bracket_expansion.py (7 hunks)

ovos_utils/bracket_expansion.py Show resolved Hide resolved
@github-actions github-actions bot added feature and removed feature labels Dec 6, 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: 0

🧹 Outside diff range and nitpick comments (1)
test/unittests/test_bracket_expansion.py (1)

8-36: Well-structured test with comprehensive coverage!

The test effectively validates the expand_slots function with a practical example, covering all possible combinations of slot values and optional words.

Fix indentation in expected_sentences list.

The list uses 14 spaces for indentation instead of the standard 8 spaces.

     expected_sentences = ['change brightness to low and color to red',
-                              'change brightness to low and color to green',
+                        'change brightness to low and color to green',
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d754009 and 5711789.

📒 Files selected for processing (1)
  • test/unittests/test_bracket_expansion.py (1 hunks)
🧰 Additional context used
🪛 Ruff (0.8.0)
test/unittests/test_bracket_expansion.py

40-40: Local variable templates is assigned to but never used

Remove assignment to unused variable templates

(F841)

🔇 Additional comments (2)
test/unittests/test_bracket_expansion.py (2)

3-6: LGTM! Clean imports and appropriate class renaming.

The imports are minimal and the class renaming from TestBracketExpansion to TestTemplateExpansion better reflects the broader scope of template expansion functionality.


38-114: Excellent test coverage of template expansion patterns!

The test comprehensively covers all syntax features mentioned in the PR objectives:

  • Optional words using [brackets]
  • Alternatives using (pipes|or|choices)
  • Slot placeholders using {curly_braces}
  • Nested structures combining all features
  • Empty optional sections
  • Mid-word affixes

The use of subtests for each template pattern is a good practice for maintainable tests.

Note: The static analysis warning about unused templates variable can be ignored as it's used indirectly through expected_outputs.items().

🧰 Tools
🪛 Ruff (0.8.0)

40-40: Local variable templates is assigned to but never used

Remove assignment to unused variable templates

(F841)

@github-actions github-actions bot added feature and removed feature labels Dec 6, 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

🧹 Outside diff range and nitpick comments (2)
ovos_utils/dialog.py (1)

95-95: Consider documenting template expansion behavior

The random selection from expanded templates should be documented to clarify the behavior when using optional syntax (e.g., [hello,] how are you).

Consider adding a docstring example:

def render(self, template_name, context=None, index=None):
    """
    ...
    Examples:
        Template "[hello,] how are you" might expand to either:
        - "hello how are you"
        - "how are you"
    """
ovos_utils/file_utils.py (1)

Line range hint 228-244: Document new template syntax in function docstring

The docstring should be updated to include examples of the new optional syntax supported in vocabulary files.

 def read_vocab_file(path: str) -> List[List[str]]:
     """
     Read voc file.
 
     This reads a .voc file, stripping out empty lines comments and expand
-    parentheses. It returns each line as a list of all expanded
+    parentheses and optional syntax. It returns each line as a list of all expanded
     alternatives.
 
+    Supported syntax:
+    - [optional]: Square brackets for optional words
+    - (a|b): Parentheses for alternatives
+    Example:
+        "[hello,] (good morning|good evening)" expands to:
+        ["hello good morning", "hello good evening", "good morning", "good evening"]
+
     Args:
         path (str): path to vocab file.
 
     Returns:
         List of Lists of strings.
     """
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 5711789 and 4dc2fab.

📒 Files selected for processing (2)
  • ovos_utils/dialog.py (2 hunks)
  • ovos_utils/file_utils.py (2 hunks)
🔇 Additional comments (3)
ovos_utils/dialog.py (1)

8-8: LGTM: Import change aligns with new template expansion functionality

The change from expand_options to expand_template aligns with the PR objectives to support enhanced template syntax.

ovos_utils/file_utils.py (2)

15-15: LGTM: Import change maintains consistency

The change from expand_options to expand_template maintains consistency with the new template expansion functionality.


244-244: Review case sensitivity in template expansion

The .lower() conversion is applied before template expansion. Verify this doesn't affect any case-sensitive template variables or optional syntax.

✅ Verification successful

Case conversion before template expansion is safe

After examining the implementation of expand_template and its test cases, the .lower() conversion before template expansion is safe because:

  1. The template expansion function (expand_template) operates purely on pattern matching using regex for:

    • Optional brackets [optional]
    • Alternative choices (a|b)
    • Slot placeholders {variable}
  2. The test cases demonstrate that case sensitivity is preserved for slot variables (e.g., {device_name}, {zone_name}), which are not affected by the .lower() call since they are processed after template expansion.

  3. The expansion logic doesn't rely on case-sensitive patterns for its functionality, only on the special characters [](){}| for syntax.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for case-sensitive variables in vocabulary files

# Search for uppercase variables in .voc files
fd -e voc -x rg -l '\{[A-Z][^}]*\}'

# Search for uppercase content in square brackets
fd -e voc -x rg -l '\[[^]]*[A-Z][^]]*\]'

Length of output: 80


Script:

#!/bin/bash
# Let's check the implementation of expand_template and its usage context
ast-grep --pattern 'def expand_template'

# Also search for any documentation or comments about template expansion
rg -B2 -A2 "expand_template"

# Let's also check for any .voc files in test directories that might show template usage
fd -e voc -p "test"

Length of output: 5150


Script:

#!/bin/bash
# Let's examine the expand_template implementation to understand how it handles case
cat ovos_utils/bracket_expansion.py

# Also check test cases to see if there are any case-sensitive examples
cat test/unittests/test_bracket_expansion.py

Length of output: 15179

ovos_utils/dialog.py Show resolved Hide resolved
@JarbasAl JarbasAl merged commit c5ef1f0 into dev Dec 6, 2024
10 checks passed
@JarbasAl JarbasAl deleted the feat/extend_templates branch December 6, 2024 13:25
JarbasAl added a commit to OpenVoiceOS/ovos-core that referenced this pull request Dec 6, 2024
JarbasAl added a commit to OpenVoiceOS/ovos-core that referenced this pull request Dec 6, 2024
JarbasAl added a commit to OpenVoiceOS/ovos-core that referenced this pull request Dec 6, 2024
* fix:bracket_expansion

pull OpenVoiceOS/ovos-utils#317 into dependencies

* Update build_tests.yml

* failing tests

* Update requirements.txt
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.

feat: support [optional] syntax
1 participant