Skip to content

DuongCaoNhan/pluralsight-ai-translator-ext

Repository files navigation

<<<<<<< Updated upstream

pluralsight-ai-translator-ext

=======

Pluralsight Bilingual AI Translator - Chrome Extension

A powerful Chrome Extension (Manifest V3) that translates English subtitles on Pluralsight.com to Vietnamese (or other languages) in real-time using LLM APIs like OpenAI GPT or Google Gemini.

🎯 Features

Real-time Translation - Automatically translates subtitles as they appear
Dual Display - Shows both English (original) and translated (yellow italic) subtitles simultaneously
Smart Caching - Avoids re-translating the same subtitle if you rewind
Multiple Languages - Supports Vietnamese, Spanish, French, German, Japanese, Chinese
Dual API Support - Works with OpenAI and Google Gemini APIs
Async/Await Architecture - Non-blocking translation to prevent UI freezing
Efficient Observation - Uses MutationObserver for precise subtitle detection

📋 Project Structure

Pluralsight-Bilingual-Translator/
├── manifest.json          # Chrome Extension configuration (Manifest V3)
├── popup.html             # Settings UI for API key and language selection
├── popup.js               # Popup logic for saving/loading settings
├── styles.css             # Popup and extension styling
├── content.js             # Core logic: subtitle detection + injection (MutationObserver)
├── background.js          # Service worker: API request handling (CORS workaround)
└── README.md             # This file

🚀 Installation & Setup

Prerequisites

  • Chrome/Chromium browser (v88+)
  • OpenAI API key OR Google Gemini API key
  • Pluralsight account with active video content

Step 1: Obtain an API Key

Option A: OpenAI (Recommended)

  1. Go to https://platform.openai.com/api-keys
  2. Create a new API key
  3. Keep it secret (never share publicly)

Option B: Google Gemini

  1. Go to https://aistudio.google.com/apikey
  2. Create a new API key
  3. Keep it secret (never share publicly)

Step 2: Install the Extension

  1. Clone or download this repository
  2. Open Chrome and navigate to chrome://extensions/
  3. Enable "Developer mode" (top-right corner)
  4. Click "Load unpacked" and select the Pluralsight-Bilingual-Translator folder
  5. The extension icon should appear in your toolbar

Step 3: Configure Settings

  1. Click the extension icon in your Chrome toolbar
  2. Enter your API key (OpenAI or Google Gemini)
  3. Select your API provider
  4. Choose your target language (default: Vietnamese)
  5. Click "Save Settings"

Step 4: Start Watching Videos

  1. Navigate to a Pluralsight course with English subtitles
  2. Enable subtitles in the video player
  3. The extension will automatically detect and translate subtitles
  4. Translations appear in yellow italic text below the English subtitle

🔧 Technical Architecture

Manifest V3 Compliance

{
  "manifest_version": 3,
  "permissions": ["storage", "scripting"],
  "host_permissions": ["https://www.pluralsight.com/*"],
  "action": { "default_popup": "popup.html" },
  "background": { "service_worker": "background.js" },
  "content_scripts": [...]
}

Content Script: Subtitle Detection (MutationObserver)

The content.js implements a robust MutationObserver strategy:

// Detects changes in subtitle DOM
const observer = new MutationObserver((mutations) => {
  handleSubtitleMutation(mutations);
});

observer.observe(subtitleContainer, {
  childList: true,      // Watch for added/removed nodes
  subtree: true,        // Observe all descendants
  characterData: true   // Watch for text changes
});

Selector Strategy:

  • Searches multiple possible subtitle selectors to handle different Pluralsight player versions
  • Fallback mechanism if initial selectors fail
  • Retry logic with 2-second intervals

Translation Pipeline

Subtitle Text Detected (content.js)
         ↓
  Generate Hash (for caching)
         ↓
  Check Translation Cache
         ↓
  If Not Cached → Send to API (message passing to background.js)
         ↓
  API Response (OpenAI or Gemini)
         ↓
  Cache Result + Inject into DOM
         ↓
  Display with Yellow Styling

API Integration (Background Service Worker)

OpenAI GPT-3.5-turbo:

POST https://api.openai.com/v1/chat/completions
Header: Authorization: Bearer {API_KEY}
Body: {
  "model": "gpt-3.5-turbo",
  "messages": [
    {"role": "system", "content": "You are a tech translator..."},
    {"role": "user", "content": "Original subtitle text"}
  ]
}

Google Gemini:

POST https://generativelanguage.googleapis.com/v1/models/gemini-pro:generateContent?key={API_KEY}
Body: {
  "contents": [{"role": "user", "parts": [{"text": "..."}]}]
}

