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

[EN] Enhanced get state sentences for media_player #2230

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

tetele
Copy link
Contributor

@tetele tetele commented Jun 13, 2024

An attempt to fix #2229 (at least in English)

These sentences "rephrase" some states that you ask about regarding media players.

Also, when the state is ambiguous (e.g. is the TV on?), the response clarifies the state, e.g. the TV is on, but it is not playing.

As a dependency in this PR, there is a small fix regarding passing a list for the state slot, which, although supported in hassil, would have appeared as no matches were found until now.

Summary by CodeRabbit

  • New Features

    • Introduced an alternate_state response template for more nuanced state representation.
    • Added detailed state management and querying for media players.
  • Enhancements

    • Refined state definitions for media players, including states like "off", "on", "idle", "standby", "buffering", "playing", and "paused".
    • Updated Home Assistant intents to exclude media_player from specific state checks.
  • Tests

    • Added tests for querying and managing media player states to ensure accurate and reliable responses.

This is used for confirming ambiguous state values which could be rephrased/reinterpreted
Passing the `state` slot as a list to the parser/test processor, although supported in hassil, would have not worked.
Copy link

coderabbitai bot commented Jun 13, 2024

Walkthrough

Walkthrough

This update enhances the Home Assistant's HassGetState functionality by refining state query responses for media players, improving the clarity and accuracy of status reports. It introduces new templates to provide detailed responses and adjusts the logic for matched states, specifically addressing the inclusion of alternate state representations.

Changes

Files Change Summary
responses/en/HassGetState.yaml Added alternate_state response template for better representation of entity states.
sentences/en/_common.yaml Refined media_player_states and media_players definitions to improve state parsing for media players.
sentences/en/homeassistant_HassGetState.yaml Added media_player exclusion within excludes_context to refine state checking logic.
sentences/en/media_player_HassGetState.yaml Introduced new intents for querying and managing media player states, improving query handling for such devices.
shared/__init__.py Modified state_name variable to accept both string and list of strings for flexible state matching in get_matched_states.
tests/en/media_player_HassGetState.yaml Introduced tests for querying media player states, including actual and alternate state responses.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Assistant
    participant StateHandler
    participant ResponseHandler

    User->>Assistant: Is the receiver on?
    Assistant->>StateHandler: Query State of Media Player
    StateHandler->>Assistant: State: playing
    Assistant->>ResponseHandler: Format Response with State
    ResponseHandler->>Assistant: Receiver is on and playing
    Assistant->>User: Receiver is on and playing
Loading

Assessment Against Linked Issues

