|
| 1 | +''' Used to launch the FastAPI web server when worker is running in API mode. ''' |
| 2 | + |
| 3 | +import os |
| 4 | +import threading |
| 5 | + |
| 6 | +import uvicorn |
| 7 | +from fastapi import FastAPI |
| 8 | +from fastapi.encoders import jsonable_encoder |
| 9 | +from pydantic import BaseModel |
| 10 | + |
| 11 | +from .job import run_job |
| 12 | +from .worker_state import set_job_id |
| 13 | +from .heartbeat import start_heartbeat |
| 14 | + |
| 15 | + |
| 16 | +class Job(BaseModel): |
| 17 | + ''' Represents a job. ''' |
| 18 | + id: str |
| 19 | + input: dict |
| 20 | + |
| 21 | + |
| 22 | +class WorkerAPI: |
| 23 | + ''' Used to launch the FastAPI web server when worker is running in API mode. ''' |
| 24 | + |
| 25 | + def __init__(self): |
| 26 | + ''' |
| 27 | + Initializes the WorkerAPI class. |
| 28 | + 1. Starts the heartbeat thread. |
| 29 | + 2. Initializes the FastAPI web server. |
| 30 | + ''' |
| 31 | + heartbeat_thread = threading.Thread(target=start_heartbeat) |
| 32 | + heartbeat_thread.daemon = True |
| 33 | + heartbeat_thread.start() |
| 34 | + |
| 35 | + self.config = {"handler": None} |
| 36 | + self.rp_app = FastAPI() |
| 37 | + self.rp_app.add_api_route("/run", self.run, methods=["POST"]) |
| 38 | + |
| 39 | + def start_uvicorn(self, api_port): |
| 40 | + ''' |
| 41 | + Starts the Uvicorn server. |
| 42 | + ''' |
| 43 | + uvicorn.run( |
| 44 | + self.rp_app, host='0.0.0.0', port=int(api_port), |
| 45 | + workers=os.environ.get('RUNPOD_REALTIME_CONCURRENCY', 1) |
| 46 | + ) |
| 47 | + |
| 48 | + async def run(self, job: Job): |
| 49 | + ''' |
| 50 | + Performs model inference on the input data. |
| 51 | + ''' |
| 52 | + set_job_id(job.id) |
| 53 | + |
| 54 | + job_results = run_job(self.config["handler"], job.__dict__) |
| 55 | + |
| 56 | + set_job_id(None) |
| 57 | + |
| 58 | + return jsonable_encoder(job_results) |
0 commit comments