
- Updated OpenAI package from 1.3.7 to 1.51.0 for latest API compatibility
- Added PyTorch and torchaudio dependencies for Whisper model support
- Fixed OpenAI API calls to use new AsyncOpenAI client format
- Updated transcription service to use client.audio.transcriptions.create()
- Updated translation service to use client.chat.completions.create()
- Added proper logging to language detection service
- Added environment variable loading with python-dotenv in main.py
- Fixed import order to comply with linting standards
🤖 Generated with BackendIM
Co-Authored-By: Claude <noreply@anthropic.com>
69 lines
2.3 KiB
Python
69 lines
2.3 KiB
Python
import os
|
|
from openai import AsyncOpenAI
|
|
from typing import Optional
|
|
import logging
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
|
|
|
if not OPENAI_API_KEY:
|
|
logger.warning("OpenAI API key not configured")
|
|
|
|
client = AsyncOpenAI(api_key=OPENAI_API_KEY) if OPENAI_API_KEY else None
|
|
|
|
|
|
async def translate_text(text: str, target_language: str, source_language: str = "auto") -> Optional[str]:
|
|
if not client:
|
|
logger.error("OpenAI API key not configured")
|
|
return None
|
|
|
|
try:
|
|
# Language mapping for better prompts
|
|
language_names = {
|
|
"en": "English",
|
|
"es": "Spanish",
|
|
"fr": "French",
|
|
"de": "German",
|
|
"it": "Italian",
|
|
"pt": "Portuguese",
|
|
"ru": "Russian",
|
|
"ja": "Japanese",
|
|
"ko": "Korean",
|
|
"zh": "Chinese",
|
|
"ar": "Arabic",
|
|
"hi": "Hindi"
|
|
}
|
|
|
|
target_lang_name = language_names.get(target_language, target_language)
|
|
source_lang_name = language_names.get(source_language, source_language)
|
|
|
|
# Create translation prompt
|
|
if source_language == "auto":
|
|
prompt = f"Translate the following text to {target_lang_name}. Maintain the original tone and meaning:\n\n{text}"
|
|
else:
|
|
prompt = f"Translate the following text from {source_lang_name} to {target_lang_name}. Maintain the original tone and meaning:\n\n{text}"
|
|
|
|
# Use GPT-4 for translation
|
|
response = await client.chat.completions.create(
|
|
model="gpt-4",
|
|
messages=[
|
|
{
|
|
"role": "system",
|
|
"content": "You are a professional translator. Provide accurate translations while maintaining the original tone and context. Return only the translated text without any additional commentary."
|
|
},
|
|
{
|
|
"role": "user",
|
|
"content": prompt
|
|
}
|
|
],
|
|
max_tokens=2000,
|
|
temperature=0.3
|
|
)
|
|
|
|
translated_text = response.choices[0].message.content.strip()
|
|
return translated_text
|
|
|
|
except Exception as e:
|
|
logger.error(f"Error translating text: {e}")
|
|
return None |