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: voice replacment agent #154

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

Conversation

omgate234
Copy link

@omgate234 omgate234 commented Mar 4, 2025

Added a voice replacement agent. This agent takes voice sample from a sample video and overlays given videos with the cloned voice.

Inputs:

  • a sample video from which sample audio file is extracted
  • videos which have to be overlayed with the cloned voice

Output:

  • Video streams of all videos with the cloned voice instead of their original voices

Summary by CodeRabbit

  • New Features
    • Added a voice replacement capability that enables users to clone their voice and overlay it on videos, complete with robust audio and video processing.
    • Integrated the new voice replacement option into the main chat interface.
    • Enhanced audio processing tools to support audio cloning, voice retrieval, and text-to-speech synthesis.
    • Updated video features to provide direct access to audio links.

Copy link
Contributor

coderabbitai bot commented Mar 4, 2025

Walkthrough

A new VoiceReplacementAgent has been added which handles voice cloning and audio overlaying for videos by downloading media, extracting audio, managing transcripts, and synthesizing new audio using the ElevenLabs API. The agent is integrated into the existing ChatHandler. In addition, the ElevenLabs tool now includes methods to clone audio, retrieve voices, and synthesize text. The VideoDBTool has been enhanced to return a URL for audio files. Overall, these updates improve the system's audio processing capabilities with structured error handling and timeline management.

Changes

File(s) Change Summary
backend/director/agents/voice_replacement.py
backend/director/handler.py
Added new VoiceReplacementAgent class with methods for video/audio download, audio extraction, transcript retrieval, timeline updates, and voice cloning orchestration; integrated the agent into the ChatHandler agents list.
backend/director/tools/elevenlabs.py Introduced new methods: clone_audio, get_voice, and synthesis_text for managing voice cloning and text-to-audio synthesis, along with a new import for RequestOptions and accompanying error handling.
backend/director/tools/videodb_tool.py Updated get_audio method to include an additional key-value pair that returns an audio URL generated via the generate_url method.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant CH as ChatHandler
    participant VRA as VoiceReplacementAgent
    participant EL as ElevenLabsTool
    participant VDB as VideoDBTool

    U->>CH: Request voice replacement
    CH->>VRA: Invoke run() method with required parameters
    VRA->>VRA: Download video (_download_video_file)
    VRA->>VRA: Download audio (_download_audio_file)
    VRA->>VRA: Extract audio (_extract_audio_from_video)
    VRA->>VRA: Retrieve transcript (_get_transcript)
    alt Existing voice provided?
        VRA->>EL: Retrieve voice (get_voice)
    else
        VRA->>EL: Clone voice (clone_audio)
    end
    VRA->>EL: Synthesize text to audio (synthesis_text)
    VRA->>VDB: Upload audio & get URL (generate_url)
    VRA->>CH: Return AgentResponse (success/failure)
    CH->>U: Relay final response
Loading

Suggested reviewers

  • 0xrohitgarg
  • ashish-spext

Poem

I’m a rabbit with a joyful leap,
Hoping through new code so deep,
Cloning voices with a digital flair,
Overlaying dreams with utmost care,
In binary fields my hops compete,
Celebrating changes in every beat! 🐇

✨ Finishing Touches
  • 📝 Generate Docstrings

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.
  • @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

🧹 Nitpick comments (8)
backend/director/tools/elevenlabs.py (3)

233-239: Add error handling around voice cloning.

Currently, the method relies on the caller to handle exceptions. Consider wrapping the self.client.clone() call in a try/except block, logging errors, and returning a more descriptive message if cloning fails.


241-243: Handle non-existent or restricted voices.

If the voice lookup fails or if the user does not have access to a voice, this method may raise exceptions. Adding a try/except here would improve reliability and provide clearer error messages.


245-252: Use a logger for errors instead of print statements.

While the exception handling is good, consider using logger.error(...) for consistency instead of a raw print statement to maintain standardized logging across the codebase.

-except Exception as e:
-    print(f"Error while text synthesis {e}")
-    return None
+except Exception as e:
+    logger.error(f"Error while text synthesis {e}")
+    return None
backend/director/agents/voice_replacement.py (5)

78-101: Use consistent error logging.

_download_video_file uses a raw print() statement for errors (line 99) whereas _download_audio_file uses logger.error(). For uniformity, switch to logger.error() here as well to ensure consistent logging.

-    print(f"Failed to download {video_url}: {e}")
+    logger.error(f"Failed to download {video_url}: {e}")

102-124: Check content type before saving.

Unlike _download_video_file, _download_audio_file doesn’t verify that the resource is actually audio (e.g., Content-Type: audio/*). Adding a similar check to avoid silently saving invalid files would harden the logic.


125-135: Clarify audio extraction flow.

The method uploads the entire video as media_type="audio" and relies on the backend to extract audio. Consider documenting this behavior more explicitly or verifying the backend’s success before proceeding to download.


188-233: Robust approach to sample and clone.

Using the partial video stream from start_time to end_time is a flexible solution for capturing audio. The fallback to an existing cloned_voice_id or creating a new voice is well-handled. Just be mindful that extremely short or long audio might affect clone quality.


234-310: Mixed error-handling behavior within the loop.

If text synthesis fails (line 243), the method returns immediately, but if uploading fails (line 258), it continues to process other videos. Consider aligning behavior—either skip each failure or return immediately. Consistent logic helps users predict outcomes.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d6e125b and 762a71b.

📒 Files selected for processing (4)
  • backend/director/agents/voice_replacement.py (1 hunks)
  • backend/director/handler.py (2 hunks)
  • backend/director/tools/elevenlabs.py (2 hunks)
  • backend/director/tools/videodb_tool.py (1 hunks)
🔇 Additional comments (8)
backend/director/handler.py (2)

28-28: Add basic unit tests for the newly introduced agent.

The import for VoiceReplacementAgent is straightforward; however, ensure that the new agent is covered by unit tests (or integration tests) to confirm correct behavior and avoid regressions, especially given its external dependencies.


73-73: Confirmed integration of the new agent.

No issues found with appending the agent to self.agents. This change properly registers the VoiceReplacementAgent in the handler.

backend/director/tools/videodb_tool.py (1)

154-154: LGTM: Providing audio URLs is beneficial.

Adding the generated URL in the dictionary return value is a helpful enhancement. Make sure any upstream consumers handle potential failures in audio.generate_url(), but otherwise this looks good.

backend/director/tools/elevenlabs.py (2)

6-6: Import usage looks valid.

Importing RequestOptions is consistent with the usage in synthesis_text(). No issues here.


232-232: No functional changes.

This blank line appears to be purely stylistic. No further action required.

backend/director/agents/voice_replacement.py (3)

136-148: Efficient fallback for no transcript.

The retry logic is clear—if a transcript is unavailable, you index spoken words, then retrieve it. This is a neat pattern. Just ensure that indexing won't cause indefinite retries if something fails repeatedly (here it appears to raise on error, which is sufficient).


149-159: Overlay logic is straightforward.

Adding the video inline first and audio as an overlay next is clear. Ensure large audio clips or misaligned durations are handled gracefully. Otherwise, this function looks good.


160-186: Authorization check is valid.

Returning an error immediately if is_authorized_to_clone_voice is false ensures no unintentionally cloned voices. Good approach.

video = self.videodb_tool.get_video(video_id=video_id)
text_to_synthesis = self._get_transcript(video_id=video_id)

self.output_message.actions.append(f"Synthesising {video["name"]}'s transcript in cloned voice")
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix f-string quoting errors.

These strings will cause a syntax error because they nest double quotes. Replace video["name"] with video['name'] inside the f-strings:

- f"Synthesising {video["name"]}'s transcript in cloned voice"
+ f"Synthesising {video['name']}'s transcript in cloned voice"

- status_message=f"Adding cloned voice to {video["name"]} failed"
+ status_message=f"Adding cloned voice to {video['name']} failed"

- status_message=f"Adding cloned voice to {video["name"]}"
+ status_message=f"Adding cloned voice to {video['name']}"

- f"Here is your video {video["name"]} with the cloned voice"
+ f"Here is your video {video['name']} with the cloned voice"

Also applies to: 261-261, 270-270, 284-284

@omgate234 omgate234 changed the title Feat/voice replacement video sample feat: voice replacment agent Mar 4, 2025
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.

1 participant