api.py 16.5 KB
Newer Older
PengGao's avatar
PengGao committed
1
2
import asyncio
import gc
PengGao's avatar
PengGao committed
3
import threading
gaclove's avatar
gaclove committed
4
import time
PengGao's avatar
PengGao committed
5
import uuid
PengGao's avatar
PengGao committed
6
from pathlib import Path
gaclove's avatar
gaclove committed
7
8
from typing import Any, Optional
from urllib.parse import urlparse
PengGao's avatar
PengGao committed
9

gaclove's avatar
gaclove committed
10
import httpx
PengGao's avatar
PengGao committed
11
12
13
14
15
import torch
from fastapi import APIRouter, FastAPI, File, Form, HTTPException, UploadFile
from fastapi.responses import StreamingResponse
from loguru import logger

PengGao's avatar
PengGao committed
16
17
from .schema import (
    StopTaskResponse,
PengGao's avatar
PengGao committed
18
19
    TaskRequest,
    TaskResponse,
PengGao's avatar
PengGao committed
20
)
PengGao's avatar
PengGao committed
21
from .service import DistributedInferenceService, FileService, VideoGenerationService
gaclove's avatar
gaclove committed
22
from .task_manager import TaskStatus, task_manager
PengGao's avatar
PengGao committed
23
24
25


class ApiServer:
gaclove's avatar
gaclove committed
26
27
    def __init__(self, max_queue_size: int = 10, app: Optional[FastAPI] = None):
        self.app = app or FastAPI(title="LightX2V API", version="1.0.0")
PengGao's avatar
PengGao committed
28
29
30
        self.file_service = None
        self.inference_service = None
        self.video_service = None
gaclove's avatar
gaclove committed
31
32
33
34
        self.max_queue_size = max_queue_size

        self.processing_thread = None
        self.stop_processing = threading.Event()
PengGao's avatar
PengGao committed
35
36
37
38
39
40
41
42

        self.tasks_router = APIRouter(prefix="/v1/tasks", tags=["tasks"])
        self.files_router = APIRouter(prefix="/v1/files", tags=["files"])
        self.service_router = APIRouter(prefix="/v1/service", tags=["service"])

        self._setup_routes()

    def _setup_routes(self):
43
44
45
46
        @self.app.get("/")
        def redirect_to_docs():
            return RedirectResponse(url="/docs")

PengGao's avatar
PengGao committed
47
48
49
50
51
52
53
54
        self._setup_task_routes()
        self._setup_file_routes()
        self._setup_service_routes()

        self.app.include_router(self.tasks_router)
        self.app.include_router(self.files_router)
        self.app.include_router(self.service_router)

55
56
57
58
    def _write_file_sync(self, file_path: Path, content: bytes) -> None:
        with open(file_path, "wb") as buffer:
            buffer.write(content)

PengGao's avatar
PengGao committed
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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
    def _stream_file_response(self, file_path: Path, filename: str | None = None) -> StreamingResponse:
        assert self.file_service is not None, "File service is not initialized"

        try:
            resolved_path = file_path.resolve()

            if not str(resolved_path).startswith(str(self.file_service.output_video_dir.resolve())):
                raise HTTPException(status_code=403, detail="Access to this file is not allowed")

            if not resolved_path.exists() or not resolved_path.is_file():
                raise HTTPException(status_code=404, detail=f"File not found: {file_path}")

            file_size = resolved_path.stat().st_size
            actual_filename = filename or resolved_path.name

            # Set appropriate MIME type
            mime_type = "application/octet-stream"
            if actual_filename.lower().endswith((".mp4", ".avi", ".mov", ".mkv")):
                mime_type = "video/mp4"
            elif actual_filename.lower().endswith((".jpg", ".jpeg", ".png", ".gif")):
                mime_type = "image/jpeg"

            headers = {
                "Content-Disposition": f'attachment; filename="{actual_filename}"',
                "Content-Length": str(file_size),
                "Accept-Ranges": "bytes",
            }

            def file_stream_generator(file_path: str, chunk_size: int = 1024 * 1024):
                with open(file_path, "rb") as file:
                    while chunk := file.read(chunk_size):
                        yield chunk

            return StreamingResponse(
                file_stream_generator(str(resolved_path)),
                media_type=mime_type,
                headers=headers,
            )
        except HTTPException:
            raise
        except Exception as e:
            logger.error(f"Error occurred while processing file stream response: {e}")
            raise HTTPException(status_code=500, detail="File transfer failed")

    def _setup_task_routes(self):
        @self.tasks_router.post("/", response_model=TaskResponse)
        async def create_task(message: TaskRequest):
            """Create video generation task"""
            try:
