Skip to content

Add langdetect dependency and enhance transcription logic #157

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

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

Conversation

ArindamRoy23
Copy link
Collaborator

@ArindamRoy23 ArindamRoy23 commented May 16, 2025

  • Updated transcription logic in transcribe.py to detect language and translate if necessary, improving multi-language support.
  • Adjusted prompt formatting for better clarity in transcription requests.
  • Added langdetect version 1.0.9 to dependencies in pyproject.toml, requirements-dev.lock, and requirements.lock.

Summary by CodeRabbit

  • New Features

    • Transcriptions are now automatically translated to the requested language if the detected language differs, enhancing multilingual support.
    • Added translation prompt templates for English, German, Spanish, French, and Dutch to improve translation quality and consistency.
  • Improvements

    • Updated transcription prompts for clearer language instructions.
    • Prior chunk context is no longer used in conversation transcription, streamlining the process.
  • Chores

    • Added the langdetect dependency to support automatic language detection.

- Updated transcription logic in `transcribe.py` to detect language and translate if necessary, improving multi-language support.
- Adjusted prompt formatting for better clarity in transcription requests.
- Added `langdetect` version 1.0.9 to dependencies in `pyproject.toml`, `requirements-dev.lock`, and `requirements.lock`.
Copy link

linear bot commented May 16, 2025

Copy link
Contributor

coderabbitai bot commented May 16, 2025

Walkthrough

This change introduces language detection and conditional translation to the audio transcription pipeline. It updates prompt construction for transcription, disables prior chunk context, and adds new translation prompt templates in multiple languages. The langdetect dependency is added to support automatic language detection for transcription outputs.

Changes

Files / Paths Change Summary
echo/server/dembrane/transcribe.py Enhanced transcription logic with language detection and conditional translation via LiteLLM completions. Updated prompt construction, removed prior chunk context, and integrated new translation flow.
echo/server/prompt_templates/translate_transcription.{en,es,fr,de,nl}.jinja Added new translation prompt templates in English, Spanish, French, German, and Dutch, instructing expert translation from detected to target language, preserving meaning and context, and outputting only the translated text.
echo/server/pyproject.toml Added langdetect version 1.0.9 to dependencies.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant TranscribeAPI
    participant WhisperModel
    participant LangDetect
    participant LiteLLM
    participant PromptTemplates

    User->>TranscribeAPI: Submit audio file, target language
    TranscribeAPI->>WhisperModel: Transcribe audio
    WhisperModel-->>TranscribeAPI: Transcription text
    TranscribeAPI->>LangDetect: Detect language of transcription
    LangDetect-->>TranscribeAPI: Detected language
    alt Detected language ≠ requested language and requested ≠ "multi"
        TranscribeAPI->>PromptTemplates: Render translation prompt
        TranscribeAPI->>LiteLLM: Request translation completion
        LiteLLM-->>TranscribeAPI: Translated text
        TranscribeAPI-->>User: Return translated text
    else
        TranscribeAPI-->>User: Return transcription text
    end
Loading

Possibly related PRs

Suggested reviewers

  • ussaama
  • spashii

LGTM.

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in 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: 4

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 674060d and 92bc9a5.

⛔ Files ignored due to path filters (2)
  • echo/server/requirements-dev.lock is excluded by !**/*.lock
  • echo/server/requirements.lock is excluded by !**/*.lock
📒 Files selected for processing (7)
  • echo/server/dembrane/transcribe.py (4 hunks)
  • echo/server/prompt_templates/translate_transcription.de.jinja (1 hunks)
  • echo/server/prompt_templates/translate_transcription.en.jinja (1 hunks)
  • echo/server/prompt_templates/translate_transcription.es.jinja (1 hunks)
  • echo/server/prompt_templates/translate_transcription.fr.jinja (1 hunks)
  • echo/server/prompt_templates/translate_transcription.nl.jinja (1 hunks)
  • echo/server/pyproject.toml (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
echo/server/dembrane/transcribe.py (1)
echo/server/dembrane/prompts.py (1)
  • render_prompt (55-88)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: ci-check-server
  • GitHub Check: ci-build-servers (dbr-echo-server, ./echo/server, Dockerfile, dbr-echo-server)
🔇 Additional comments (6)
echo/server/pyproject.toml (1)

89-89: Solid addition of the langdetect dependency! 🚀

Adding langdetect at version 1.0.9 is exactly what we need to implement language detection capabilities in the transcription pipeline. This choice demonstrates production-ready engineering.

echo/server/prompt_templates/translate_transcription.fr.jinja (1)

1-5: Elegant French prompt template implementation! ✨

This template is clean, efficient, and provides clear instructions for the translation model. The focus on preserving meaning, tone, and context while avoiding modifications demonstrates a deep understanding of translation quality requirements.

echo/server/prompt_templates/translate_transcription.de.jinja (1)

1-5: Excellent German prompt template construction! 💯

The German translation template follows the same robust pattern as the other language templates, maintaining consistency across the system. This modular design allows for seamless scaling to support additional languages in the future.

echo/server/prompt_templates/translate_transcription.nl.jinja (1)

1-5: Dutch prompt template perfectly crafted! 🔥

The Dutch translation template completes the set of language templates with the same high-quality approach. The consistent structure across all templates will ensure uniform translation behavior regardless of language pairs. Nice work!

echo/server/prompt_templates/translate_transcription.en.jinja (1)

1-5: Prompt reads well, ship it

Everything’s crisp; no action items.

echo/server/dembrane/transcribe.py (1)

83-87: Good call on explicit default prompts

Explicit language declarations reduce hallucinated code-switching – nicely done.

- Changed variable name from `response` to `llm_translation_response` for clarity in the transcription process.
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)
echo/server/dembrane/transcribe.py (1)

