karthikeya1212 commited on
Commit
c5fb75b
·
verified ·
1 Parent(s): 10e7ad9

Update api/server.py

Browse files
Files changed (1) hide show
  1. api/server.py +20 -208
api/server.py CHANGED
@@ -1,157 +1,12 @@
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
- # -------------------------------
146
- logging.basicConfig(
147
- level=logging.INFO,
148
- format="%(asctime)s [%(levelname)s] %(message)s"
149
- )
150
 
151
- # -------------------------------
152
- # FastAPI app
153
- # -------------------------------
154
- app = FastAPI(title="AI ADD Generator Server", version="1.0")
155
 
156
  app.add_middleware(
157
  CORSMiddleware,
@@ -161,9 +16,9 @@ app.add_middleware(
161
  allow_headers=["*"],
162
  )
163
 
164
- # -------------------------------
165
  # Pydantic models
166
- # -------------------------------
167
  class IdeaRequest(BaseModel):
168
  idea: str
169
 
@@ -171,75 +26,32 @@ class ConfirmationRequest(BaseModel):
171
  task_id: str
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 {
191
- "status": "submitted",
192
- "task_id": task_id,
193
- "message": "Idea received. Script will be generated shortly.",
194
- }
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:
201
- raise HTTPException(status_code=404, detail="Task not found.")
202
-
203
  if task["status"] != queue_manager.TaskStatus.WAITING_CONFIRMATION:
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
215
- return {"status": "rejected", "task_id": task_id}
216
 
 
 
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
-
227
  return task
228
 
229
-
230
  @app.get("/")
231
- async def health_check():
232
- return {"status": "running", "message": "AI ADD Generator is live."}
233
-
234
-
235
- # -------------------------------
236
- # Startup / Shutdown events
237
- # -------------------------------
238
- @app.on_event("startup")
239
- async def startup_event():
240
- logging.info("🚀 Server starting up...")
241
- queue_manager.start_worker()
242
-
243
- @app.on_event("shutdown")
244
- async def shutdown_event():
245
- logging.info("🛑 Server shutting down...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import logging
2
+ from fastapi import FastAPI, HTTPException
3
  from fastapi.middleware.cors import CORSMiddleware
4
+ from pydantic import BaseModel
5
+ from services import queue_manager
6
 
7
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
 
 
 
 
 
 
8
 
9
+ app = FastAPI(title="AI ADD Generator", version="1.0")
 
 
 
10
 
11
  app.add_middleware(
12
  CORSMiddleware,
 
16
  allow_headers=["*"],
17
  )
18
 
19
+ # ---------------------------
20
  # Pydantic models
21
+ # ---------------------------
22
  class IdeaRequest(BaseModel):
23
  idea: str
24
 
 
26
  task_id: str
27
  confirm: bool
28
 
29
+ # ---------------------------
30
+ # API endpoints
31
+ # ---------------------------
 
 
 
 
 
32
  @app.post("/submit_idea")
33
  async def submit_idea(request: IdeaRequest):
34
  task_id = await queue_manager.add_task(request.idea)
35
+ return {"status": "submitted", "task_id": task_id}
 
 
 
 
 
 
 
 
 
36
 
37
  @app.post("/confirm")
38
  async def confirm_task(request: ConfirmationRequest):
39
+ task = queue_manager.get_task_status(request.task_id)
 
40
  if not task:
41
+ raise HTTPException(status_code=404, detail="Task not found")
 
42
  if task["status"] != queue_manager.TaskStatus.WAITING_CONFIRMATION:
43
+ raise HTTPException(status_code=400, detail="Task not waiting for confirmation")
 
 
 
 
 
 
 
 
 
 
 
44
 
45
+ await queue_manager.confirm_task(request.task_id)
46
+ return {"status": "confirmed", "task": task}
47
 
48
  @app.get("/status/{task_id}")
49
+ async def status(task_id: str):
50
  task = queue_manager.get_task_status(task_id)
51
  if not task:
52
+ raise HTTPException(status_code=404, detail="Task not found")
 
 
 
 
53
  return task
54
 
 
55
  @app.get("/")
56
+ async def health():
57
+ return {"status": "running"}