gaclove's avatar
gaclove committed
108
109
110
111
112
113
114
115
                if hasattr(message, "image_path") and message.image_path and message.image_path.startswith("http"):
                    if not await self._validate_image_url(message.image_path):
                        raise HTTPException(status_code=400, detail=f"Image URL is not accessible: {message.image_path}")

                task_id = task_manager.create_task(message)
                message.task_id = task_id

                self._ensure_processing_thread_running()
PengGao's avatar
PengGao committed
116
117
118

                return TaskResponse(
                    task_id=task_id,
gaclove's avatar
gaclove committed
119
                    task_status="pending",
120
                    save_result_path=message.save_result_path,
PengGao's avatar
PengGao committed
121
122
                )
            except RuntimeError as e:
gaclove's avatar
gaclove committed
123
124
125
126
                raise HTTPException(status_code=503, detail=str(e))
            except Exception as e:
                logger.error(f"Failed to create task: {e}")
                raise HTTPException(status_code=500, detail=str(e))
PengGao's avatar
PengGao committed
127
128
129
130
131

        @self.tasks_router.post("/form", response_model=TaskResponse)
        async def create_task_form(
            image_file: UploadFile = File(...),
            prompt: str = Form(default=""),
132
            save_result_path: str = Form(default=""),
PengGao's avatar
PengGao committed
133
134
135
136
137
138
            use_prompt_enhancer: bool = Form(default=False),
            negative_prompt: str = Form(default=""),
            num_fragments: int = Form(default=1),
            infer_steps: int = Form(default=5),
            target_video_length: int = Form(default=81),
            seed: int = Form(default=42),
139
            audio_file: UploadFile = File(None),
PengGao's avatar
PengGao committed
140
141
142
143
            video_duration: int = Form(default=5),
        ):
            assert self.file_service is not None, "File service is not initialized"

144
145
146
147
148
            async def save_file_async(file: UploadFile, target_dir: Path) -> str:
                if not file or not file.filename:
                    return ""

                file_extension = Path(file.filename).suffix
PengGao's avatar
PengGao committed
149
                unique_filename = f"{uuid.uuid4()}{file_extension}"
150
                file_path = target_dir / unique_filename
PengGao's avatar
PengGao committed
151

152
                content = await file.read()
PengGao's avatar
PengGao committed
153

154
                await asyncio.to_thread(self._write_file_sync, file_path, content)
PengGao's avatar
PengGao committed
155

156
                return str(file_path)
PengGao's avatar
PengGao committed
157

158
159
160
            image_path = ""
            if image_file and image_file.filename:
                image_path = await save_file_async(image_file, self.file_service.input_image_dir)
PengGao's avatar
PengGao committed
161

162
163
164
            audio_path = ""
            if audio_file and audio_file.filename:
                audio_path = await save_file_async(audio_file, self.file_service.input_audio_dir)
PengGao's avatar
PengGao committed
165
166
167
168
169
170
171

            message = TaskRequest(
                prompt=prompt,
                use_prompt_enhancer=use_prompt_enhancer,
                negative_prompt=negative_prompt,
                image_path=image_path,
                num_fragments=num_fragments,
172
                save_result_path=save_result_path,
PengGao's avatar
PengGao committed
173
174
175
176
177
178
179
180
                infer_steps=infer_steps,
                target_video_length=target_video_length,
                seed=seed,
                audio_path=audio_path,
                video_duration=video_duration,
            )

            try:
gaclove's avatar
gaclove committed
181
182
183
184
                task_id = task_manager.create_task(message)
                message.task_id = task_id

                self._ensure_processing_thread_running()
PengGao's avatar
PengGao committed
185
186
187

                return TaskResponse(
                    task_id=task_id,
gaclove's avatar
gaclove committed
188
                    task_status="pending",
189
                    save_result_path=message.save_result_path,
PengGao's avatar
PengGao committed
190
191
                )
            except RuntimeError as e:
gaclove's avatar
gaclove committed
192
193
194
195
                raise HTTPException(status_code=503, detail=str(e))
            except Exception as e:
                logger.error(f"Failed to create form task: {e}")
                raise HTTPException(status_code=500, detail=str(e))
PengGao's avatar
PengGao committed
196
197
198

        @self.tasks_router.get("/", response_model=dict)
        async def list_tasks():
gaclove's avatar
gaclove committed
199
200
201
202
203
204
205
206
207
208
209
210
211
            return task_manager.get_all_tasks()

        @self.tasks_router.get("/queue/status", response_model=dict)
        async def get_queue_status():
            service_status = task_manager.get_service_status()
            return {
                "is_processing": task_manager.is_processing(),
                "current_task": service_status.get("current_task"),
                "pending_count": task_manager.get_pending_task_count(),
                "active_count": task_manager.get_active_task_count(),
                "queue_size": self.max_queue_size,
                "queue_available": self.max_queue_size - task_manager.get_active_task_count(),
            }
