Spaces:
Sleeping
Sleeping
Create routers/ideas.py
Browse files- routers/ideas.py +37 -0
routers/ideas.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# routers/ideas.py
|
| 2 |
+
from fastapi import APIRouter, Depends, HTTPException, status
|
| 3 |
+
from starlette.concurrency import run_in_threadpool
|
| 4 |
+
import models
|
| 5 |
+
import config
|
| 6 |
+
from services import generation, security
|
| 7 |
+
import logging
|
| 8 |
+
|
| 9 |
+
logger = logging.getLogger(__name__)
|
| 10 |
+
router = APIRouter(
|
| 11 |
+
prefix="/ideas",
|
| 12 |
+
tags=["Content Ideas"],
|
| 13 |
+
dependencies=[Depends(security.get_api_key)] # Apply API key security to all routes here
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
@router.post("/", response_model=models.IdeaResponse, status_code=status.HTTP_201_CREATED)
|
| 17 |
+
async def create_content_ideas(request: models.IdeaRequest):
|
| 18 |
+
"""
|
| 19 |
+
Generates content ideas based on a prompt using a text generation model.
|
| 20 |
+
"""
|
| 21 |
+
try:
|
| 22 |
+
logger.info(f"Received idea generation request: prompt='{request.prompt}'")
|
| 23 |
+
# Run the synchronous, CPU/GPU-bound ML model in a thread pool
|
| 24 |
+
ideas = await run_in_threadpool(
|
| 25 |
+
generation.generate_ideas_sync, # Pass the function itself
|
| 26 |
+
prompt=request.prompt, # Pass arguments by name
|
| 27 |
+
max_length=request.max_length,
|
| 28 |
+
num_ideas=request.num_ideas
|
| 29 |
+
)
|
| 30 |
+
logger.info(f"Successfully generated {len(ideas)} idea(s).")
|
| 31 |
+
return models.IdeaResponse(ideas=ideas, model_name=config.TEXT_MODEL_NAME)
|
| 32 |
+
except RuntimeError as e:
|
| 33 |
+
logger.error(f"Model runtime error during idea generation: {e}", exc_info=True)
|
| 34 |
+
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=f"Model inference failed: {e}")
|
| 35 |
+
except Exception as e:
|
| 36 |
+
logger.error(f"Unexpected error during idea generation: {e}", exc_info=True)
|
| 37 |
+
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"An unexpected error occurred: {e}")
|