chatbott / app /routes /translate.py
MuhammadSaad16's picture
Upload 111 files
807b59f verified
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from sqlalchemy.exc import IntegrityError
from app.database import get_db
from app.models.translation import Translation
from app.schemas.translate import TranslateRequest, TranslateResponse
from app.services.openai_service import OpenAIService
import logging
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api", tags=["translation"])
@router.post("/translate/urdu", response_model=TranslateResponse)
async def translate_to_urdu(
request: TranslateRequest,
db: Session = Depends(get_db)
):
"""
Translate English text to Urdu.
- Checks cache first for existing translation
- If not cached, calls Gemini for translation
- Stores new translations in database for future requests
"""
# T007: Check cache first
cached = db.query(Translation).filter_by(cache_key=request.cache_key).first()
if cached:
return TranslateResponse(urdu_text=cached.urdu_text, cached=True)
# Perform translation via OpenAI SDK + Gemini
try:
openai_service = OpenAIService()
urdu_text = await openai_service.translate_to_urdu(request.content)
except Exception as e:
logger.error(f"Gemini translation error: {e}")
raise HTTPException(status_code=503, detail="Translation service temporarily unavailable")
# T008 & T009: Store in cache with race condition handling
try:
translation = Translation(
cache_key=request.cache_key,
english_text=request.content,
urdu_text=urdu_text
)
db.add(translation)
db.commit()
except IntegrityError:
db.rollback()
# Race condition - another request cached this key
cached = db.query(Translation).filter_by(cache_key=request.cache_key).first()
if cached:
return TranslateResponse(urdu_text=cached.urdu_text, cached=True)
except Exception as e:
logger.error(f"Database error: {e}")
# Return translation even if caching fails
return TranslateResponse(urdu_text=urdu_text, cached=False)
return TranslateResponse(urdu_text=urdu_text, cached=False)