PengGao's avatar
PengGao committed
212
213
214

        @self.tasks_router.get("/{task_id}/status")
        async def get_task_status(task_id: str):
gaclove's avatar
gaclove committed
215
216
217
218
            status = task_manager.get_task_status(task_id)
            if not status:
                raise HTTPException(status_code=404, detail="Task not found")
            return status
PengGao's avatar
PengGao committed
219
220
221
222
223
224
225

        @self.tasks_router.get("/{task_id}/result")
        async def get_task_result(task_id: str):
            assert self.video_service is not None, "Video service is not initialized"
            assert self.file_service is not None, "File service is not initialized"

            try:
gaclove's avatar
gaclove committed
226
                task_status = task_manager.get_task_status(task_id)
PengGao's avatar
PengGao committed
227

gaclove's avatar
gaclove committed
228
229
230
231
232
                if not task_status:
                    raise HTTPException(status_code=404, detail="Task not found")

                if task_status.get("status") != TaskStatus.COMPLETED.value:
                    raise HTTPException(status_code=404, detail="Task not completed")
PengGao's avatar
PengGao committed
233

234
235
                save_result_path = task_status.get("save_result_path")
                if not save_result_path:
PengGao's avatar
PengGao committed
236
237
                    raise HTTPException(status_code=404, detail="Task result file does not exist")

238
                full_path = Path(save_result_path)
PengGao's avatar
PengGao committed
239
                if not full_path.is_absolute():
240
                    full_path = self.file_service.output_video_dir / save_result_path
PengGao's avatar
PengGao committed
241
242
243
244
245
246
247
248
249

                return self._stream_file_response(full_path)

            except HTTPException:
                raise
            except Exception as e:
                logger.error(f"Error occurred while getting task result: {e}")
                raise HTTPException(status_code=500, detail="Failed to get task result")

gaclove's avatar
gaclove committed
250
251
252
253
254
255
        @self.tasks_router.delete("/{task_id}", response_model=StopTaskResponse)
        async def stop_task(task_id: str):
            try:
                if task_manager.cancel_task(task_id):
                    gc.collect()
                    if torch.cuda.is_available():
PengGao's avatar
PengGao committed
256
                        torch.cuda.empty_cache()
gaclove's avatar
gaclove committed
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
                    logger.info(f"Task {task_id} stopped successfully.")
                    return StopTaskResponse(stop_status="success", reason="Task stopped successfully.")
                else:
                    return StopTaskResponse(stop_status="do_nothing", reason="Task not found or already completed.")
            except Exception as e:
                logger.error(f"Error occurred while stopping task {task_id}: {str(e)}")
                return StopTaskResponse(stop_status="error", reason=str(e))

        @self.tasks_router.delete("/all/running", response_model=StopTaskResponse)
        async def stop_all_running_tasks():
            try:
                task_manager.cancel_all_tasks()
                gc.collect()
                if torch.cuda.is_available():
                    torch.cuda.empty_cache()
                logger.info("All tasks stopped successfully.")
                return StopTaskResponse(stop_status="success", reason="All tasks stopped successfully.")
            except Exception as e:
                logger.error(f"Error occurred while stopping all tasks: {str(e)}")
                return StopTaskResponse(stop_status="error", reason=str(e))
PengGao's avatar
PengGao committed
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292

    def _setup_file_routes(self):
        @self.files_router.get("/download/{file_path:path}")
        async def download_file(file_path: str):
            assert self.file_service is not None, "File service is not initialized"

            try:
                full_path = self.file_service.output_video_dir / file_path
                return self._stream_file_response(full_path)
            except HTTPException:
                raise
            except Exception as e:
                logger.error(f"Error occurred while processing file download request: {e}")
                raise HTTPException(status_code=500, detail="File download failed")

    def _setup_service_routes(self):
gaclove's avatar
gaclove committed
293
        @self.service_router.get("/status", response_model=dict)
PengGao's avatar
PengGao committed
294
        async def get_service_status():
gaclove's avatar
gaclove committed
295
            return task_manager.get_service_status()
PengGao's avatar
PengGao committed
296

297
298
299
300
301
        @self.service_router.get("/metadata", response_model=dict)
        async def get_service_metadata():
            assert self.inference_service is not None, "Inference service is not initialized"
            return self.inference_service.server_metadata()

