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

Added a possibility to select which speaker device to use #96

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

icarosadero
Copy link

@icarosadero icarosadero commented Jan 14, 2025

This change allows the user to select which device to use for the calls to sounddevice.play. It can be set as an extra option in the glados_config.yml file like so:

Glados:
  completion_url: "http://localhost:11434/api/chat"
  model: "llama3.2"
 (...)
  wake_word: null
IO:
  speaker_device: <id_to_speaker_device>

To list the available devices and their IDs, just run sounddevice.query_devices()

Summary by CodeRabbit

  • New Features

    • Added support for configuring audio output device through a YAML configuration file
    • Enhanced system configuration with flexible device selection
  • Improvements

    • Improved configuration loading with fallback encoding support

Copy link
Contributor

coderabbitai bot commented Jan 14, 2025

Walkthrough

The pull request introduces a new function configure_io in the glados.py file, which enables dynamic configuration of audio output devices through a YAML configuration file. The function reads the configuration file, handling potential encoding issues, and sets the default speaker device using the sounddevice library. The start method is modified to call this new configuration function before initializing the main Glados class functionality, allowing for more flexible audio device selection.

Changes

File Change Summary
glados.py - Added configure_io function to read YAML configuration for speaker device
- Modified start method to call configure_io("glados_config.yml") before loading configuration

Sequence Diagram

sequenceDiagram
    participant Config as YAML Config
    participant ConfigFunc as configure_io()
    participant Sounddevice as sounddevice
    participant Glados as Glados.start()

    Config->>ConfigFunc: Read configuration file
    ConfigFunc-->>Config: Parse YAML
    ConfigFunc->>Sounddevice: Set default speaker device
    Sounddevice-->>ConfigFunc: Device configured
    ConfigFunc-->>Glados: Return configuration
    Glados->>Glados: Continue initialization
Loading

Possibly related PRs

Poem

🐰 A rabbit's config tale unfolds,
Where YAML secrets gently hold
The speaker's path, a sonic dream
With sounddevice's gentle stream
Configuration, now so neat! 🎧

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.

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 comments (1)
glados.py (1)

Confirmed: Audio device handling needs improvement

The codebase lacks robust error handling for audio device operations:

  • No error handling when setting sd.default.device
  • Missing device availability checks before playback
  • No recovery mechanism for device disconnection
  • Basic stream monitoring without proper error recovery
🔗 Analysis chain

Line range hint 401-401: Add robust speaker device handling.

The speaker device is used in multiple places but lacks handling for device changes or failures during runtime. Consider:

  1. Device disconnection during playback
  2. Device becoming unavailable between calls
  3. Device hot-plugging scenarios

Let's verify the current error handling:

Consider implementing a robust audio device manager that:

  1. Monitors device availability
  2. Handles device changes gracefully
  3. Falls back to default device when necessary
  4. Provides device status callbacks

Would you like me to propose a design for this enhancement?

Also applies to: 154-154, 90-90

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for error handling around sounddevice.play calls
rg -A 2 "sd\.play" 

Length of output: 412


Script:

#!/bin/bash
# Search for exception handling and device management
rg -B 2 -A 4 "try:.*sd\." 

# Search for sounddevice device configuration
rg -B 2 -A 4 "sd\.(get|set|default|query|check)"

Length of output: 627

🧰 Tools
🪛 Ruff (0.8.2)

87-88: Use a single if statement instead of nested if statements

Combine if statements using and

(SIM102)


88-88: Use key in dict instead of key in dict.keys()

Remove .keys()

(SIM118)

🧹 Nitpick comments (1)
glados.py (1)

622-625: Optimize YAML file reading and add error handling.

The current implementation reads the YAML file twice:

  1. Once in configure_io
  2. Again in GladosConfig.from_yaml

Consider refactoring to read the file once and share the parsed data.

Apply this diff to improve efficiency:

 def start() -> None:
     """Set up the LLM server and start GlaDOS."""
-    configure_io("glados_config.yml")
-    glados_config = GladosConfig.from_yaml("glados_config.yml")
+    try:
+        # Read YAML file once
+        with open("glados_config.yml", "r", encoding="utf-8") as file:
+            config_data = yaml.safe_load(file)
+        
+        # Configure IO using the parsed data
+        if "IO" in config_data:
+            configure_io_from_dict(config_data["IO"])
+        
+        # Create Glados config using the parsed data
+        glados_config = GladosConfig.from_dict(config_data.get("Glados", {}))
+        
+        # Start Glados
+        glados = Glados.from_config(glados_config)
+        glados.start_listen_event_loop()
+    except Exception as e:
+        logger.error(f"Failed to start GlaDOS: {e}")
+        sys.exit(1)

This requires adding two new methods:

  1. configure_io_from_dict to configure IO from parsed data
  2. GladosConfig.from_dict to create config from parsed data

Would you like me to generate the implementation for these methods?

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ae91a2e and c2ed29c.

