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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
# # app.py
# import os
# import uuid
# import shutil
# import tempfile
# import asyncio
# from pathlib import Path
# from fastapi import FastAPI, File, UploadFile, Form, HTTPException
# from fastapi.responses import FileResponse, JSONResponse
# from fastapi.middleware.cors import CORSMiddleware

# # local imports
# from task_queue import TaskQueue, TaskStatus
# from core.pipeline import process_image_pipeline  # your real pipeline

# # App config
# APP_NAME = "manim_render_service"
# TMP_ROOT = Path(tempfile.gettempdir()) / APP_NAME
# TASKS_DIR = TMP_ROOT / "tasks"
# OUTPUTS_DIR = TMP_ROOT / "outputs"
# TASKS_DIR.mkdir(parents=True, exist_ok=True)
# OUTPUTS_DIR.mkdir(parents=True, exist_ok=True)

# # instantiate queue (file-backed)
# queue = TaskQueue(base_dir=TMP_ROOT, max_workers=os.cpu_count() or 2)

# app = FastAPI(title="Manim Render Service")
# app.add_middleware(
#     CORSMiddleware,
#     allow_origins=["*"],  # change in prod
#     allow_credentials=True,
#     allow_methods=["*"],
#     allow_headers=["*"],
# )


# @app.on_event("startup")
# async def startup_event():
#     # start background workers (non-blocking)
#     await queue.start(processor=process_image_pipeline)


# @app.on_event("shutdown")
# async def shutdown_event():
#     await queue.stop()


# def _make_task_dir(task_id: str) -> Path:
#     p = TASKS_DIR / task_id
#     p.mkdir(parents=True, exist_ok=True)
#     return p


# def _secure_filename(filename: str) -> str:
#     # Minimal safe filename normalizer
#     return "".join(c for c in filename if c.isalnum() or c in "._-").strip("_")


# @app.post("/render", status_code=202)
# async def submit_render(
#     image: UploadFile = File(...),
#     style: str = Form("fade-in"),
#     quality: str = Form("final"),  # preview or final
# ):
#     # Basic validation
#     if image.content_type.split("/")[0] != "image":
#         raise HTTPException(status_code=400, detail="Uploaded file must be an image.")

#     task_id = uuid.uuid4().hex
#     task_dir = _make_task_dir(task_id)

#     # Save upload to tmp task directory
#     safe_name = _secure_filename(image.filename or f"{task_id}.png")
#     uploaded_path = task_dir / safe_name
#     try:
#         with uploaded_path.open("wb") as f:
#             content = await image.read()
#             # Limit size for safety (example: 25 MB)
#             if len(content) > 25 * 1024 * 1024:
#                 raise HTTPException(status_code=413, detail="File too large (max 25MB).")
#             f.write(content)
#     finally:
#         await image.close()

#     # Compose metadata
#     meta = {
#         "task_id": task_id,
#         "input_image": str(uploaded_path),
#         "style": style,
#         "quality": quality,
#         "task_dir": str(task_dir),
#     }

#     # Enqueue the task
#     queue.enqueue(meta)

#     return JSONResponse({"task_id": task_id, "status": "queued"})


# @app.get("/status/{task_id}")
# async def status(task_id: str):
#     st = queue.get_status(task_id)
#     if st is None:
#         raise HTTPException(status_code=404, detail="Task not found")
#     return JSONResponse({"task_id": task_id, "status": st.name})


# @app.get("/result/{task_id}")
# async def result(task_id: str):
#     info = queue.get_task_info(task_id)
#     if info is None:
#         raise HTTPException(status_code=404, detail="Task not found")

#     status = queue.get_status(task_id)
#     if status != TaskStatus.COMPLETED:
#         return JSONResponse({"task_id": task_id, "status": status.name})

#     output_path = Path(info.get("output_path", ""))
#     if not output_path.exists():
#         raise HTTPException(status_code=404, detail="Output not found on disk")

#     return FileResponse(path=str(output_path), filename=output_path.name, media_type="video/mp4")


# @app.delete("/task/{task_id}")
# async def delete_task(task_id: str):
#     info = queue.get_task_info(task_id)
#     if info:
#         # attempt cleanup
#         task_dir = Path(info.get("task_dir", ""))
#         if task_dir.exists():
#             shutil.rmtree(task_dir, ignore_errors=True)
#         queue.remove_task(task_id)
#         return JSONResponse({"task_id": task_id, "status": "removed"})
#     else:
#         raise HTTPException(status_code=404, detail="Task not found")