Smart Caching System

  • Cache Structure: Map<hash, { original, translation }>
  • Persistence: Cached data stored in chrome.storage.local
  • Hash Function: Simple numeric hash of subtitle text
  • Benefits:
    • Prevents duplicate API calls when rewinding
    • Reduces API costs
    • Improves performance

📝 Configuration Details

Supported Languages

  • Vietnamese (default)
  • Spanish
  • French
  • German
  • Japanese
  • Chinese (Simplified)

To add more languages, edit popup.html and add options:

<option value="[Language Name]">[Display Name]</option>

System Prompt

Sent to LLM for every translation:

You are a tech translator. Translate the following technical sentence to {language} 
concisely. Do not add explanations.

Customize by editing background.js:

const SYSTEM_PROMPT = `Your custom prompt here...`;

API Models Used

  • OpenAI: gpt-3.5-turbo (set model in background.js for GPT-4)
  • Gemini: gemini-pro

Change to GPT-4 in background.js:

model: 'gpt-4' // Requires GPT-4 API access

🔒 Security & Privacy

API Keys Stored Securely:

  • Keys stored in chrome.storage.sync (encrypted by Chrome)
  • Never logged or sent to external services except the API provider
  • User controls what data is sent

No Data Collection:

  • No analytics or tracking
  • No server backend
  • Direct API calls only

Best Practices:

  • Never commit API keys to version control
  • Use environment variables or .env files if developing locally
  • Consider using restricted API keys with usage limits

🐛 Troubleshooting

Translations Not Appearing

  1. Check if extension is enabled:

    • Go to chrome://extensions/
    • Verify the extension is toggled ON
  2. Verify API key:

    • Click extension icon → Check if API key is saved
    • Test API key directly at OpenAI/Gemini console
  3. Check Console:

    • Right-click on Pluralsight video → Inspect → Console
    • Look for [Pluralsight Translator] log messages
    • Check for API errors
  4. Ensure subtitles are enabled:

    • Enable subtitles in the Pluralsight video player (CC button)
    • Translator only works if subtitles are visible

API Errors

"401 Unauthorized"

  • Invalid API key
  • Check if API key is correctly copied
  • Ensure key hasn't expired

"429 Rate Limited"

"Invalid subtitle container"

  • Pluralsight changed the subtitle DOM structure
  • Check console for clues about new selectors
  • Pluralsight player update may be needed

Performance Issues

  • Too many API calls? Cache is working - check chrome://extensions and click "Details" → "Inspect Views" → Service Worker
  • Subtitle detection slow? Browser performance - close other tabs or reduce cache size
  • Video freezing? API response slow - try a different API provider

🔄 Update Selectors for Pluralsight Changes

If Pluralsight updates their video player and subtitles aren't detected:

  1. Open the Pluralsight video
  2. Right-click → Inspect → Elements tab
  3. Locate the subtitle text in the DOM
  4. Find the parent container class name
  5. Edit content.js line ~104 to add the new selector:
const selectors = [
  '.player-subtitles span',
  '[class*="subtitle"] span',
  '.your-new-selector span',  // Add here
  // ...
];

📚 Learning Resources

🎨 Customization

Change Translation Styling

Edit content.js around line 180:

translationElement.style.cssText = `
  color: #FFD700;           // Change color (yellow)
  font-size: inherit;       // Font size
  font-style: italic;       // Make it italic
  opacity: 0.95;           // Transparency
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.8); // Shadow
`;

Change Cache Size Limit

Currently unlimited. To limit cache, edit content.js:

if (translationCache.size > 1000) {
  // Delete oldest entries or clear all
  translationCache.clear();
}

📄 License

This project is provided as-is for educational purposes. Respect API provider terms of service when using OpenAI or Google Gemini.

🤝 Contributing

To improve this extension:

  1. Test with various Pluralsight courses
  2. Report selector issues if subtitles aren't detected
  3. Suggest language additions or styling improvements
  4. Test with both OpenAI and Gemini APIs

⚠️ Important Notes

  1. API Costs: Every subtitle translation costs money (OpenAI/Gemini). Monitor your API usage.
  2. Internet Required: Extension needs internet for API calls
  3. Pluralsight Only: Currently designed for Pluralsight.com; may not work elsewhere
  4. Rate Limiting: APIs may rate-limit you if translating too many subtitles quickly

🚀 Future Enhancements

  • Hotkey to toggle translation on/off
  • Custom prompt engineering UI
  • Translation history log
  • Multiple subtitle track support
  • Offline translation (local models)
  • Dark mode for popup
  • Statistics dashboard (translations done, API costs)

Happy Learning with Bilingual Translations! 🌍

Stashed changes

About

A powerful Chrome Extension (Manifest V3) that translates English subtitles on Pluralsight.com to Vietnamese (or other languages) in real-time using LLM APIs like OpenAI GPT or Google Gemini.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors