2022-11-25 17:15:56 -07:00
|
|
|
"""
|
2022-12-26 18:25:17 -07:00
|
|
|
Flask server that serves the riffusion model as an API.
|
2022-11-25 17:15:56 -07:00
|
|
|
"""
|
|
|
|
|
|
|
|
import dataclasses
|
|
|
|
import io
|
|
|
|
import json
|
2022-12-26 19:12:02 -07:00
|
|
|
import logging
|
2022-11-25 17:15:56 -07:00
|
|
|
import time
|
2022-11-25 23:49:25 -07:00
|
|
|
import typing as T
|
2022-12-26 19:12:02 -07:00
|
|
|
from pathlib import Path
|
2022-11-25 17:15:56 -07:00
|
|
|
|
|
|
|
import dacite
|
|
|
|
import flask
|
|
|
|
import PIL
|
2022-12-26 19:12:02 -07:00
|
|
|
from flask_cors import CORS
|
2022-11-25 17:15:56 -07:00
|
|
|
|
2022-12-26 19:12:02 -07:00
|
|
|
from riffusion.datatypes import InferenceInput, InferenceOutput
|
2022-12-26 18:25:17 -07:00
|
|
|
from riffusion.riffusion_pipeline import RiffusionPipeline
|
|
|
|
from riffusion.spectrogram_image_converter import SpectrogramImageConverter
|
|
|
|
from riffusion.spectrogram_params import SpectrogramParams
|
|
|
|
from riffusion.util import base64_util
|
2022-11-25 17:15:56 -07:00
|
|
|
|
|
|
|
# Flask app with CORS
|
|
|
|
app = flask.Flask(__name__)
|
|
|
|
CORS(app)
|
|
|
|
|
|
|
|
# Log at the INFO level to both stdout and disk
|
|
|
|
logging.basicConfig(level=logging.INFO)
|
|
|
|
logging.getLogger().addHandler(logging.FileHandler("server.log"))
|
|
|
|
|
|
|
|
# Global variable for the model pipeline
|
2022-12-26 18:25:17 -07:00
|
|
|
PIPELINE: T.Optional[RiffusionPipeline] = None
|
2022-11-25 17:15:56 -07:00
|
|
|
|
|
|
|
# Where built-in seed images are stored
|
|
|
|
SEED_IMAGES_DIR = Path(Path(__file__).resolve().parent.parent, "seed_images")
|
|
|
|
|
|
|
|
|
|
|
|
def run_app(
|
|
|
|
*,
|
2022-12-12 23:16:45 -07:00
|
|
|
checkpoint: str = "riffusion/riffusion-model-v1",
|
2022-12-22 22:08:37 -07:00
|
|
|
no_traced_unet: bool = False,
|
2022-12-26 18:25:17 -07:00
|
|
|
device: str = "cuda",
|
2022-11-25 17:15:56 -07:00
|
|
|
host: str = "127.0.0.1",
|
2022-12-26 18:25:17 -07:00
|
|
|
port: int = 3013,
|
2022-11-25 17:15:56 -07:00
|
|
|
debug: bool = False,
|
2022-11-25 23:49:25 -07:00
|
|
|
ssl_certificate: T.Optional[str] = None,
|
2022-11-27 14:55:42 -07:00
|
|
|
ssl_key: T.Optional[str] = None,
|
2022-11-25 17:15:56 -07:00
|
|
|
):
|
|
|
|
"""
|
|
|
|
Run a flask API that serves the given riffusion model checkpoint.
|
|
|
|
"""
|
|
|
|
# Initialize the model
|
2022-12-26 18:25:17 -07:00
|
|
|
global PIPELINE
|
|
|
|
PIPELINE = RiffusionPipeline.load_checkpoint(
|
|
|
|
checkpoint=checkpoint,
|
|
|
|
use_traced_unet=not no_traced_unet,
|
|
|
|
device=device,
|
|
|
|
)
|
2022-11-25 17:15:56 -07:00
|
|
|
|
2022-11-25 23:49:25 -07:00
|
|
|
args = dict(
|
2022-11-25 17:15:56 -07:00
|
|
|
debug=debug,
|
|
|
|
threaded=False,
|
|
|
|
host=host,
|
|
|
|
port=port,
|
|
|
|
)
|
|
|
|
|
2022-11-25 23:49:25 -07:00
|
|
|
if ssl_certificate:
|
|
|
|
assert ssl_key is not None
|
|
|
|
args["ssl_context"] = (ssl_certificate, ssl_key)
|
|
|
|
|
2022-12-26 18:25:17 -07:00
|
|
|
app.run(**args) # type: ignore
|
2022-11-25 17:15:56 -07:00
|
|
|
|
|
|
|
|
|
|
|
@app.route("/run_inference/", methods=["POST"])
|
|
|
|
def run_inference():
|
|
|
|
"""
|
|
|
|
Execute the riffusion model as an API.
|
|
|
|
|
|
|
|
Inputs:
|
|
|
|
Serialized JSON of the InferenceInput dataclass
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
Serialized JSON of the InferenceOutput dataclass
|
|
|
|
"""
|
|
|
|
start_time = time.time()
|
|
|
|
|
|
|
|
# Parse the payload as JSON
|
|
|
|
json_data = json.loads(flask.request.data)
|
|
|
|
|
|
|
|
# Log the request
|
|
|
|
logging.info(json_data)
|
|
|
|
|
|
|
|
# Parse an InferenceInput dataclass from the payload
|
|
|
|
try:
|
|
|
|
inputs = dacite.from_dict(InferenceInput, json_data)
|
|
|
|
except dacite.exceptions.WrongTypeError as exception:
|
|
|
|
logging.info(json_data)
|
|
|
|
return str(exception), 400
|
|
|
|
except dacite.exceptions.MissingValueError as exception:
|
|
|
|
logging.info(json_data)
|
|
|
|
return str(exception), 400
|
|
|
|
|
2022-12-26 18:25:17 -07:00
|
|
|
response = compute_request(
|
|
|
|
inputs=inputs,
|
|
|
|
seed_images_dir=SEED_IMAGES_DIR,
|
|
|
|
pipeline=PIPELINE,
|
|
|
|
)
|
2022-11-27 17:06:12 -07:00
|
|
|
|
|
|
|
# Log the total time
|
|
|
|
logging.info(f"Request took {time.time() - start_time:.2f} s")
|
|
|
|
|
|
|
|
return response
|
|
|
|
|
2022-12-12 23:43:46 -07:00
|
|
|
|
2022-12-26 18:25:17 -07:00
|
|
|
def compute_request(
|
|
|
|
inputs: InferenceInput,
|
|
|
|
pipeline: RiffusionPipeline,
|
|
|
|
seed_images_dir: str,
|
|
|
|
) -> T.Union[str, T.Tuple[str, int]]:
|
2022-11-27 17:06:12 -07:00
|
|
|
"""
|
|
|
|
Does all the heavy lifting of the request.
|
2022-12-26 18:25:17 -07:00
|
|
|
|
|
|
|
Args:
|
|
|
|
inputs: The input dataclass
|
|
|
|
pipeline: The riffusion model pipeline
|
|
|
|
seed_images_dir: The directory where seed images are stored
|
2022-11-27 17:06:12 -07:00
|
|
|
"""
|
2022-11-25 17:15:56 -07:00
|
|
|
# Load the seed image by ID
|
2022-12-26 18:25:17 -07:00
|
|
|
init_image_path = Path(seed_images_dir, f"{inputs.seed_image_id}.png")
|
|
|
|
|
2022-11-27 17:06:12 -07:00
|
|
|
if not init_image_path.is_file():
|
2022-11-25 17:15:56 -07:00
|
|
|
return f"Invalid seed image: {inputs.seed_image_id}", 400
|
|
|
|
init_image = PIL.Image.open(str(init_image_path)).convert("RGB")
|
|
|
|
|
2022-11-25 23:48:52 -07:00
|
|
|
# Load the mask image by ID
|
2022-12-26 18:25:17 -07:00
|
|
|
mask_image: T.Optional[PIL.Image.Image] = None
|
2022-11-25 23:48:52 -07:00
|
|
|
if inputs.mask_image_id:
|
2022-12-26 18:25:17 -07:00
|
|
|
mask_image_path = Path(seed_images_dir, f"{inputs.mask_image_id}.png")
|
2022-11-27 17:06:12 -07:00
|
|
|
if not mask_image_path.is_file():
|
2022-11-25 23:48:52 -07:00
|
|
|
return f"Invalid mask image: {inputs.mask_image_id}", 400
|
|
|
|
mask_image = PIL.Image.open(str(mask_image_path)).convert("RGB")
|
|
|
|
|
2022-11-25 17:15:56 -07:00
|
|
|
# Execute the model to get the spectrogram image
|
2022-12-26 18:25:17 -07:00
|
|
|
image = pipeline.riffuse(
|
|
|
|
inputs,
|
|
|
|
init_image=init_image,
|
|
|
|
mask_image=mask_image,
|
|
|
|
)
|
2022-11-27 14:55:42 -07:00
|
|
|
|
2022-12-26 18:25:17 -07:00
|
|
|
# TODO(hayk): Change the frequency range to [20, 20k] once the model is retrained
|
|
|
|
params = SpectrogramParams(
|
|
|
|
min_frequency=0,
|
|
|
|
max_frequency=10000,
|
2022-11-27 14:55:42 -07:00
|
|
|
)
|
2022-11-25 17:15:56 -07:00
|
|
|
|
2022-12-26 18:25:17 -07:00
|
|
|
# Reconstruct audio from the image
|
2022-12-27 08:44:39 -07:00
|
|
|
# TODO(hayk): It may help performance a bit to cache this object
|
2022-12-26 18:25:17 -07:00
|
|
|
converter = SpectrogramImageConverter(params=params, device=str(pipeline.device))
|
2022-12-27 08:44:39 -07:00
|
|
|
|
2022-12-26 18:25:17 -07:00
|
|
|
segment = converter.audio_from_spectrogram_image(
|
|
|
|
image,
|
|
|
|
apply_filters=True,
|
|
|
|
)
|
2022-11-25 17:15:56 -07:00
|
|
|
|
2022-12-26 18:25:17 -07:00
|
|
|
# Export audio to MP3 bytes
|
|
|
|
mp3_bytes = io.BytesIO()
|
|
|
|
segment.export(mp3_bytes, format="mp3")
|
|
|
|
mp3_bytes.seek(0)
|
2022-11-25 17:15:56 -07:00
|
|
|
|
2022-12-26 18:25:17 -07:00
|
|
|
# Export image to JPEG bytes
|
2022-11-25 17:15:56 -07:00
|
|
|
image_bytes = io.BytesIO()
|
2022-12-26 18:25:17 -07:00
|
|
|
image.save(image_bytes, exif=image.getexif(), format="JPEG")
|
2022-11-25 17:15:56 -07:00
|
|
|
image_bytes.seek(0)
|
|
|
|
|
2022-12-26 18:25:17 -07:00
|
|
|
# Assemble the output dataclass
|
|
|
|
output = InferenceOutput(
|
|
|
|
image="data:image/jpeg;base64," + base64_util.encode(image_bytes),
|
|
|
|
audio="data:audio/mpeg;base64," + base64_util.encode(mp3_bytes),
|
|
|
|
duration_s=segment.duration_seconds,
|
|
|
|
)
|
2022-11-25 17:15:56 -07:00
|
|
|
|
2022-12-26 18:25:17 -07:00
|
|
|
return json.dumps(dataclasses.asdict(output))
|
2022-11-25 17:15:56 -07:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
import argh
|
|
|
|
|
|
|
|
argh.dispatch_command(run_app)
|