# app.py
import os
import uuid
import shutil
import tempfile
import asyncio
from pathlib import Path
from fastapi import FastAPI, File, UploadFile, Form, HTTPException
from fastapi.responses import FileResponse, JSONResponse
from fastapi.middleware.cors import CORSMiddleware
import subprocess
# local imports
from task_queue import TaskQueue, TaskStatus
from core.pipeline import process_image_pipeline  # your real pipeline
from fastapi.responses import FileResponse, JSONResponse, Response
from fastapi.responses import JSONResponse, Response, FileResponse
from fastapi import HTTPException
from pathlib import Path
import base64
import base64
from pathlib import Path
from moviepy.video.io.VideoFileClip import VideoFileClip

# --------------------------------------------------
# Logging Setup
# --------------------------------------------------
import logging

logging.basicConfig(
    level=logging.DEBUG,
    format="πŸŒ€ [%(asctime)s] [%(levelname)s] %(message)s",
    datefmt="%H:%M:%S",
)
logger = logging.getLogger("manim_render_service")

# --------------------------------------------------
# App config
# --------------------------------------------------
APP_NAME = "manim_render_service"
TMP_ROOT = Path("tmp")/ APP_NAME
TASKS_DIR = TMP_ROOT / "tasks"
OUTPUTS_DIR = TMP_ROOT / "outputs"
TASKS_DIR.mkdir(parents=True, exist_ok=True)
OUTPUTS_DIR.mkdir(parents=True, exist_ok=True)

queue = TaskQueue(base_dir=TMP_ROOT, max_workers=os.cpu_count() or 2)

app = FastAPI(title="Manim Render Service")
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# --------------------------------------------------
# Lifecycle Events
# --------------------------------------------------
@app.on_event("startup")
async def startup_event():
    logger.info("πŸš€ Starting up backend...")
    logger.debug(f"Temporary root: {TMP_ROOT}")
    await queue.start(processor=process_image_pipeline)
    logger.info("βœ… Queue system initialized and worker started.")


@app.on_event("shutdown")
async def shutdown_event():
    logger.info("🧹 Shutting down backend...")
    await queue.stop()
    logger.info("πŸ›‘ Queue stopped gracefully.")


# --------------------------------------------------
# Helpers
# --------------------------------------------------
def _make_task_dir(task_id: str) -> Path:
    p = TASKS_DIR / task_id
    p.mkdir(parents=True, exist_ok=True)
    logger.debug(f"πŸ“ Created task directory: {p}")
    return p


def _secure_filename(filename: str) -> str:
    safe = "".join(c for c in filename if c.isalnum() or c in "._-").strip("_")
    logger.debug(f"πŸ”’ Secured filename: {filename} β†’ {safe}")
    return safe


# --------------------------------------------------
# Routes
# --------------------------------------------------
@app.post("/render", status_code=202)
async def submit_render(
    image: UploadFile = File(...),
    style: str = Form("fade-in"),
    quality: str = Form("final"),
):
    logger.info(f"πŸ“¨ Received new render request | style={style}, quality={quality}")
    logger.debug(f"Uploaded file info: {image.filename}, type={image.content_type}")

    if image.content_type.split("/")[0] != "image":
        logger.error("❌ Invalid file type, not an image.")
        raise HTTPException(status_code=400, detail="Uploaded file must be an image.")

    task_id = uuid.uuid4().hex
    task_dir = _make_task_dir(task_id)
    logger.info(f"πŸ†” Generated Task ID: {task_id}")

    safe_name = _secure_filename(image.filename or f"{task_id}.png")
    uploaded_path = task_dir / safe_name
    logger.debug(f"πŸ—‚ Saving upload to {uploaded_path}")

    try:
        with uploaded_path.open("wb") as f:
            content = await image.read()
            logger.debug(f"πŸ“¦ File size: {len(content)/1024:.2f} KB")
            if len(content) > 25 * 1024 * 1024:
                logger.warning("⚠️ Upload too large (>25MB). Rejecting.")
                raise HTTPException(status_code=413, detail="File too large (max 25MB).")
            f.write(content)
    finally:
        await image.close()
        logger.debug("πŸ“ Image file closed after writing.")

    meta = {
        "task_id": task_id,
        "input_image": str(uploaded_path),
        "style": style,
        "quality": quality,
        "task_dir": str(task_dir),
    }

    logger.debug(f"🧾 Task metadata: {meta}")
    queue.enqueue(meta)
    logger.info(f"πŸ“€ Task {task_id} successfully enqueued.")

    return JSONResponse({"task_id": task_id, "status": "queued"})


@app.get("/status/{task_id}")
async def status(task_id: str):
    logger.debug(f"Status check for task: {task_id}")
    st = queue.get_status(task_id)
    if st is None:
        logger.warning(f"Task {task_id} not found")
        raise HTTPException(status_code=404, detail="Task not found")
    
    # Get additional info
    task_info = queue.get_task_info(task_id)
    logger.info(f"Task {task_id} status: {st.name} | info: {task_info}")
    
    return JSONResponse({
        "task_id": task_id,
        "status": st.name,
        "details": task_info
    })


