api_server.py 4.66 KB
Newer Older
1
import asyncio
helloyongyang's avatar
helloyongyang committed
2
import argparse
3
from fastapi import FastAPI
helloyongyang's avatar
helloyongyang committed
4
from pydantic import BaseModel
root's avatar
root committed
5
from loguru import logger
helloyongyang's avatar
helloyongyang committed
6
7
import uvicorn
import json
8
9
10
from typing import Optional
from datetime import datetime
import threading
11
12
13
import ctypes
import gc
import torch
helloyongyang's avatar
helloyongyang committed
14
15
16
17

from lightx2v.utils.profiler import ProfilingContext
from lightx2v.utils.set_config import set_config
from lightx2v.infer import init_runner
18
from lightx2v.utils.service_utils import TaskStatusMessage, BaseServiceStatus, ProcessManager
19
20
21
22
23
24
25


# =========================
# FastAPI Related Code
# =========================

runner = None
26
thread = None
27
28
29
30

app = FastAPI()


helloyongyang's avatar
helloyongyang committed
31
class Message(BaseModel):
32
33
34
    task_id: str
    task_id_must_unique: bool = False

helloyongyang's avatar
helloyongyang committed
35
    prompt: str
Zhuguanyu Wu's avatar
Zhuguanyu Wu committed
36
    use_prompt_enhancer: bool = False
helloyongyang's avatar
helloyongyang committed
37
38
    negative_prompt: str = ""
    image_path: str = ""
Zhuguanyu Wu's avatar
Zhuguanyu Wu committed
39
    num_fragments: int = 1
helloyongyang's avatar
helloyongyang committed
40
41
42
43
44
45
    save_video_path: str

    def get(self, key, default=None):
        return getattr(self, key, default)


46
47
class ApiServerServiceStatus(BaseServiceStatus):
    pass
48
49
50
51
52
53
54


def local_video_generate(message: Message):
    try:
        global runner
        runner.set_inputs(message)
        logger.info(f"message: {message}")
55
56
57
58
59
60
61
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        try:
            loop.run_until_complete(runner.run_pipeline())
        finally:
            loop.close()
        ApiServerServiceStatus.complete_task(message)
62
63
    except Exception as e:
        logger.error(f"task_id {message.task_id} failed: {str(e)}")
64
        ApiServerServiceStatus.record_failed_task(message, error=str(e))
65
66


67
@app.post("/v1/local/video/generate")
helloyongyang's avatar
helloyongyang committed
68
async def v1_local_video_generate(message: Message):
69
    try:
70
        task_id = ApiServerServiceStatus.start_task(message)
71
        # Use background threads to perform long-running tasks
72
73
74
        global thread
        thread = threading.Thread(target=local_video_generate, args=(message,), daemon=True)
        thread.start()
75
        return {"task_id": task_id, "task_status": "processing", "save_video_path": message.save_video_path}
76
77
78
79
80
81
    except RuntimeError as e:
        return {"error": str(e)}


@app.get("/v1/local/video/generate/service_status")
async def get_service_status():
82
    return ApiServerServiceStatus.get_status_service()
83
84
85
86


@app.get("/v1/local/video/generate/get_all_tasks")
async def get_all_tasks():
87
    return ApiServerServiceStatus.get_all_tasks()
88
89
90
91


@app.post("/v1/local/video/generate/task_status")
async def get_task_status(message: TaskStatusMessage):
92
    return ApiServerServiceStatus.get_status_task_id(message.task_id)
93
94


95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
def _async_raise(tid, exctype):
    """Force thread tid to raise exception exctype"""
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), ctypes.py_object(exctype))
    if res == 0:
        raise ValueError("Invalid thread ID")
    elif res > 1:
        ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), 0)
        raise SystemError("PyThreadState_SetAsyncExc failed")


@app.get("/v1/local/video/generate/stop_running_task")
async def stop_running_task():
    global thread
    if thread and thread.is_alive():
        try:
            _async_raise(thread.ident, SystemExit)
            thread.join()

            # Clean up the thread reference
            thread = None
115
            ApiServerServiceStatus.clean_stopped_task()
116
117
118
119
120
121
122
            gc.collect()
            torch.cuda.empty_cache()
            return {"stop_status": "success", "reason": "Task stopped successfully."}
        except Exception as e:
            return {"stop_status": "error", "reason": str(e)}
    else:
        return {"stop_status": "do_nothing", "reason": "No running task found."}
helloyongyang's avatar
helloyongyang committed
123
124


125
126
127
128
# =========================
# Main Entry
# =========================

helloyongyang's avatar
helloyongyang committed
129
if __name__ == "__main__":
130
    ProcessManager.register_signal_handler()
helloyongyang's avatar
helloyongyang committed
131
    parser = argparse.ArgumentParser()
132
    parser.add_argument("--model_cls", type=str, required=True, choices=["wan2.1", "hunyuan", "wan2.1_distill", "wan2.1_causvid", "wan2.1_skyreels_v2_df", "cogvideox"], default="hunyuan")
helloyongyang's avatar
helloyongyang committed
133
134
135
    parser.add_argument("--task", type=str, choices=["t2v", "i2v"], default="t2v")
    parser.add_argument("--model_path", type=str, required=True)
    parser.add_argument("--config_json", type=str, required=True)
136
    parser.add_argument("--split", action="store_true")
helloyongyang's avatar
helloyongyang committed
137

helloyongyang's avatar
helloyongyang committed
138
139
    parser.add_argument("--port", type=int, default=8000)
    args = parser.parse_args()
root's avatar
root committed
140
    logger.info(f"args: {args}")
helloyongyang's avatar
helloyongyang committed
141
142
143

    with ProfilingContext("Init Server Cost"):
        config = set_config(args)
144
        config["mode"] = "split_server" if args.split else "server"
root's avatar
root committed
145
        logger.info(f"config:\n{json.dumps(config, ensure_ascii=False, indent=4)}")
helloyongyang's avatar
helloyongyang committed
146
147
        runner = init_runner(config)

148
    uvicorn.run(app, host="0.0.0.0", port=config.port, reload=False, workers=1)