7.7 KiB
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
- Article Editor: Translation component in the edit form
- Article List: Quick translation buttons in the admin list
- 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)
// 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)
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
<BlogTranslator
title={editing.title}
content={editing.content}
onTranslationComplete={(translatedTitle, translatedContent) => {
setEditing(prev => ({
...prev,
title: translatedTitle,
content: translatedContent,
slug: makeSlug(translatedTitle),
}));
}}
/>
2. Quick Translation in List
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
{
"q": "Text to translate",
"source": "cs",
"target": "en",
"format": "text", // or "html"
"alternatives": 0
}
Response Format
{
"translatedText": "Translated text",
"alternatives": ["Alternative 1", "Alternative 2"]
}
Configuration
Environment Variables
# 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
- Write Original Content: Create article in Czech or English
- Auto-Detect Language: System detects source language automatically
- Click Translate: Press the translation button in the editor
- Process Translation: API translates title and content
- Update Form: Form fields are updated with translated content
- Save Article: Save to database with translated content
Quick Translation from List
- Find Article: Locate article in admin list
- Click Globe Icon: Press the translation button
- Auto-Translate: System detects and translates to opposite language
- Save to DB: Article is automatically updated in database
- 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
- Multiple Language Support: Extend beyond Czech/English
- Translation History: Track translation versions
- Batch Translation: Translate multiple articles at once
- Translation Quality: Alternative translation providers
- SEO Optimization: Hreflang tags for translated content
Integration Opportunities
- Auto-Translation: Automatic translation for new articles
- Translation API: Public translation endpoint
- Translation Analytics: Track translation usage
- 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.