# async def result(task_id: str):
#     logger.debug(f"πŸ“¦ Fetching result for task: {task_id}")
#     info = queue.get_task_info(task_id)
#     if info is None:
#         logger.warning(f"⚠️ Task info not found for {task_id}")
#         raise HTTPException(status_code=404, detail="Task not found")

#     status = queue.get_status(task_id)
#     logger.debug(f"πŸ“ˆ Task {task_id} current status: {status.name}")

#     if status != TaskStatus.COMPLETED:
#         logger.info(f"⏳ Task {task_id} still in progress ({status.name})")
#         return JSONResponse({"task_id": task_id, "status": status.name})

#     output_path = Path(info.get("output_path", ""))
#     logger.debug(f"🧩 Checking output path: {output_path}")
#     # if not output_path.exists():
#     #     logger.error(f"❌ Output file missing for task {task_id}")
#     #     raise HTTPException(status_code=404, detail="Output not found on disk")
    
#     info = queue.get_task_info(task_id)
#     output_bytes = info.get("output_bytes")

#     if output_bytes:
#         logger.info(f"🎬 Returning in-memory video for task {task_id}")
#         return Response(content=output_bytes, media_type="video")

# # fallback to disk if memory missing
#     if not output_path.exists():
#         logger.error(f"❌ Output file missing for task {task_id}")
#         raise HTTPException(status_code=404, detail="Output not found on disk")

#     logger.info(f"🎬 Returning result video from disk for task {task_id}")
#     return FileResponse(
#         path=str(output_path), filename=output_path.name, media_type="video"
#         )
@app.get("/result/{task_id}")
async def result(task_id: str):
    logger.debug(f"πŸ“¦ Fetching result for task: {task_id}")
    info = queue.get_task_info(task_id)
    if info is None:
        logger.warning(f"⚠️ Task info not found for {task_id}")
        raise HTTPException(status_code=404, detail="Task not found")

    status = queue.get_status(task_id)
    logger.debug(f"πŸ“ˆ Task {task_id} current status: {status.name}")

    if status != TaskStatus.COMPLETED:
        logger.info(f"⏳ Task {task_id} still in progress ({status.name})")
        return JSONResponse({"task_id": task_id, "status": status.name})

    info = queue.get_task_info(task_id)
    output_path = Path(info.get("output_path", ""))  # MOV path

    if not output_path.exists():
        logger.error(f"❌ Output file missing for task {task_id}")
        raise HTTPException(status_code=404, detail="Output not found")
    
    # Convert MOV to WEBM with alpha if needed
    webm_path = output_path.with_suffix(".webm")
    if output_path.suffix.lower() == ".mov" and not webm_path.exists():
        try:
            logger.info(f"🎞️ Converting .mov β†’ .webm (keeping transparency)...")
            cmd = [
                "ffmpeg",
                "-y",
                "-i", str(output_path),
                "-c:v", "libvpx-vp9",
                "-pix_fmt", "yuva420p",  # keep alpha channel
                "-b:v", "4M",
                "-auto-alt-ref", "0",
                str(webm_path)
            ]
            subprocess.run(cmd, check=True, capture_output=True)
            logger.info(f"βœ… Converted successfully β†’ {webm_path}")
        except Exception as e:
            logger.error(f"⚠️ MOVβ†’WEBM conversion failed: {e}")
            raise HTTPException(status_code=500, detail=f"Conversion failed: {e}")
    
    # Read both MOV and WEBM as bytes
    mov_bytes = output_path.read_bytes()
    webm_bytes = webm_path.read_bytes()

    logger.info(f"βœ… Returning both MOV + WEBM for task {task_id}")
    return JSONResponse({
        "task_id": task_id,
        "status": "COMPLETED",
        "results": [
            {
                "format": "mov",
                "data": base64.b64encode(mov_bytes).decode("utf-8"),
            },
            {
                "format": "webm",
                "data": base64.b64encode(webm_bytes).decode("utf-8"),
            },
        ],
    })

@app.delete("/task/{task_id}")
async def delete_task(task_id: str):
    logger.info(f"πŸ—‘ Request to delete task: {task_id}")
    info = queue.get_task_info(task_id)
    if info:
        task_dir = Path(info.get("task_dir", ""))
        if task_dir.exists():
            logger.debug(f"🧹 Removing directory: {task_dir}")
            shutil.rmtree(task_dir, ignore_errors=True)
        queue.remove_task(task_id)
        logger.info(f"βœ… Task {task_id} removed successfully.")
        return JSONResponse({"task_id": task_id, "status": "removed"})
    else:
        logger.warning(f"⚠️ Task {task_id} not found for deletion.")
        raise HTTPException(status_code=404, detail="Task not found")





@app.get("/")
def home():
    return {"status": "Your Manim backend is running!"}