Objective (Issue) Addressed Explanation
Improve HassGetState for media players (#2229)
Enhance state query templates and logic (#2229)

Recent review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

Commits

Files that changed from the base of the PR and between 69f1c62 and ce9ab25.

Files selected for processing (6)
  • responses/en/HassGetState.yaml (1 hunks)
  • sentences/en/_common.yaml (2 hunks)
  • sentences/en/homeassistant_HassGetState.yaml (1 hunks)
  • sentences/en/media_player_HassGetState.yaml (1 hunks)
  • shared/init.py (2 hunks)
  • tests/en/media_player_HassGetState.yaml (1 hunks)
Additional context used
Path-based instructions (1)
shared/__init__.py (4)

Pattern */**(html|markdown|md): - For instructional content in documentation, use a direct and authoritative tone. Avoid expressions of politeness such as 'may' or 'please', and ensure the goal of the instruction is fronted.

  • Apply the Microsoft Style Guide to ensure documentation maintains clarity and conciseness.
  • In step-by-step instructions, front the location phrase in the instructional sentence.
  • In step-by-step instructions, front the 'goal' in the instructional sentence.
  • In step-by-step instructions, if in doubt what to front, front the 'goal' before the location phrase in the instructional sentence.
  • do not hyphenate terms like 'top-right' or 'bottom-left' with 'corner'

Pattern */**(html|markdown|md): - Use bold to mark UI strings.

  • If "" are used to mark UI strings, replace them by bold.

Pattern */**(html|markdown|md): - Be brief in your replies and don't add fluff like "thank you for..." and "Please let me know if"


Pattern */**(html|markdown|md): - Use sentence-style capitalization also in headings.

GitHub Check: build
responses/en/HassGetState.yaml

[failure] 1-1:
'dict object' has no attribute 'actual_state' in response 'alternate_state' (template='{{ slots.name | capitalize }} is {{ slots.actual_state }}, but it is

tests/en/media_player_HassGetState.yaml

[failure] 1-1:
invalid format: Expected anything but a dictionary for dictionary value @ data['tests'][0]['intent']['slots']['alternate_state']. Got {'on': 'in an unknown state', 'idle': 'not playing', 'standby': 'in standby'}

Ruff
shared/__init__.py

26-26: Missing type annotation for self in method (ANN101)


33-33: Missing type annotation for self in method (ANN101)


40-40: Missing type annotation for self in method (ANN101)


72-72: Missing type annotation for self in method (ANN101)


88-88: get_matched_states is too complex (22 > 10) (C901)


89-89: Trailing comma missing (COM812)

Add trailing comma


166-169: Combine if branches using logical or operator (SIM114)

Combine if branches


179-179: get_matched_timers is too complex (11 > 10) (C901)


242-242: By default, jinja2 sets autoescape to False. Consider using autoescape=True or the select_autoescape function to mitigate XSS vulnerabilities. (S701)


254-254: Use of assert detected (S101)


289-289: Trailing comma missing (COM812)

Add trailing comma


293-293: Dynamically typed expressions (typing.Any) are disallowed in state_attr (ANN401)


340-342: Unnecessary generator (rewrite as a list comprehension) (C400)

Rewrite as a list comprehension


393-393: Trailing comma missing (COM812)

Add trailing comma


413-413: Trailing comma missing (COM812)

Add trailing comma


448-448: Trailing comma missing (COM812)

Add trailing comma

Additional comments not posted (3)
sentences/en/homeassistant_HassGetState.yaml (1)

18-18: LGTM! Ensure that excluding the media_player domain from certain state checks does not inadvertently affect other functionalities.

sentences/en/media_player_HassGetState.yaml (1)

1-75: LGTM! The new intents and responses for media players are well-structured and relevant. Please ensure they integrate smoothly with the existing system.

Verification successful

The new intents and responses for media players are well-structured and relevant. The verification script output indicates that the new intents and responses are well-integrated with the existing system, as evidenced by multiple references to media_player in various YAML files.

  • tests/en/media_player_HassGetState.yaml: Contains multiple references to domain: media_player, indicating proper context setup.
  • intents.yaml: Contains references to domain: media_player, suggesting integration with the main intents configuration.
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the integration of the new media player intents and responses with the existing system.

# Test: Search for the integration points in other YAML files. Expect: Smooth integration with the existing system.
rg --type yaml $'media_player'

Length of output: 11500

sentences/en/_common.yaml (1)

131-140: The updated media_player_states values enhance the flexibility and accuracy of state descriptions for media players. This change aligns well with the PR objectives.


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

Comment on lines +8 to +12
actual_state: "on"
alternate_state:
"on": "in an unknown state"
idle: "not playing"
standby: "in standby"
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Maybe these should actually be metadata?

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

Outside diff range comments (4)
shared/__init__.py (4)

Line range hint 120-168: The changes to get_matched_states enhance flexibility by allowing state_name to accept both strings and lists. However, the function's complexity is noted as too high. Consider refactoring to simplify the logic.

- def get_matched_states(
+ def get_matched_states(
  # Consider breaking down into smaller helper functions or simplifying the conditional logic.
Tools
Ruff

166-169: Combine if branches using logical or operator (SIM114)

Combine if branches


Line range hint 179-179: The get_matched_timers function is noted to be slightly too complex. Consider refactoring to simplify the conditional logic or breaking it into smaller functions.


Line range hint 242-242: Consider enabling autoescape in Jinja2 to mitigate potential XSS vulnerabilities.

- return Environment(loader=BaseLoader(), undefined=StrictUndefined)
+ return Environment(loader=BaseLoader(), undefined=StrictUndefined, autoescape=select_autoescape(['html', 'xml']))

Line range hint 254-254: Avoid using assert in production code as it can be disabled in optimized runs. Use explicit error handling instead.

- assert response_template, "Empty response template"
+ if not response_template:
+     raise ValueError("Empty response template")

Comment on lines +12 to +18
alternate_state: |
{{ slots.name | capitalize }} is {{ slots.actual_state }}, but it is
{% if state.state in slots.alternate_state %}
{{ slots.alternate_state[state.state] }}
{% else %}
{{ state.state }}
{% endif %}
Copy link

@coderabbitai coderabbitai bot Jun 13, 2024

Choose a reason for hiding this comment

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

The new alternate_state response template enhances descriptive accuracy but may have an issue with the actual_state attribute.

- {{ slots.name | capitalize }} is {{ slots.actual_state }}, but it is
+ {{ slots.name | capitalize }} is {{ state.state_with_unit }}, but it is
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
alternate_state: |
{{ slots.name | capitalize }} is {{ slots.actual_state }}, but it is
{% if state.state in slots.alternate_state %}
{{ slots.alternate_state[state.state] }}
{% else %}
{{ state.state }}
{% endif %}
alternate_state: |
{{ slots.name | capitalize }} is {{ state.state_with_unit }}, but it is
{% if state.state in slots.alternate_state %}
{{ slots.alternate_state[state.state] }}
{% else %}
{{ state.state }}
{% endif %}

Copy link
Contributor Author

Choose a reason for hiding this comment

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

That's a slot being passed from sentences/en/media_player_HassGetState.yaml, so first of all it's not an attribute and second of all it is not a problem.

Copy link

Choose a reason for hiding this comment

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

@tetele Thank you for the clarification on the actual_state slot usage. I appreciate your insight and understanding of the implementation details. If there's anything else you need assistance with regarding this PR, feel free to let me know!

Comment on lines +1 to +125
- "on"
- "idle"
- "paused"
- "standby"
- "buffering"
actual_state: "not off"
alternate_state:
"on": "in an unknown state"
idle: "not playing anything"
standby: "in standby"
context:
domain: media_player
volume_level: "50"
response: "Tv is not off, but it is not playing anything"

- sentences:
- "is the TV playing?"
intent:
name: HassGetState
slots:
name: "TV"
state: "playing"
context:
domain: media_player
volume_level: "50"
response: "No, idle"

- sentences:
- "is the TV standing by?"
intent:
name: HassGetState
slots:
name: "TV"
state:
- "on"
- "idle"
- "standby"
- "buffering"
context:
domain: media_player
volume_level: "50"
response: "Yes"

- sentences:
- "are any media players on in the kitchen?"
intent:
name: HassGetState
slots:
area: "Kitchen"
domain: "media_player"
state: "playing"
response: "No"

- sentences:
- "are all media players on?"
intent:
name: HassGetState
slots:
domain: "media_player"
state: "playing"
response: "No, TV is not on"

- sentences:
- "are all media players off?"
intent:
name: HassGetState
slots:
domain: "media_player"
state: "off"
response: "No, TV is not off"

- sentences:
- "which media players are on?"
intent:
name: HassGetState
slots:
domain: "media_player"
state: "playing"
response: "Not any"

- sentences:
- "how many media players are on?"
intent:
name: HassGetState
slots:
domain: "media_player"
state: "playing"
response: "0"

- sentences:
- "are all the media players on in the living room"
- "are all media players on in the living room?"
- "are all media players in the living room on?"
intent:
name: HassGetState
slots:
domain: "media_player"
state: "playing"
area: "Living Room"
response: "No, TV is not on"
Copy link

Choose a reason for hiding this comment

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

The test scenarios are well-designed but there's an issue with the format of alternate_state.

- alternate_state:
-   "on": "in an unknown state"
-   idle: "not playing"
-   standby: "in standby"
+ alternate_state: "in an unknown state"

Committable suggestion was skipped due to low confidence.

Tools
GitHub Check: build

[failure] 1-1:
invalid format: Expected anything but a dictionary for dictionary value @ data['tests'][0]['intent']['slots']['alternate_state']. Got {'on': 'in an unknown state', 'idle': 'not playing', 'standby': 'in standby'}

@tetele tetele requested a review from synesthesiam June 13, 2024 13:40
@@ -372,6 +382,7 @@ expansion_rules:
in: "(in|on|at|of)"
position: "{position}[[ ]%| percent]"
volume: "{volume:volume_level}[[ ]%| percent]"
media_players: "([media ]player[s]|speaker[s]stereo[s]|tv[s])"
Copy link
Contributor

Choose a reason for hiding this comment

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

Missing a | between speaker and stereo. Should maybe add television? Also, this could be simplified by moving the [s] to the end.

Suggested change
media_players: "([media ]player[s]|speaker[s]stereo[s]|tv[s])"
media_players: "([media ]player|speaker|stereo|tv|television)[s]"

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Agreed regarding television, but moving the [s] at the end makes it less readable and does not optimize matching.

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.

HassGetState and media players
2 participants