Yassine Mhirsi
feat: Add topic-related schemas and API routes for topic management, along with LangChain dependencies in requirements.
2380f6f
raw
history blame
3 kB
"""Topic extraction endpoints"""
from fastapi import APIRouter, HTTPException
from datetime import datetime
import logging
from services.topic_service import topic_service
from models.topic import (
TopicRequest,
TopicResponse,
BatchTopicRequest,
BatchTopicResponse,
)
router = APIRouter()
logger = logging.getLogger(__name__)
@router.post("/extract", response_model=TopicResponse, tags=["Topic Extraction"])
async def extract_topic(request: TopicRequest):
"""
Extract a topic from a given text/argument
- **text**: The input text or argument to extract topic from (5-5000 chars)
Returns the extracted topic description
"""
try:
# Extract topic
topic = topic_service.extract_topic(request.text)
# Build response
response = TopicResponse(
text=request.text,
topic=topic,
timestamp=datetime.now().isoformat()
)
logger.info(f"Topic extracted: {topic[:50]}...")
return response
except ValueError as e:
logger.error(f"Validation error: {str(e)}")
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
logger.error(f"Topic extraction error: {str(e)}")
raise HTTPException(status_code=500, detail=f"Topic extraction failed: {str(e)}")
@router.post("/batch-extract", response_model=BatchTopicResponse, tags=["Topic Extraction"])
async def batch_extract_topics(request: BatchTopicRequest):
"""
Extract topics from multiple texts/arguments
- **texts**: List of texts to extract topics from (max 50)
Returns extracted topics for all texts
"""
try:
# Batch extract topics
topics = topic_service.batch_extract_topics(request.texts)
# Build response
results = []
timestamp = datetime.now().isoformat()
for i, text in enumerate(request.texts):
if topics[i] is not None:
results.append(
TopicResponse(
text=text,
topic=topics[i],
timestamp=timestamp
)
)
else:
# Skip failed extractions or handle as needed
logger.warning(f"Failed to extract topic for text at index {i}")
logger.info(f"Batch topic extraction completed: {len(results)}/{len(request.texts)} successful")
return BatchTopicResponse(
results=results,
total_processed=len(results),
timestamp=timestamp
)
except ValueError as e:
logger.error(f"Validation error: {str(e)}")
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
logger.error(f"Batch topic extraction error: {str(e)}")
raise HTTPException(status_code=500, detail=f"Batch topic extraction failed: {str(e)}")