|
| 1 | +# Copyright (C) 2024 Intel Corporation |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +import argparse |
| 5 | +import base64 |
| 6 | +import os |
| 7 | +import threading |
| 8 | +import time |
| 9 | + |
| 10 | +import torch |
| 11 | +from diffusers import DiffusionPipeline |
| 12 | + |
| 13 | +from comps import ( |
| 14 | + CustomLogger, |
| 15 | + SDInputs, |
| 16 | + SDOutputs, |
| 17 | + ServiceType, |
| 18 | + opea_microservices, |
| 19 | + register_microservice, |
| 20 | + register_statistics, |
| 21 | + statistics_dict, |
| 22 | +) |
| 23 | + |
| 24 | +logger = CustomLogger("text2image") |
| 25 | +pipe = None |
| 26 | +args = None |
| 27 | +initialization_lock = threading.Lock() |
| 28 | +initialized = False |
| 29 | + |
| 30 | + |
| 31 | +def initialize(): |
| 32 | + global pipe, args, initialized |
| 33 | + with initialization_lock: |
| 34 | + if not initialized: |
| 35 | + # initialize model and tokenizer |
| 36 | + if os.getenv("MODEL", None): |
| 37 | + args.model_name_or_path = os.getenv("MODEL") |
| 38 | + kwargs = {} |
| 39 | + if args.bf16: |
| 40 | + kwargs["torch_dtype"] = torch.bfloat16 |
| 41 | + if not args.token: |
| 42 | + args.token = os.getenv("HF_TOKEN") |
| 43 | + if args.device == "hpu": |
| 44 | + kwargs.update( |
| 45 | + { |
| 46 | + "use_habana": True, |
| 47 | + "use_hpu_graphs": args.use_hpu_graphs, |
| 48 | + "gaudi_config": "Habana/stable-diffusion", |
| 49 | + "token": args.token, |
| 50 | + } |
| 51 | + ) |
| 52 | + if "stable-diffusion-3" in args.model_name_or_path: |
| 53 | + from optimum.habana.diffusers import GaudiStableDiffusion3Pipeline |
| 54 | + |
| 55 | + pipe = GaudiStableDiffusion3Pipeline.from_pretrained( |
| 56 | + args.model_name_or_path, |
| 57 | + **kwargs, |
| 58 | + ) |
| 59 | + elif "stable-diffusion" in args.model_name_or_path.lower() or "flux" in args.model_name_or_path.lower(): |
| 60 | + from optimum.habana.diffusers import AutoPipelineForText2Image |
| 61 | + |
| 62 | + pipe = AutoPipelineForText2Image.from_pretrained( |
| 63 | + args.model_name_or_path, |
| 64 | + **kwargs, |
| 65 | + ) |
| 66 | + else: |
| 67 | + raise NotImplementedError( |
| 68 | + "Only support stable-diffusion, stable-diffusion-xl, stable-diffusion-3 and flux now, " |
| 69 | + + f"model {args.model_name_or_path} not supported." |
| 70 | + ) |
| 71 | + elif args.device == "cpu": |
| 72 | + pipe = DiffusionPipeline.from_pretrained(args.model_name_or_path, token=args.token, **kwargs) |
| 73 | + else: |
| 74 | + raise NotImplementedError(f"Only support cpu and hpu device now, device {args.device} not supported.") |
| 75 | + logger.info("Stable Diffusion model initialized.") |
| 76 | + initialized = True |
| 77 | + |
| 78 | + |
| 79 | +@register_microservice( |
| 80 | + name="opea_service@text2image", |
| 81 | + service_type=ServiceType.TEXT2IMAGE, |
| 82 | + endpoint="/v1/text2image", |
| 83 | + host="0.0.0.0", |
| 84 | + port=9379, |
| 85 | + input_datatype=SDInputs, |
| 86 | + output_datatype=SDOutputs, |
| 87 | +) |
| 88 | +@register_statistics(names=["opea_service@text2image"]) |
| 89 | +def text2image(input: SDInputs): |
| 90 | + initialize() |
| 91 | + start = time.time() |
| 92 | + prompt = input.prompt |
| 93 | + num_images_per_prompt = input.num_images_per_prompt |
| 94 | + |
| 95 | + generator = torch.manual_seed(args.seed) |
| 96 | + images = pipe(prompt, generator=generator, num_images_per_prompt=num_images_per_prompt).images |
| 97 | + image_path = os.path.join(os.getcwd(), prompt.strip().replace(" ", "_").replace("/", "")) |
| 98 | + os.makedirs(image_path, exist_ok=True) |
| 99 | + results = [] |
| 100 | + for i, image in enumerate(images): |
| 101 | + save_path = os.path.join(image_path, f"image_{i+1}.png") |
| 102 | + image.save(save_path) |
| 103 | + with open(save_path, "rb") as f: |
| 104 | + bytes = f.read() |
| 105 | + b64_str = base64.b64encode(bytes).decode() |
| 106 | + results.append(b64_str) |
| 107 | + statistics_dict["opea_service@text2image"].append_latency(time.time() - start, None) |
| 108 | + return SDOutputs(images=results) |
| 109 | + |
| 110 | + |
| 111 | +if __name__ == "__main__": |
| 112 | + parser = argparse.ArgumentParser() |
| 113 | + parser.add_argument("--model_name_or_path", type=str, default="stabilityai/stable-diffusion-3-medium-diffusers") |
| 114 | + parser.add_argument("--use_hpu_graphs", default=False, action="store_true") |
| 115 | + parser.add_argument("--device", type=str, default="cpu") |
| 116 | + parser.add_argument("--token", type=str, default=None) |
| 117 | + parser.add_argument("--seed", type=int, default=42) |
| 118 | + parser.add_argument("--bf16", action="store_true") |
| 119 | + |
| 120 | + args = parser.parse_args() |
| 121 | + |
| 122 | + logger.info("Text2image server started.") |
| 123 | + opea_microservices["opea_service@text2image"].start() |
0 commit comments