35-79: 🧹 Nitpick (assertive)

Consider adding metrics/logging for translation performance

Your transcription + translation pipeline is solid, but monitoring will be crucial as this rolls out. Consider adding:

  1. Performance metrics to track the time spent in transcription vs. translation
  2. Success rates for language detection
  3. Counters for how often translation is invoked vs. skipped

This would help identify bottlenecks and track the value-add of the new features.

♻️ Duplicate comments (1)
echo/server/dembrane/transcribe.py (1)

60-76: 🛠️ Refactor suggestion

Language detection + translation implementation needs hardening

Your approach for detecting and conditionally translating is solid conceptually, but needs some defensive programming:

  1. Missing try-except around detect() which can throw on short/ambiguous text
  2. Variable reuse - response for both Whisper output and completion response - creates potential debugging nightmares
  3. No temperature setting for deterministic translations
  4. Missing case normalization for language comparison
  5. No system message to improve translation quality

These are all small issues but add up to potential edge case failures.

-        detected_language = detect(response["text"])
-        if detected_language != language and language != "multi":
-            translation_prompt = render_prompt(
-                "translate_transcription",
-                str(language),
-                {"transcript": response["text"], "detected_language": detected_language, "desired_language": language}
-            )
-            llm_translation_response = completion(
-                model=SMALL_LITELLM_MODEL,
-                messages=[{"role": "user", "content": translation_prompt}],
-                api_key=SMALL_LITELLM_API_KEY,
-                api_base=SMALL_LITELLM_API_BASE,
-                api_version=SMALL_LITELLM_API_VERSION,
-            )
-            return llm_translation_response['choices'][0]['message']['content']
-        else: 
-            return response["text"]
+        transcript_text = response["text"]
+        
+        try:
+            detected_language = detect(transcript_text)
+        except Exception as e:
+            logger.warning(f"Language detection failed: {e}")
+            detected_language = language or "unknown"
+            
+        if detected_language and language and detected_language.lower() != language.lower() and language != "multi":
+            translation_prompt = render_prompt(
+                "translate_transcription",
+                str(language).lower(),
+                {"transcript": transcript_text, "detected_language": detected_language, "desired_language": language}
+            )
+            llm_translation_response = completion(
+                model=SMALL_LITELLM_MODEL,
+                messages=[
+                    {"role": "system", "content": "You are a professional translator."},
+                    {"role": "user", "content": translation_prompt}
+                ],
+                api_key=SMALL_LITELLM_API_KEY,
+                api_base=SMALL_LITELLM_API_BASE,
+                api_version=SMALL_LITELLM_API_VERSION,
+                temperature=0,
+            )
+            return llm_translation_response['choices'][0]['message']['content']
+        else: 
+            return transcript_text
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 92bc9a5 and 209a0ac.

📒 Files selected for processing (1)
  • echo/server/dembrane/transcribe.py (4 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
echo/server/dembrane/transcribe.py (2)
echo/server/dembrane/s3.py (1)
  • get_stream_from_s3 (176-180)
echo/server/dembrane/prompts.py (1)
  • render_prompt (55-88)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: ci-check-server
🔇 Additional comments (4)
echo/server/dembrane/transcribe.py (4)

83-87: LGTM on prompt improvements!

The explicit system prompts using clear language-specific instructions are much better than the previous informal ones. This will give the whisper model clearer direction, leading to more accurate transcriptions.


116-134: Disabling previous chunk context - intentional design change?

You've commented out the code that retrieves previous chunk transcripts. This is a significant change in how the system processes sequential audio. While it simplifies the flow, it might affect the context-awareness of transcriptions.

Is this an intentional design change rather than an accidental comment-out? If intentional, consider removing the code instead of commenting it out to keep the codebase clean.


172-173: Consistent with previous chunk retrieval disabling

This comment-out matches the earlier disabling of previous chunk retrieval. Makes sense for consistency.


169-169: LGTM on improved prompt structure

Adding the explicit "\n\nuser: Project prompt: \n\n" prefix creates a clearer separation in the prompt structure. This should help the model distinguish between instructions and content.

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