Spaces:
Sleeping
Sleeping
Update api/server.py
Browse files- api/server.py +140 -26
api/server.py
CHANGED
|
@@ -1,15 +1,145 @@
|
|
| 1 |
|
| 2 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
import uuid
|
| 4 |
import asyncio
|
| 5 |
-
from fastapi import FastAPI, HTTPException
|
| 6 |
from pydantic import BaseModel
|
| 7 |
-
from services import queue_manager #
|
| 8 |
import logging
|
| 9 |
from fastapi.middleware.cors import CORSMiddleware
|
| 10 |
|
| 11 |
-
|
| 12 |
-
router = APIRouter()
|
| 13 |
# -------------------------------
|
| 14 |
# Setup logging
|
| 15 |
# -------------------------------
|
|
@@ -23,7 +153,6 @@ logging.basicConfig(
|
|
| 23 |
# -------------------------------
|
| 24 |
app = FastAPI(title="AI ADD Generator Server", version="1.0")
|
| 25 |
|
| 26 |
-
# Enable CORS for local testing
|
| 27 |
app.add_middleware(
|
| 28 |
CORSMiddleware,
|
| 29 |
allow_origins=["*"],
|
|
@@ -43,21 +172,19 @@ class ConfirmationRequest(BaseModel):
|
|
| 43 |
confirm: bool
|
| 44 |
|
| 45 |
# -------------------------------
|
| 46 |
-
# In-memory
|
| 47 |
# -------------------------------
|
| 48 |
-
|
| 49 |
-
script_results = {} # task_id -> generated script for confirmation
|
| 50 |
|
| 51 |
# -------------------------------
|
| 52 |
# API Endpoints
|
| 53 |
# -------------------------------
|
| 54 |
@app.post("/submit_idea")
|
| 55 |
async def submit_idea(request: IdeaRequest):
|
| 56 |
-
"""Receives a new ad idea and enqueues it."""
|
| 57 |
task_id = await queue_manager.add_task(request.idea)
|
| 58 |
logging.info(f"π‘ New idea received | Task ID: {task_id}")
|
| 59 |
|
| 60 |
-
# Start worker
|
| 61 |
asyncio.create_task(queue_manager.wait_for_script(task_id, script_results))
|
| 62 |
|
| 63 |
return {
|
|
@@ -68,7 +195,6 @@ async def submit_idea(request: IdeaRequest):
|
|
| 68 |
|
| 69 |
@app.post("/confirm")
|
| 70 |
async def confirm_task(request: ConfirmationRequest):
|
| 71 |
-
"""Confirms a paused task, generates story, and returns full JSON."""
|
| 72 |
task_id = request.task_id
|
| 73 |
task = queue_manager.get_task_status(task_id)
|
| 74 |
if not task:
|
|
@@ -78,18 +204,11 @@ async def confirm_task(request: ConfirmationRequest):
|
|
| 78 |
raise HTTPException(status_code=400, detail="Task not waiting for confirmation.")
|
| 79 |
|
| 80 |
if request.confirm:
|
| 81 |
-
# Confirm task
|
| 82 |
await queue_manager.confirm_task(task_id)
|
| 83 |
-
logging.info(f"β
Task {task_id} confirmed by user.")
|
| 84 |
-
|
| 85 |
-
# Generate story immediately
|
| 86 |
-
script_result = task["result"]["script"]
|
| 87 |
-
story_result = await queue_manager.generate_story_after_confirm(script_result)
|
| 88 |
-
task["result"]["story_script"] = story_result
|
| 89 |
-
task["status"] = queue_manager.TaskStatus.COMPLETED
|
| 90 |
|
| 91 |
-
|
| 92 |
-
return {"status": "completed", "task": task}
|
| 93 |
|
| 94 |
else:
|
| 95 |
task["status"] = queue_manager.TaskStatus.FAILED
|
|
@@ -98,12 +217,10 @@ async def confirm_task(request: ConfirmationRequest):
|
|
| 98 |
|
| 99 |
@app.get("/status/{task_id}")
|
| 100 |
async def get_status(task_id: str):
|
| 101 |
-
"""Check the current status of a task."""
|
| 102 |
task = queue_manager.get_task_status(task_id)
|
| 103 |
if not task:
|
| 104 |
raise HTTPException(status_code=404, detail="Task not found.")
|
| 105 |
|
| 106 |
-
# If waiting confirmation, return script only
|
| 107 |
if task["status"] == queue_manager.TaskStatus.WAITING_CONFIRMATION:
|
| 108 |
return {"status": task["status"], "script": task["result"]["script"]}
|
| 109 |
|
|
@@ -126,6 +243,3 @@ async def startup_event():
|
|
| 126 |
@app.on_event("shutdown")
|
| 127 |
async def shutdown_event():
|
| 128 |
logging.info("π Server shutting down...")
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
app.include_router(router)
|
|
|
|
| 1 |
|
| 2 |
|
| 3 |
+
# import uuid
|
| 4 |
+
# import asyncio
|
| 5 |
+
# from fastapi import FastAPI, HTTPException, APIRouter
|
| 6 |
+
# from pydantic import BaseModel
|
| 7 |
+
# from services import queue_manager # β
import your actual queue module
|
| 8 |
+
# import logging
|
| 9 |
+
# from fastapi.middleware.cors import CORSMiddleware
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# router = APIRouter()
|
| 13 |
+
# # -------------------------------
|
| 14 |
+
# # Setup logging
|
| 15 |
+
# # -------------------------------
|
| 16 |
+
# logging.basicConfig(
|
| 17 |
+
# level=logging.INFO,
|
| 18 |
+
# format="%(asctime)s [%(levelname)s] %(message)s"
|
| 19 |
+
# )
|
| 20 |
+
|
| 21 |
+
# # -------------------------------
|
| 22 |
+
# # FastAPI app
|
| 23 |
+
# # -------------------------------
|
| 24 |
+
# app = FastAPI(title="AI ADD Generator Server", version="1.0")
|
| 25 |
+
|
| 26 |
+
# # Enable CORS for local testing
|
| 27 |
+
# app.add_middleware(
|
| 28 |
+
# CORSMiddleware,
|
| 29 |
+
# allow_origins=["*"],
|
| 30 |
+
# allow_credentials=True,
|
| 31 |
+
# allow_methods=["*"],
|
| 32 |
+
# allow_headers=["*"],
|
| 33 |
+
# )
|
| 34 |
+
|
| 35 |
+
# # -------------------------------
|
| 36 |
+
# # Pydantic models
|
| 37 |
+
# # -------------------------------
|
| 38 |
+
# class IdeaRequest(BaseModel):
|
| 39 |
+
# idea: str
|
| 40 |
+
|
| 41 |
+
# class ConfirmationRequest(BaseModel):
|
| 42 |
+
# task_id: str
|
| 43 |
+
# confirm: bool
|
| 44 |
+
|
| 45 |
+
# # -------------------------------
|
| 46 |
+
# # In-memory confirmation tracker
|
| 47 |
+
# # -------------------------------
|
| 48 |
+
# pending_confirmations = {} # task_id -> asyncio.Event
|
| 49 |
+
# script_results = {} # task_id -> generated script for confirmation
|
| 50 |
+
|
| 51 |
+
# # -------------------------------
|
| 52 |
+
# # API Endpoints
|
| 53 |
+
# # -------------------------------
|
| 54 |
+
# @app.post("/submit_idea")
|
| 55 |
+
# async def submit_idea(request: IdeaRequest):
|
| 56 |
+
# """Receives a new ad idea and enqueues it."""
|
| 57 |
+
# task_id = await queue_manager.add_task(request.idea)
|
| 58 |
+
# logging.info(f"π‘ New idea received | Task ID: {task_id}")
|
| 59 |
+
|
| 60 |
+
# # Start worker listener
|
| 61 |
+
# asyncio.create_task(queue_manager.wait_for_script(task_id, script_results))
|
| 62 |
+
|
| 63 |
+
# return {
|
| 64 |
+
# "status": "submitted",
|
| 65 |
+
# "task_id": task_id,
|
| 66 |
+
# "message": "Idea received. Script will be generated shortly.",
|
| 67 |
+
# }
|
| 68 |
+
|
| 69 |
+
# @app.post("/confirm")
|
| 70 |
+
# async def confirm_task(request: ConfirmationRequest):
|
| 71 |
+
# """Confirms a paused task, generates story, and returns full JSON."""
|
| 72 |
+
# task_id = request.task_id
|
| 73 |
+
# task = queue_manager.get_task_status(task_id)
|
| 74 |
+
# if not task:
|
| 75 |
+
# raise HTTPException(status_code=404, detail="Task not found.")
|
| 76 |
+
|
| 77 |
+
# if task["status"] != queue_manager.TaskStatus.WAITING_CONFIRMATION:
|
| 78 |
+
# raise HTTPException(status_code=400, detail="Task not waiting for confirmation.")
|
| 79 |
+
|
| 80 |
+
# if request.confirm:
|
| 81 |
+
# # Confirm task
|
| 82 |
+
# await queue_manager.confirm_task(task_id)
|
| 83 |
+
# logging.info(f"β
Task {task_id} confirmed by user.")
|
| 84 |
+
|
| 85 |
+
# # Generate story immediately
|
| 86 |
+
# script_result = task["result"]["script"]
|
| 87 |
+
# story_result = await queue_manager.generate_story_after_confirm(script_result)
|
| 88 |
+
# task["result"]["story_script"] = story_result
|
| 89 |
+
# task["status"] = queue_manager.TaskStatus.COMPLETED
|
| 90 |
+
|
| 91 |
+
# logging.info(f"π¬ Task {task_id} story generated and task completed.")
|
| 92 |
+
# return {"status": "completed", "task": task}
|
| 93 |
+
|
| 94 |
+
# else:
|
| 95 |
+
# task["status"] = queue_manager.TaskStatus.FAILED
|
| 96 |
+
# return {"status": "rejected", "task_id": task_id}
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
# @app.get("/status/{task_id}")
|
| 100 |
+
# async def get_status(task_id: str):
|
| 101 |
+
# """Check the current status of a task."""
|
| 102 |
+
# task = queue_manager.get_task_status(task_id)
|
| 103 |
+
# if not task:
|
| 104 |
+
# raise HTTPException(status_code=404, detail="Task not found.")
|
| 105 |
+
|
| 106 |
+
# # If waiting confirmation, return script only
|
| 107 |
+
# if task["status"] == queue_manager.TaskStatus.WAITING_CONFIRMATION:
|
| 108 |
+
# return {"status": task["status"], "script": task["result"]["script"]}
|
| 109 |
+
|
| 110 |
+
# return task
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
# @app.get("/")
|
| 114 |
+
# async def health_check():
|
| 115 |
+
# return {"status": "running", "message": "AI ADD Generator is live."}
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
# # -------------------------------
|
| 119 |
+
# # Startup / Shutdown events
|
| 120 |
+
# # -------------------------------
|
| 121 |
+
# @app.on_event("startup")
|
| 122 |
+
# async def startup_event():
|
| 123 |
+
# logging.info("π Server starting up...")
|
| 124 |
+
# queue_manager.start_worker()
|
| 125 |
+
|
| 126 |
+
# @app.on_event("shutdown")
|
| 127 |
+
# async def shutdown_event():
|
| 128 |
+
# logging.info("π Server shutting down...")
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
# app.include_router(router)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
|
| 135 |
import uuid
|
| 136 |
import asyncio
|
| 137 |
+
from fastapi import FastAPI, HTTPException
|
| 138 |
from pydantic import BaseModel
|
| 139 |
+
from services import queue_manager # your updated queue_manager
|
| 140 |
import logging
|
| 141 |
from fastapi.middleware.cors import CORSMiddleware
|
| 142 |
|
|
|
|
|
|
|
| 143 |
# -------------------------------
|
| 144 |
# Setup logging
|
| 145 |
# -------------------------------
|
|
|
|
| 153 |
# -------------------------------
|
| 154 |
app = FastAPI(title="AI ADD Generator Server", version="1.0")
|
| 155 |
|
|
|
|
| 156 |
app.add_middleware(
|
| 157 |
CORSMiddleware,
|
| 158 |
allow_origins=["*"],
|
|
|
|
| 172 |
confirm: bool
|
| 173 |
|
| 174 |
# -------------------------------
|
| 175 |
+
# In-memory tracker for scripts
|
| 176 |
# -------------------------------
|
| 177 |
+
script_results = {} # task_id -> script string
|
|
|
|
| 178 |
|
| 179 |
# -------------------------------
|
| 180 |
# API Endpoints
|
| 181 |
# -------------------------------
|
| 182 |
@app.post("/submit_idea")
|
| 183 |
async def submit_idea(request: IdeaRequest):
|
|
|
|
| 184 |
task_id = await queue_manager.add_task(request.idea)
|
| 185 |
logging.info(f"π‘ New idea received | Task ID: {task_id}")
|
| 186 |
|
| 187 |
+
# Start worker for this task (generates script first)
|
| 188 |
asyncio.create_task(queue_manager.wait_for_script(task_id, script_results))
|
| 189 |
|
| 190 |
return {
|
|
|
|
| 195 |
|
| 196 |
@app.post("/confirm")
|
| 197 |
async def confirm_task(request: ConfirmationRequest):
|
|
|
|
| 198 |
task_id = request.task_id
|
| 199 |
task = queue_manager.get_task_status(task_id)
|
| 200 |
if not task:
|
|
|
|
| 204 |
raise HTTPException(status_code=400, detail="Task not waiting for confirmation.")
|
| 205 |
|
| 206 |
if request.confirm:
|
| 207 |
+
# β
Confirm the task, resume pipeline
|
| 208 |
await queue_manager.confirm_task(task_id)
|
| 209 |
+
logging.info(f"β
Task {task_id} confirmed by user. Pipeline will continue automatically.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
|
| 211 |
+
return {"status": "confirmed", "message": "Task confirmed. Story, images, and other stages will be generated automatically."}
|
|
|
|
| 212 |
|
| 213 |
else:
|
| 214 |
task["status"] = queue_manager.TaskStatus.FAILED
|
|
|
|
| 217 |
|
| 218 |
@app.get("/status/{task_id}")
|
| 219 |
async def get_status(task_id: str):
|
|
|
|
| 220 |
task = queue_manager.get_task_status(task_id)
|
| 221 |
if not task:
|
| 222 |
raise HTTPException(status_code=404, detail="Task not found.")
|
| 223 |
|
|
|
|
| 224 |
if task["status"] == queue_manager.TaskStatus.WAITING_CONFIRMATION:
|
| 225 |
return {"status": task["status"], "script": task["result"]["script"]}
|
| 226 |
|
|
|
|
| 243 |
@app.on_event("shutdown")
|
| 244 |
async def shutdown_event():
|
| 245 |
logging.info("π Server shutting down...")
|
|
|
|
|
|
|
|
|