karthikeya1212 commited on
Commit
4a5d5fa
·
verified ·
1 Parent(s): ce2e62e

Update api/server.py

Browse files
Files changed (1) hide show
  1. api/server.py +126 -403
api/server.py CHANGED
@@ -1,403 +1,126 @@
1
- # # api/server.py
2
- # from fastapi import FastAPI, HTTPException
3
- # from pydantic import BaseModel
4
- # import asyncio
5
- # from pipeline.pipeline_runner import run_pipeline_task
6
-
7
- # app = FastAPI(title="AI ADD Maker API", version="1.0")
8
-
9
- # # Request body schema
10
- # class GenerateRequest(BaseModel):
11
- # idea: str
12
-
13
- # # Response schema (optional, for docs clarity)
14
- # class GenerateResponse(BaseModel):
15
- # task_id: str
16
- # scenes: list
17
- # images: list
18
- # video: dict
19
- # music: dict
20
- # final_output: dict
21
-
22
- # @app.post("/generate", response_model=GenerateResponse)
23
- # async def generate_video(request: GenerateRequest):
24
- # """
25
- # Trigger the AI Ad/Video pipeline with a product or idea description.
26
- # Returns all intermediate and final outputs.
27
- # """
28
- # idea = request.idea.strip()
29
- # if not idea:
30
- # raise HTTPException(status_code=400, detail="Idea cannot be empty.")
31
-
32
- # try:
33
- # # Run the pipeline asynchronously
34
- # result = await run_pipeline_task(idea)
35
- # return result
36
- # except Exception as e:
37
- # raise HTTPException(status_code=500, detail=f"Pipeline failed: {str(e)}")
38
-
39
- # # Optional health check endpoint
40
- # @app.get("/health")
41
- # async def health_check():
42
- # return {"status": "ok"}
43
-
44
-
45
-
46
-
47
-
48
- # # server.py
49
- # import uuid
50
- # import asyncio
51
- # from fastapi import FastAPI, HTTPException
52
- # from pydantic import BaseModel
53
- # from queue import QueueManager # your queue.py module
54
- # import logging
55
-
56
- # # -------------------------------
57
- # # Setup logging
58
- # # -------------------------------
59
- # logging.basicConfig(
60
- # level=logging.INFO,
61
- # format="%(asctime)s [%(levelname)s] %(message)s"
62
- # )
63
-
64
- # # -------------------------------
65
- # # FastAPI app
66
- # # -------------------------------
67
- # app = FastAPI(title="ADD Maker Server", version="1.0")
68
-
69
- # # -------------------------------
70
- # # Pydantic models
71
- # # -------------------------------
72
- # class IdeaRequest(BaseModel):
73
- # idea: str
74
-
75
- # class ConfirmationRequest(BaseModel):
76
- # task_id: str
77
- # confirm: bool
78
-
79
- # # -------------------------------
80
- # # Queue Manager Instance
81
- # # -------------------------------
82
- # queue_manager = QueueManager()
83
-
84
- # # In-memory task storage for confirmation
85
- # pending_confirmations = {} # task_id -> asyncio.Event
86
-
87
- # # -------------------------------
88
- # # Helper function for confirmation
89
- # # -------------------------------
90
- # async def wait_for_confirmation(task_id: str, timeout: int = 120):
91
- # """Wait for user confirmation or auto-confirm after timeout."""
92
- # event = asyncio.Event()
93
- # pending_confirmations[task_id] = event
94
- # try:
95
- # await asyncio.wait_for(event.wait(), timeout=timeout)
96
- # logging.info(f"Task {task_id} confirmed by user.")
97
- # return True
98
- # except asyncio.TimeoutError:
99
- # logging.info(f"Task {task_id} auto-confirmed after {timeout} seconds.")
100
- # return True
101
- # finally:
102
- # pending_confirmations.pop(task_id, None)
103
-
104
- # # -------------------------------
105
- # # API Endpoints
106
- # # -------------------------------
107
- # @app.post("/submit_idea")
108
- # async def submit_idea(request: IdeaRequest):
109
- # task_id = str(uuid.uuid4())
110
- # logging.info(f"Received idea: {request.idea} | Task ID: {task_id}")
111
-
112
- # # Push task to queue
113
- # await queue_manager.enqueue({
114
- # "task_id": task_id,
115
- # "idea": request.idea
116
- # })
117
-
118
- # # Start confirmation wait in background
119
- # asyncio.create_task(wait_for_confirmation(task_id))
120
-
121
- # return {"status": "submitted", "task_id": task_id, "message": "Idea received, waiting for confirmation."}
122
-
123
- # @app.post("/confirm")
124
- # async def confirm_task(request: ConfirmationRequest):
125
- # task_id = request.task_id
126
- # if task_id not in pending_confirmations:
127
- # raise HTTPException(status_code=404, detail="Task not pending confirmation or already confirmed.")
128
-
129
- # if request.confirm:
130
- # pending_confirmations[task_id].set()
131
- # return {"status": "confirmed", "task_id": task_id}
132
- # else:
133
- # return {"status": "rejected", "task_id": task_id}
134
-
135
- # @app.get("/")
136
- # async def health_check():
137
- # return {"status": "running"}
138
-
139
- # # -------------------------------
140
- # # Startup / Shutdown events
141
- # # -------------------------------
142
- # @app.on_event("startup")
143
- # async def startup_event():
144
- # logging.info("Server starting up...")
145
-
146
- # @app.on_event("shutdown")
147
- # async def shutdown_event():
148
- # logging.info("Server shutting down...")
149
-
150
-
151
-
152
- # # best
153
- # # server.py
154
- # import uuid
155
- # import asyncio
156
- # from fastapi import FastAPI, HTTPException
157
- # from pydantic import BaseModel
158
- # from services import queue_manager as queue_manager # ✅ import your actual queue module
159
- # import logging
160
- # from fastapi.middleware.cors import CORSMiddleware
161
-
162
-
163
- # # -------------------------------
164
- # # Setup logging
165
- # # -------------------------------
166
- # logging.basicConfig(
167
- # level=logging.INFO,
168
- # format="%(asctime)s [%(levelname)s] %(message)s"
169
- # )
170
-
171
- # # -------------------------------
172
- # # FastAPI app
173
- # # -------------------------------
174
- # app = FastAPI(title="AI ADD Generator Server", version="1.0")
175
- # # Enable CORS for local testing
176
- # app.add_middleware(
177
- # CORSMiddleware,
178
- # allow_origins=["*"], # Allow requests from anywhere (for testing)
179
- # allow_credentials=True,
180
- # allow_methods=["*"], # Allow all HTTP methods
181
- # allow_headers=["*"], # Allow all headers
182
- # )
183
-
184
- # # -------------------------------
185
- # # Pydantic models
186
- # # -------------------------------
187
- # class IdeaRequest(BaseModel):
188
- # idea: str
189
-
190
- # class ConfirmationRequest(BaseModel):
191
- # task_id: str
192
- # confirm: bool
193
-
194
- # # -------------------------------
195
- # # In-memory confirmation tracker
196
- # # -------------------------------
197
- # pending_confirmations = {} # task_id -> asyncio.Event
198
-
199
- # # -------------------------------
200
- # # Helper function for confirmation
201
- # # -------------------------------
202
- # async def wait_for_confirmation(task_id: str, timeout: int = 120):
203
- # """Wait for user confirmation or auto-confirm after timeout."""
204
- # event = asyncio.Event()
205
- # pending_confirmations[task_id] = event
206
- # try:
207
- # await asyncio.wait_for(event.wait(), timeout=timeout)
208
- # logging.info(f"✅ Task {task_id} confirmed by user.")
209
- # await queue_manager.confirm_task(task_id)
210
- # return True
211
- # except asyncio.TimeoutError:
212
- # logging.info(f"⌛ Task {task_id} auto-confirmed after {timeout}s.")
213
- # await queue_manager.confirm_task(task_id)
214
- # return True
215
- # finally:
216
- # pending_confirmations.pop(task_id, None)
217
-
218
- # # -------------------------------
219
- # # API Endpoints
220
- # # -------------------------------
221
-
222
- # @app.post("/submit_idea")
223
- # async def submit_idea(request: IdeaRequest):
224
- # """Receives a new ad idea and enqueues it."""
225
- # task_id = await queue_manager.add_task(request.idea)
226
- # logging.info(f"💡 New idea received | Task ID: {task_id}")
227
-
228
- # # Start confirmation listener
229
- # asyncio.create_task(wait_for_confirmation(task_id))
230
-
231
- # return {
232
- # "status": "submitted",
233
- # "task_id": task_id,
234
- # "message": "Idea received. Waiting for user confirmation after script generation."
235
- # }
236
-
237
-
238
- # @app.post("/confirm")
239
- # async def confirm_task(request: ConfirmationRequest):
240
- # """Confirms a paused task and continues the pipeline."""
241
- # task_id = request.task_id
242
- # if task_id not in pending_confirmations:
243
- # raise HTTPException(status_code=404, detail="Task not pending confirmation or already confirmed.")
244
-
245
- # if request.confirm:
246
- # pending_confirmations[task_id].set()
247
- # return {"status": "confirmed", "task_id": task_id}
248
- # else:
249
- # return {"status": "rejected", "task_id": task_id}
250
-
251
-
252
- # @app.get("/status/{task_id}")
253
- # async def get_status(task_id: str):
254
- # """Check the current status of a task."""
255
- # status = queue_manager.get_task_status(task_id)
256
- # if not status:
257
- # raise HTTPException(status_code=404, detail="Task not found.")
258
- # return status
259
-
260
-
261
- # @app.get("/")
262
- # async def health_check():
263
- # return {"status": "running", "message": "AI ADD Generator is live."}
264
-
265
-
266
- # # -------------------------------
267
- # # Startup / Shutdown events
268
- # # -------------------------------
269
- # @app.on_event("startup")
270
- # async def startup_event():
271
- # logging.info("🚀 Server starting up...")
272
- # queue_manager.start_worker() # ✅ Start async worker loop
273
-
274
- # @app.on_event("shutdown")
275
- # async def shutdown_event():
276
- # logging.info("🛑 Server shutting down...")
277
-
278
-
279
-
280
- import uuid
281
- import asyncio
282
- from fastapi import FastAPI, HTTPException
283
- from pydantic import BaseModel
284
- from services import queue_manager # ✅ import your actual queue module
285
- import logging
286
- from fastapi.middleware.cors import CORSMiddleware
287
-
288
- # -------------------------------
289
- # Setup logging
290
- # -------------------------------
291
- logging.basicConfig(
292
- level=logging.INFO,
293
- format="%(asctime)s [%(levelname)s] %(message)s"
294
- )
295
-
296
- # -------------------------------
297
- # FastAPI app
298
- # -------------------------------
299
- app = FastAPI(title="AI ADD Generator Server", version="1.0")
300
-
301
- # Enable CORS for local testing
302
- app.add_middleware(
303
- CORSMiddleware,
304
- allow_origins=["*"],
305
- allow_credentials=True,
306
- allow_methods=["*"],
307
- allow_headers=["*"],
308
- )
309
-
310
- # -------------------------------
311
- # Pydantic models
312
- # -------------------------------
313
- class IdeaRequest(BaseModel):
314
- idea: str
315
-
316
- class ConfirmationRequest(BaseModel):
317
- task_id: str
318
- confirm: bool
319
-
320
- # -------------------------------
321
- # In-memory confirmation tracker
322
- # -------------------------------
323
- pending_confirmations = {} # task_id -> asyncio.Event
324
- script_results = {} # task_id -> generated script for confirmation
325
-
326
- # -------------------------------
327
- # API Endpoints
328
- # -------------------------------
329
- @app.post("/submit_idea")
330
- async def submit_idea(request: IdeaRequest):
331
- """Receives a new ad idea and enqueues it."""
332
- task_id = await queue_manager.add_task(request.idea)
333
- logging.info(f"💡 New idea received | Task ID: {task_id}")
334
-
335
- # Start worker listener
336
- asyncio.create_task(queue_manager.wait_for_script(task_id, script_results))
337
-
338
- return {
339
- "status": "submitted",
340
- "task_id": task_id,
341
- "message": "Idea received. Script will be generated shortly.",
342
- }
343
-
344
- @app.post("/confirm")
345
- async def confirm_task(request: ConfirmationRequest):
346
- """Confirms a paused task, generates story, and returns full JSON."""
347
- task_id = request.task_id
348
- task = queue_manager.get_task_status(task_id)
349
- if not task:
350
- raise HTTPException(status_code=404, detail="Task not found.")
351
-
352
- if task["status"] != queue_manager.TaskStatus.WAITING_CONFIRMATION:
353
- raise HTTPException(status_code=400, detail="Task not waiting for confirmation.")
354
-
355
- if request.confirm:
356
- # Confirm task
357
- await queue_manager.confirm_task(task_id)
358
- logging.info(f"✅ Task {task_id} confirmed by user.")
359
-
360
- # Generate story immediately
361
- script_result = task["result"]["script"]
362
- story_result = await queue_manager.generate_story_after_confirm(script_result)
363
- task["result"]["story_script"] = story_result
364
- task["status"] = queue_manager.TaskStatus.COMPLETED
365
-
366
- logging.info(f"🎬 Task {task_id} story generated and task completed.")
367
- return {"status": "completed", "task": task}
368
-
369
- else:
370
- task["status"] = queue_manager.TaskStatus.FAILED
371
- return {"status": "rejected", "task_id": task_id}
372
-
373
-
374
- @app.get("/status/{task_id}")
375
- async def get_status(task_id: str):
376
- """Check the current status of a task."""
377
- task = queue_manager.get_task_status(task_id)
378
- if not task:
379
- raise HTTPException(status_code=404, detail="Task not found.")
380
-
381
- # If waiting confirmation, return script only
382
- if task["status"] == queue_manager.TaskStatus.WAITING_CONFIRMATION:
383
- return {"status": task["status"], "script": task["result"]["script"]}
384
-
385
- return task
386
-
387
-
388
- @app.get("/")
389
- async def health_check():
390
- return {"status": "running", "message": "AI ADD Generator is live."}
391
-
392
-
393
- # -------------------------------
394
- # Startup / Shutdown events
395
- # -------------------------------
396
- @app.on_event("startup")
397
- async def startup_event():
398
- logging.info("🚀 Server starting up...")
399
- queue_manager.start_worker()
400
-
401
- @app.on_event("shutdown")
402
- async def shutdown_event():
403
- logging.info("🛑 Server shutting down...")
 
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 # import your actual queue module
8
+ import logging
9
+ from fastapi.middleware.cors import CORSMiddleware
10
+
11
+ # -------------------------------
12
+ # Setup logging
13
+ # -------------------------------
14
+ logging.basicConfig(
15
+ level=logging.INFO,
16
+ format="%(asctime)s [%(levelname)s] %(message)s"
17
+ )
18
+
19
+ # -------------------------------
20
+ # FastAPI app
21
+ # -------------------------------
22
+ app = FastAPI(title="AI ADD Generator Server", version="1.0")
23
+
24
+ # Enable CORS for local testing
25
+ app.add_middleware(
26
+ CORSMiddleware,
27
+ allow_origins=["*"],
28
+ allow_credentials=True,
29
+ allow_methods=["*"],
30
+ allow_headers=["*"],
31
+ )
32
+
33
+ # -------------------------------
34
+ # Pydantic models
35
+ # -------------------------------
36
+ class IdeaRequest(BaseModel):
37
+ idea: str
38
+
39
+ class ConfirmationRequest(BaseModel):
40
+ task_id: str
41
+ confirm: bool
42
+
43
+ # -------------------------------
44
+ # In-memory confirmation tracker
45
+ # -------------------------------
46
+ pending_confirmations = {} # task_id -> asyncio.Event
47
+ script_results = {} # task_id -> generated script for confirmation
48
+
49
+ # -------------------------------
50
+ # API Endpoints
51
+ # -------------------------------
52
+ @app.post("/submit_idea")
53
+ async def submit_idea(request: IdeaRequest):
54
+ """Receives a new ad idea and enqueues it."""
55
+ task_id = await queue_manager.add_task(request.idea)
56
+ logging.info(f"💡 New idea received | Task ID: {task_id}")
57
+
58
+ # Start worker listener
59
+ asyncio.create_task(queue_manager.wait_for_script(task_id, script_results))
60
+
61
+ return {
62
+ "status": "submitted",
63
+ "task_id": task_id,
64
+ "message": "Idea received. Script will be generated shortly.",
65
+ }
66
+
67
+ @app.post("/confirm")
68
+ async def confirm_task(request: ConfirmationRequest):
69
+ """Confirms a paused task, generates story, and returns full JSON."""
70
+ task_id = request.task_id
71
+ task = queue_manager.get_task_status(task_id)
72
+ if not task:
73
+ raise HTTPException(status_code=404, detail="Task not found.")
74
+
75
+ if task["status"] != queue_manager.TaskStatus.WAITING_CONFIRMATION:
76
+ raise HTTPException(status_code=400, detail="Task not waiting for confirmation.")
77
+
78
+ if request.confirm:
79
+ # Confirm task
80
+ await queue_manager.confirm_task(task_id)
81
+ logging.info(f"✅ Task {task_id} confirmed by user.")
82
+
83
+ # Generate story immediately
84
+ script_result = task["result"]["script"]
85
+ story_result = await queue_manager.generate_story_after_confirm(script_result)
86
+ task["result"]["story_script"] = story_result
87
+ task["status"] = queue_manager.TaskStatus.COMPLETED
88
+
89
+ logging.info(f"🎬 Task {task_id} story generated and task completed.")
90
+ return {"status": "completed", "task": task}
91
+
92
+ else:
93
+ task["status"] = queue_manager.TaskStatus.FAILED
94
+ return {"status": "rejected", "task_id": task_id}
95
+
96
+
97
+ @app.get("/status/{task_id}")
98
+ async def get_status(task_id: str):
99
+ """Check the current status of a task."""
100
+ task = queue_manager.get_task_status(task_id)
101
+ if not task:
102
+ raise HTTPException(status_code=404, detail="Task not found.")
103
+
104
+ # If waiting confirmation, return script only
105
+ if task["status"] == queue_manager.TaskStatus.WAITING_CONFIRMATION:
106
+ return {"status": task["status"], "script": task["result"]["script"]}
107
+
108
+ return task
109
+
110
+
111
+ @app.get("/")
112
+ async def health_check():
113
+ return {"status": "running", "message": "AI ADD Generator is live."}
114
+
115
+
116
+ # -------------------------------
117
+ # Startup / Shutdown events
118
+ # -------------------------------
119
+ @app.on_event("startup")
120
+ async def startup_event():
121
+ logging.info("🚀 Server starting up...")
122
+ queue_manager.start_worker()
123
+
124
+ @app.on_event("shutdown")
125
+ async def shutdown_event():
126
+ logging.info("🛑 Server shutting down...")