gaclove's avatar
gaclove committed
302
303
304
305
306
307
308
309
310
    async def _validate_image_url(self, image_url: str) -> bool:
        if not image_url or not image_url.startswith("http"):
            return True

        try:
            parsed_url = urlparse(image_url)
            if not parsed_url.scheme or not parsed_url.netloc:
                return False

311
            timeout = httpx.Timeout(connect=5.0, read=5.0, write=5.0, pool=5.0)
gaclove's avatar
gaclove committed
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
            async with httpx.AsyncClient(verify=False, timeout=timeout) as client:
                response = await client.head(image_url, follow_redirects=True)
                return response.status_code < 400
        except Exception as e:
            logger.warning(f"URL validation failed for {image_url}: {str(e)}")
            return False

    def _ensure_processing_thread_running(self):
        if self.processing_thread is None or not self.processing_thread.is_alive():
            self.stop_processing.clear()
            self.processing_thread = threading.Thread(target=self._task_processing_loop, daemon=True)
            self.processing_thread.start()
            logger.info("Started task processing thread")

    def _task_processing_loop(self):
        logger.info("Task processing loop started")

PengGao's avatar
PengGao committed
329
330
331
        asyncio.set_event_loop(asyncio.new_event_loop())
        loop = asyncio.get_event_loop()

gaclove's avatar
gaclove committed
332
333
334
335
336
337
338
339
340
341
        while not self.stop_processing.is_set():
            task_id = task_manager.get_next_pending_task()

            if task_id is None:
                time.sleep(1)
                continue

            task_info = task_manager.get_task(task_id)
            if task_info and task_info.status == TaskStatus.PENDING:
                logger.info(f"Processing task {task_id}")
PengGao's avatar
PengGao committed
342
                loop.run_until_complete(self._process_single_task(task_info))
gaclove's avatar
gaclove committed
343

PengGao's avatar
PengGao committed
344
        loop.close()
gaclove's avatar
gaclove committed
345
346
        logger.info("Task processing loop stopped")

PengGao's avatar
PengGao committed
347
    async def _process_single_task(self, task_info: Any):
PengGao's avatar
PengGao committed
348
        assert self.video_service is not None, "Video service is not initialized"
gaclove's avatar
gaclove committed
349
350
351
352
353
354
355
356
357
358

        task_id = task_info.task_id
        message = task_info.message

        lock_acquired = task_manager.acquire_processing_lock(task_id, timeout=1)
        if not lock_acquired:
            logger.error(f"Task {task_id} failed to acquire processing lock")
            task_manager.fail_task(task_id, "Failed to acquire processing lock")
            return

PengGao's avatar
PengGao committed
359
        try:
gaclove's avatar
gaclove committed
360
361
362
363
364
            task_manager.start_task(task_id)

            if task_info.stop_event.is_set():
                logger.info(f"Task {task_id} cancelled before processing")
                task_manager.fail_task(task_id, "Task cancelled")
PengGao's avatar
PengGao committed
365
366
                return

PengGao's avatar
PengGao committed
367
            result = await self.video_service.generate_video_with_stop_event(message, task_info.stop_event)
gaclove's avatar
gaclove committed
368
369

            if result:
370
                task_manager.complete_task(task_id, result.save_result_path)
gaclove's avatar
gaclove committed
371
372
373
374
375
376
377
378
                logger.info(f"Task {task_id} completed successfully")
            else:
                if task_info.stop_event.is_set():
                    task_manager.fail_task(task_id, "Task cancelled during processing")
                    logger.info(f"Task {task_id} cancelled during processing")
                else:
                    task_manager.fail_task(task_id, "Generation failed")
                    logger.error(f"Task {task_id} generation failed")
PengGao's avatar
PengGao committed
379
380

        except Exception as e:
381
            logger.exception(f"Task {task_id} processing failed: {str(e)}")
gaclove's avatar
gaclove committed
382
383
384
385
            task_manager.fail_task(task_id, str(e))
        finally:
            if lock_acquired:
                task_manager.release_processing_lock(task_id)
PengGao's avatar
PengGao committed
386
387
388
389
390
391

    def initialize_services(self, cache_dir: Path, inference_service: DistributedInferenceService):
        self.file_service = FileService(cache_dir)
        self.inference_service = inference_service
        self.video_service = VideoGenerationService(self.file_service, inference_service)

gaclove's avatar
gaclove committed
392
393
394
395
396
397
398
399
    async def cleanup(self):
        self.stop_processing.set()
        if self.processing_thread and self.processing_thread.is_alive():
            self.processing_thread.join(timeout=5)

        if self.file_service:
            await self.file_service.cleanup()

PengGao's avatar
PengGao committed
400
401
    def get_app(self) -> FastAPI:
        return self.app