📒 Files selected for processing (1)
  • glados.py (2 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
glados.py

87-88: Use a single if statement instead of nested if statements

Combine if statements using and

(SIM102)


88-88: Use key in dict instead of key in dict.keys()

Remove .keys()

(SIM118)

Comment on lines +75 to +90
def configure_io(path: str, key: str = "IO"):
data = None

try:
# First attempt with UTF-8
with open(path, "r", encoding="utf-8") as file:
data = yaml.safe_load(file).get(key, None)
except UnicodeDecodeError:
# Fall back to utf-8-sig if UTF-8 fails (handles BOM)
with open(path, "r", encoding="utf-8-sig") as file:
data = yaml.safe_load(file).get(key, None)

if data is not None:
if "speaker_device" in data.keys():
logger.debug(f"Setting speaker device to {data['speaker_device']}")
sd.default.device = data["speaker_device"]
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling and input validation.

The function needs improvements in several areas:

  1. Add error handling for file not found and invalid YAML
  2. Validate the speaker device ID before setting it
  3. Add type hints for parameters

Apply this diff to improve the function:

-def configure_io(path: str, key: str = "IO"):
+def configure_io(path: str, key: str = "IO") -> None:
+    """Configure IO devices from YAML configuration file.
+    
+    Args:
+        path: Path to the YAML configuration file
+        key: Key in the YAML file containing IO configuration (default: "IO")
+        
+    Raises:
+        FileNotFoundError: If the configuration file is not found
+        yaml.YAMLError: If the configuration file is invalid
+        ValueError: If the speaker device ID is invalid
+    """
     data = None
     
     try:
         # First attempt with UTF-8
         with open(path, "r", encoding="utf-8") as file:
             data = yaml.safe_load(file).get(key, None)
     except UnicodeDecodeError:
         # Fall back to utf-8-sig if UTF-8 fails (handles BOM)
         with open(path, "r", encoding="utf-8-sig") as file:
             data = yaml.safe_load(file).get(key, None)
+    except FileNotFoundError:
+        logger.error(f"Configuration file not found: {path}")
+        raise
+    except yaml.YAMLError as e:
+        logger.error(f"Invalid YAML in configuration file: {e}")
+        raise
     
-    if data is not None:
-        if "speaker_device" in data.keys():
-            logger.debug(f"Setting speaker device to {data['speaker_device']}")
-            sd.default.device = data["speaker_device"]
+    if data is not None and "speaker_device" in data:
+        speaker_device = data["speaker_device"]
+        try:
+            # Query available devices to validate the speaker device ID
+            devices = sd.query_devices()
+            if not any(d["index"] == speaker_device for d in devices):
+                raise ValueError(f"Invalid speaker device ID: {speaker_device}")
+            
+            logger.debug(f"Setting speaker device to {speaker_device}")
+            sd.default.device = speaker_device
+        except sd.PortAudioError as e:
+            logger.error(f"Error accessing audio devices: {e}")
+            raise ValueError(f"Error accessing audio devices: {e}") from e
📝 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
def configure_io(path: str, key: str = "IO"):
data = None
try:
# First attempt with UTF-8
with open(path, "r", encoding="utf-8") as file:
data = yaml.safe_load(file).get(key, None)
except UnicodeDecodeError:
# Fall back to utf-8-sig if UTF-8 fails (handles BOM)
with open(path, "r", encoding="utf-8-sig") as file:
data = yaml.safe_load(file).get(key, None)
if data is not None:
if "speaker_device" in data.keys():
logger.debug(f"Setting speaker device to {data['speaker_device']}")
sd.default.device = data["speaker_device"]
def configure_io(path: str, key: str = "IO") -> None:
"""Configure IO devices from YAML configuration file.
Args:
path: Path to the YAML configuration file
key: Key in the YAML file containing IO configuration (default: "IO")
Raises:
FileNotFoundError: If the configuration file is not found
yaml.YAMLError: If the configuration file is invalid
ValueError: If the speaker device ID is invalid
"""
data = None
try:
# First attempt with UTF-8
with open(path, "r", encoding="utf-8") as file:
data = yaml.safe_load(file).get(key, None)
except UnicodeDecodeError:
# Fall back to utf-8-sig if UTF-8 fails (handles BOM)
with open(path, "r", encoding="utf-8-sig") as file:
data = yaml.safe_load(file).get(key, None)
except FileNotFoundError:
logger.error(f"Configuration file not found: {path}")
raise
except yaml.YAMLError as e:
logger.error(f"Invalid YAML in configuration file: {e}")
raise
if data is not None and "speaker_device" in data:
speaker_device = data["speaker_device"]
try:
# Query available devices to validate the speaker device ID
devices = sd.query_devices()
if not any(d["index"] == speaker_device for d in devices):
raise ValueError(f"Invalid speaker device ID: {speaker_device}")
logger.debug(f"Setting speaker device to {speaker_device}")
sd.default.device = speaker_device
except sd.PortAudioError as e:
logger.error(f"Error accessing audio devices: {e}")
raise ValueError(f"Error accessing audio devices: {e}") from e
🧰 Tools
🪛 Ruff (0.8.2)

87-88: Use a single if statement instead of nested if statements

Combine if statements using and

(SIM102)


88-88: Use key in dict instead of key in dict.keys()

Remove .keys()

(SIM118)

@dnhkng
Copy link
Owner

dnhkng commented Jan 14, 2025

Hmmm, could you add in the ability to select the recording source too?

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