File size: 6,192 Bytes
df6c67d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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
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
import os
from functools import wraps
from typing import Any, Awaitable, Callable

import uvicorn
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse

from inference.core import logger
from inference.enterprise.stream_management.api.entities import (
    CommandResponse,
    InferencePipelineStatusResponse,
    ListPipelinesResponse,
    PipelineInitialisationRequest,
)
from inference.enterprise.stream_management.api.errors import (
    ConnectivityError,
    ProcessesManagerAuthorisationError,
    ProcessesManagerClientError,
    ProcessesManagerInvalidPayload,
    ProcessesManagerNotFoundError,
)
from inference.enterprise.stream_management.api.stream_manager_client import (
    StreamManagerClient,
)
from inference.enterprise.stream_management.manager.entities import (
    STATUS_KEY,
    OperationStatus,
)

API_HOST = os.getenv("STREAM_MANAGEMENT_API_HOST", "127.0.0.1")
API_PORT = int(os.getenv("STREAM_MANAGEMENT_API_PORT", "8080"))

OPERATIONS_TIMEOUT = os.getenv("STREAM_MANAGER_OPERATIONS_TIMEOUT")
if OPERATIONS_TIMEOUT is not None:
    OPERATIONS_TIMEOUT = float(OPERATIONS_TIMEOUT)

STREAM_MANAGER_CLIENT = StreamManagerClient.init(
    host=os.getenv("STREAM_MANAGER_HOST", "127.0.0.1"),
    port=int(os.getenv("STREAM_MANAGER_PORT", "7070")),
    operations_timeout=OPERATIONS_TIMEOUT,
)

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


def with_route_exceptions(route: callable) -> Callable[[Any], Awaitable[JSONResponse]]:
    @wraps(route)
    async def wrapped_route(*args, **kwargs):
        try:
            return await route(*args, **kwargs)
        except ProcessesManagerInvalidPayload as error:
            resp = JSONResponse(
                status_code=400,
                content={STATUS_KEY: OperationStatus.FAILURE, "message": str(error)},
            )
            logger.exception("Processes Manager - invalid payload error")
            return resp
        except ProcessesManagerAuthorisationError as error:
            resp = JSONResponse(
                status_code=401,
                content={STATUS_KEY: OperationStatus.FAILURE, "message": str(error)},
            )
            logger.exception("Processes Manager - authorisation error")
            return resp
        except ProcessesManagerNotFoundError as error:
            resp = JSONResponse(
                status_code=404,
                content={STATUS_KEY: OperationStatus.FAILURE, "message": str(error)},
            )
            logger.exception("Processes Manager - not found error")
            return resp
        except ConnectivityError as error:
            resp = JSONResponse(
                status_code=503,
                content={STATUS_KEY: OperationStatus.FAILURE, "message": str(error)},
            )
            logger.exception("Processes Manager connectivity error occurred")
            return resp
        except ProcessesManagerClientError as error:
            resp = JSONResponse(
                status_code=500,
                content={STATUS_KEY: OperationStatus.FAILURE, "message": str(error)},
            )
            logger.exception("Processes Manager error occurred")
            return resp
        except Exception:
            resp = JSONResponse(
                status_code=500,
                content={
                    STATUS_KEY: OperationStatus.FAILURE,
                    "message": "Internal error.",
                },
            )
            logger.exception("Internal error in API")
            return resp

    return wrapped_route


@app.get(
    "/list_pipelines",
    response_model=ListPipelinesResponse,
    summary="List active pipelines",
    description="Listing all active pipelines in the state of ProcessesManager being queried.",
)
@with_route_exceptions
async def list_pipelines(_: Request) -> ListPipelinesResponse:
    return await STREAM_MANAGER_CLIENT.list_pipelines()


@app.get(
    "/status/{pipeline_id}",
    response_model=InferencePipelineStatusResponse,
    summary="Get status of pipeline",
    description="Returns detailed statis of Inference Pipeline in the state of ProcessesManager being queried.",
)
@with_route_exceptions
async def get_status(pipeline_id: str) -> InferencePipelineStatusResponse:
    return await STREAM_MANAGER_CLIENT.get_status(pipeline_id=pipeline_id)


@app.post(
    "/initialise",
    response_model=CommandResponse,
    summary="Initialise the pipeline",
    description="Starts new Inference Pipeline within the state of ProcessesManager being queried.",
)
@with_route_exceptions
async def initialise(request: PipelineInitialisationRequest) -> CommandResponse:
    return await STREAM_MANAGER_CLIENT.initialise_pipeline(
        initialisation_request=request
    )


@app.post(
    "/pause/{pipeline_id}",
    response_model=CommandResponse,
    summary="Pauses the pipeline processing",
    description="Mutes the VideoSource of Inference Pipeline within the state of ProcessesManager being queried.",
)
@with_route_exceptions
async def pause(pipeline_id: str) -> CommandResponse:
    return await STREAM_MANAGER_CLIENT.pause_pipeline(pipeline_id=pipeline_id)


@app.post(
    "/resume/{pipeline_id}",
    response_model=CommandResponse,
    summary="Resumes the pipeline processing",
    description="Resumes the VideoSource of Inference Pipeline within the state of ProcessesManager being queried.",
)
@with_route_exceptions
async def resume(pipeline_id: str) -> CommandResponse:
    return await STREAM_MANAGER_CLIENT.resume_pipeline(pipeline_id=pipeline_id)


@app.post(
    "/terminate/{pipeline_id}",
    response_model=CommandResponse,
    summary="Terminates the pipeline processing",
    description="Terminates the VideoSource of Inference Pipeline within the state of ProcessesManager being queried.",
)
@with_route_exceptions
async def terminate(pipeline_id: str) -> CommandResponse:
    return await STREAM_MANAGER_CLIENT.terminate_pipeline(pipeline_id=pipeline_id)


if __name__ == "__main__":
    uvicorn.run(app, host=API_HOST, port=API_PORT)