# Blog Translation System ## Overview The blog translation system provides automatic translation of blog articles between Czech and English using the free `translate.tdvorak.dev` API. The system is fully integrated with the existing blog management interface and saves translated content directly to the database. ## Features ### ✅ **Automatic Translation** - **Smart Language Detection**: Automatically detects Czech vs English content - **Bidirectional Translation**: Czech ↔ English - **HTML Support**: Preserves formatting and structure - **Fast Processing**: Uses optimized API calls ### ✅ **Integration Points** 1. **Article Editor**: Translation component in the edit form 2. **Article List**: Quick translation buttons in the admin list 3. **Database Integration**: Translated content is saved automatically ### ✅ **User Experience** - **One-Click Translation**: Single button translation - **Real-time Feedback**: Loading states and error handling - **Smart Detection**: Only shows translation option when needed - **Automatic Slug Generation**: Updates URL slug for translated titles ## Architecture ### **Frontend Components** #### 1. Translation Service (`/frontend/src/services/translation.ts`) ```typescript // Core translation functions export async function translateText(text, sourceLang, targetLang, options) export async function translateBlogContent(title, content, sourceLang, targetLang) export function detectLanguage(text): 'cs' | 'en' ``` #### 2. React Hook (`/frontend/src/hooks/useBlogTranslation.ts`) ```typescript const { translateBlog, isTranslating, translationError, detectSourceLanguage, getTargetLanguage } = useBlogTranslation(); ``` #### 3. UI Component (`/frontend/src/components/admin/BlogTranslator.tsx`) - Smart translation interface - Language detection display - Error handling and loading states - Integration callbacks ### **Backend Integration** The system uses the existing article management API: - **Create**: `POST /api/v1/admin/articles` - **Update**: `PUT /api/v1/admin/articles/:id` - **Get**: `GET /api/v1/admin/articles` ## Usage Examples ### **1. In Article Editor** ```typescript { setEditing(prev => ({ ...prev, title: translatedTitle, content: translatedContent, slug: makeSlug(translatedTitle), })); }} /> ``` ### **2. Quick Translation in List** ```typescript const handleQuickTranslate = async (article: Article) => { const sourceLang = detectLanguage(article.title + ' ' + article.content); const targetLang = sourceLang === 'cs' ? 'en' : 'cs'; const result = await translateBlogContent( article.title, article.content, sourceLang, targetLang ); await updateArticle(article.id, { title: result.translatedTitle, content: result.translatedContent, slug: makeSlug(result.translatedTitle), }); }; ``` ## API Details ### **Translation API** - **Endpoint**: `https://translate.tdvorak.dev/translate` - **Method**: POST - **Authentication**: None required (free service) - **Format**: JSON ### **Request Format** ```json { "q": "Text to translate", "source": "cs", "target": "en", "format": "text", // or "html" "alternatives": 0 } ``` ### **Response Format** ```json { "translatedText": "Translated text", "alternatives": ["Alternative 1", "Alternative 2"] } ``` ## Configuration ### **Environment Variables** ```env # No configuration required - API is free # Optional: For future API key support # REACT_APP_TRANSLATE_API_KEY=your_key_here ``` ### **Dependencies** - React 18+ - Chakra UI - React Query (for caching) - Existing article management system ## Implementation Steps ### **1. Service Setup** ✅ Translation service created ✅ Language detection implemented ✅ Error handling added ### **2. UI Integration** ✅ BlogTranslator component created ✅ React hook for state management ✅ Integration with ArticlesAdminPage ### **3. Database Integration** ✅ Uses existing article API ✅ Automatic slug generation ✅ Content sanitization with DOMPurify ### **4. User Experience** ✅ Loading states and progress indicators ✅ Error messages and feedback ✅ Smart language detection ✅ Quick translation in article list ## Workflow ### **Creating a Translated Article** 1. **Write Original Content**: Create article in Czech or English 2. **Auto-Detect Language**: System detects source language automatically 3. **Click Translate**: Press the translation button in the editor 4. **Process Translation**: API translates title and content 5. **Update Form**: Form fields are updated with translated content 6. **Save Article**: Save to database with translated content ### **Quick Translation from List** 1. **Find Article**: Locate article in admin list 2. **Click Globe Icon**: Press the translation button 3. **Auto-Translate**: System detects and translates to opposite language 4. **Save to DB**: Article is automatically updated in database 5. **Refresh List**: List refreshes to show translated content ## Error Handling ### **Translation Errors** - Network failures - API unavailable - Invalid content format - Rate limiting (if applicable) ### **User Feedback** - Toast notifications for success/error - Loading indicators during translation - Graceful degradation when API is down ## Performance Considerations ### **Optimizations** - **Language Caching**: Detection results cached - **Request Debouncing**: Prevents duplicate calls - **Error Boundaries**: Isolates translation failures - **Lazy Loading**: Translation component loads on demand ### **Caching Strategy** - React Query for API caching - Local storage for language preferences - Translation result caching for identical content ## Security ### **Content Sanitization** - DOMPurify for HTML content - XSS prevention - Safe slug generation ### **API Security** - No sensitive data sent to translation API - Content-only requests - No authentication tokens exposed ## Future Enhancements ### **Potential Improvements** 1. **Multiple Language Support**: Extend beyond Czech/English 2. **Translation History**: Track translation versions 3. **Batch Translation**: Translate multiple articles at once 4. **Translation Quality**: Alternative translation providers 5. **SEO Optimization**: Hreflang tags for translated content ### **Integration Opportunities** 1. **Auto-Translation**: Automatic translation for new articles 2. **Translation API**: Public translation endpoint 3. **Translation Analytics**: Track translation usage 4. **Content Synchronization**: Sync with translation services ## Troubleshooting ### **Common Issues** #### **Translation Not Working** - Check network connection - Verify API endpoint is accessible - Check browser console for errors #### **Content Not Updating** - Verify form state updates - Check save functionality - Validate content format #### **Language Detection Issues** - Review detection logic - Check content encoding - Verify text preprocessing ### **Debug Tools** - Browser developer tools - Network tab for API calls - React DevTools for state inspection - Toast notifications for user feedback ## Summary The blog translation system provides a seamless, automated way to translate blog content between Czech and English. It integrates directly with the existing content management system, requires no configuration, and offers both in-editor and quick-list translation options. **Key Benefits:** - ✅ Free to use (no API costs) - ✅ Automatic language detection - ✅ Preserves HTML formatting - ✅ Integrated with existing workflow - ✅ Database persistence - ✅ User-friendly interface - ✅ Error handling and feedback The system is production-ready and can be used immediately for translating blog content.