|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +This is an extra gRPC server of LocalAI for NeuTTSAir |
| 4 | +""" |
| 5 | +from concurrent import futures |
| 6 | +import time |
| 7 | +import argparse |
| 8 | +import signal |
| 9 | +import sys |
| 10 | +import os |
| 11 | +import backend_pb2 |
| 12 | +import backend_pb2_grpc |
| 13 | +import torch |
| 14 | +from neuttsair.neutts import NeuTTSAir |
| 15 | +import soundfile as sf |
| 16 | + |
| 17 | +import grpc |
| 18 | + |
| 19 | +def is_float(s): |
| 20 | + """Check if a string can be converted to float.""" |
| 21 | + try: |
| 22 | + float(s) |
| 23 | + return True |
| 24 | + except ValueError: |
| 25 | + return False |
| 26 | +def is_int(s): |
| 27 | + """Check if a string can be converted to int.""" |
| 28 | + try: |
| 29 | + int(s) |
| 30 | + return True |
| 31 | + except ValueError: |
| 32 | + return False |
| 33 | + |
| 34 | +_ONE_DAY_IN_SECONDS = 60 * 60 * 24 |
| 35 | + |
| 36 | +# If MAX_WORKERS are specified in the environment use it, otherwise default to 1 |
| 37 | +MAX_WORKERS = int(os.environ.get('PYTHON_GRPC_MAX_WORKERS', '1')) |
| 38 | + |
| 39 | +# Implement the BackendServicer class with the service methods |
| 40 | +class BackendServicer(backend_pb2_grpc.BackendServicer): |
| 41 | + """ |
| 42 | + BackendServicer is the class that implements the gRPC service |
| 43 | + """ |
| 44 | + def Health(self, request, context): |
| 45 | + return backend_pb2.Reply(message=bytes("OK", 'utf-8')) |
| 46 | + def LoadModel(self, request, context): |
| 47 | + |
| 48 | + # Get device |
| 49 | + # device = "cuda" if request.CUDA else "cpu" |
| 50 | + if torch.cuda.is_available(): |
| 51 | + print("CUDA is available", file=sys.stderr) |
| 52 | + device = "cuda" |
| 53 | + else: |
| 54 | + print("CUDA is not available", file=sys.stderr) |
| 55 | + device = "cpu" |
| 56 | + mps_available = hasattr(torch.backends, "mps") and torch.backends.mps.is_available() |
| 57 | + if mps_available: |
| 58 | + device = "mps" |
| 59 | + if not torch.cuda.is_available() and request.CUDA: |
| 60 | + return backend_pb2.Result(success=False, message="CUDA is not available") |
| 61 | + |
| 62 | + |
| 63 | + options = request.Options |
| 64 | + |
| 65 | + # empty dict |
| 66 | + self.options = {} |
| 67 | + self.ref_text = None |
| 68 | + |
| 69 | + # The options are a list of strings in this form optname:optvalue |
| 70 | + # We are storing all the options in a dict so we can use it later when |
| 71 | + # generating the images |
| 72 | + for opt in options: |
| 73 | + if ":" not in opt: |
| 74 | + continue |
| 75 | + key, value = opt.split(":") |
| 76 | + # if value is a number, convert it to the appropriate type |
| 77 | + if is_float(value): |
| 78 | + value = float(value) |
| 79 | + elif is_int(value): |
| 80 | + value = int(value) |
| 81 | + elif value.lower() in ["true", "false"]: |
| 82 | + value = value.lower() == "true" |
| 83 | + self.options[key] = value |
| 84 | + |
| 85 | + codec_repo = "neuphonic/neucodec" |
| 86 | + if "codec_repo" in self.options: |
| 87 | + codec_repo = self.options["codec_repo"] |
| 88 | + del self.options["codec_repo"] |
| 89 | + if "ref_text" in self.options: |
| 90 | + self.ref_text = self.options["ref_text"] |
| 91 | + del self.options["ref_text"] |
| 92 | + |
| 93 | + self.AudioPath = None |
| 94 | + |
| 95 | + if os.path.isabs(request.AudioPath): |
| 96 | + self.AudioPath = request.AudioPath |
| 97 | + elif request.AudioPath and request.ModelFile != "" and not os.path.isabs(request.AudioPath): |
| 98 | + # get base path of modelFile |
| 99 | + modelFileBase = os.path.dirname(request.ModelFile) |
| 100 | + # modify LoraAdapter to be relative to modelFileBase |
| 101 | + self.AudioPath = os.path.join(modelFileBase, request.AudioPath) |
| 102 | + try: |
| 103 | + print("Preparing models, please wait", file=sys.stderr) |
| 104 | + self.model = NeuTTSAir(backbone_repo=request.Model, backbone_device=device, codec_repo=codec_repo, codec_device=device) |
| 105 | + except Exception as err: |
| 106 | + return backend_pb2.Result(success=False, message=f"Unexpected {err=}, {type(err)=}") |
| 107 | + # Implement your logic here for the LoadModel service |
| 108 | + # Replace this with your desired response |
| 109 | + return backend_pb2.Result(message="Model loaded successfully", success=True) |
| 110 | + |
| 111 | + def TTS(self, request, context): |
| 112 | + try: |
| 113 | + kwargs = {} |
| 114 | + |
| 115 | + # add options to kwargs |
| 116 | + kwargs.update(self.options) |
| 117 | + |
| 118 | + ref_codes = self.model.encode_reference(self.AudioPath) |
| 119 | + |
| 120 | + wav = self.model.infer(request.text, ref_codes, self.ref_text) |
| 121 | + |
| 122 | + sf.write(request.dst, wav, 24000) |
| 123 | + except Exception as err: |
| 124 | + return backend_pb2.Result(success=False, message=f"Unexpected {err=}, {type(err)=}") |
| 125 | + return backend_pb2.Result(success=True) |
| 126 | + |
| 127 | +def serve(address): |
| 128 | + server = grpc.server(futures.ThreadPoolExecutor(max_workers=MAX_WORKERS), |
| 129 | + options=[ |
| 130 | + ('grpc.max_message_length', 50 * 1024 * 1024), # 50MB |
| 131 | + ('grpc.max_send_message_length', 50 * 1024 * 1024), # 50MB |
| 132 | + ('grpc.max_receive_message_length', 50 * 1024 * 1024), # 50MB |
| 133 | + ]) |
| 134 | + backend_pb2_grpc.add_BackendServicer_to_server(BackendServicer(), server) |
| 135 | + server.add_insecure_port(address) |
| 136 | + server.start() |
| 137 | + print("Server started. Listening on: " + address, file=sys.stderr) |
| 138 | + |
| 139 | + # Define the signal handler function |
| 140 | + def signal_handler(sig, frame): |
| 141 | + print("Received termination signal. Shutting down...") |
| 142 | + server.stop(0) |
| 143 | + sys.exit(0) |
| 144 | + |
| 145 | + # Set the signal handlers for SIGINT and SIGTERM |
| 146 | + signal.signal(signal.SIGINT, signal_handler) |
| 147 | + signal.signal(signal.SIGTERM, signal_handler) |
| 148 | + |
| 149 | + try: |
| 150 | + while True: |
| 151 | + time.sleep(_ONE_DAY_IN_SECONDS) |
| 152 | + except KeyboardInterrupt: |
| 153 | + server.stop(0) |
| 154 | + |
| 155 | +if __name__ == "__main__": |
| 156 | + parser = argparse.ArgumentParser(description="Run the gRPC server.") |
| 157 | + parser.add_argument( |
| 158 | + "--addr", default="localhost:50051", help="The address to bind the server to." |
| 159 | + ) |
| 160 | + args = parser.parse_args() |
| 161 | + |
| 162 | + serve(args.addr) |
0 commit comments