|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Extra gRPC server for OpenVoice models. |
| 4 | +""" |
| 5 | +from concurrent import futures |
| 6 | + |
| 7 | +import argparse |
| 8 | +import signal |
| 9 | +import sys |
| 10 | +import os |
| 11 | +import torch |
| 12 | +from openvoice import se_extractor |
| 13 | +from openvoice.api import ToneColorConverter |
| 14 | +from melo.api import TTS |
| 15 | + |
| 16 | +import time |
| 17 | +import backend_pb2 |
| 18 | +import backend_pb2_grpc |
| 19 | + |
| 20 | +import grpc |
| 21 | + |
| 22 | + |
| 23 | +_ONE_DAY_IN_SECONDS = 60 * 60 * 24 |
| 24 | + |
| 25 | +# If MAX_WORKERS are specified in the environment use it, otherwise default to 1 |
| 26 | +MAX_WORKERS = int(os.environ.get('PYTHON_GRPC_MAX_WORKERS', '1')) |
| 27 | + |
| 28 | +# Implement the BackendServicer class with the service methods |
| 29 | +class BackendServicer(backend_pb2_grpc.BackendServicer): |
| 30 | + """ |
| 31 | + A gRPC servicer for the backend service. |
| 32 | +
|
| 33 | + This class implements the gRPC methods for the backend service, including Health, LoadModel, and Embedding. |
| 34 | + """ |
| 35 | + def Health(self, request, context): |
| 36 | + """ |
| 37 | + A gRPC method that returns the health status of the backend service. |
| 38 | +
|
| 39 | + Args: |
| 40 | + request: A HealthRequest object that contains the request parameters. |
| 41 | + context: A grpc.ServicerContext object that provides information about the RPC. |
| 42 | +
|
| 43 | + Returns: |
| 44 | + A Reply object that contains the health status of the backend service. |
| 45 | + """ |
| 46 | + return backend_pb2.Reply(message=bytes("OK", 'utf-8')) |
| 47 | + |
| 48 | + def LoadModel(self, request, context): |
| 49 | + """ |
| 50 | + A gRPC method that loads a model into memory. |
| 51 | +
|
| 52 | + Args: |
| 53 | + request: A LoadModelRequest object that contains the request parameters. |
| 54 | + context: A grpc.ServicerContext object that provides information about the RPC. |
| 55 | +
|
| 56 | + Returns: |
| 57 | + A Result object that contains the result of the LoadModel operation. |
| 58 | + """ |
| 59 | + model_name = request.Model |
| 60 | + try: |
| 61 | + |
| 62 | + self.clonedVoice = False |
| 63 | + # Assume directory from request.ModelFile. |
| 64 | + # Only if request.LoraAdapter it's not an absolute path |
| 65 | + if request.AudioPath and request.ModelFile != "" and not os.path.isabs(request.AudioPath): |
| 66 | + # get base path of modelFile |
| 67 | + modelFileBase = os.path.dirname(request.ModelFile) |
| 68 | + request.AudioPath = os.path.join(modelFileBase, request.AudioPath) |
| 69 | + if request.AudioPath != "": |
| 70 | + self.clonedVoice = True |
| 71 | + |
| 72 | + self.modelpath = request.ModelFile |
| 73 | + self.speaker = request.Type |
| 74 | + self.ClonedVoicePath = request.AudioPath |
| 75 | + |
| 76 | + ckpt_converter = request.Model+'/converter' |
| 77 | + device = "cuda:0" if torch.cuda.is_available() else "cpu" |
| 78 | + self.device = device |
| 79 | + self.tone_color_converter = None |
| 80 | + if self.clonedVoice: |
| 81 | + self.tone_color_converter = ToneColorConverter(f'{ckpt_converter}/config.json', device=device) |
| 82 | + self.tone_color_converter.load_ckpt(f'{ckpt_converter}/checkpoint.pth') |
| 83 | + |
| 84 | + except Exception as err: |
| 85 | + return backend_pb2.Result(success=False, message=f"Unexpected {err=}, {type(err)=}") |
| 86 | + |
| 87 | + return backend_pb2.Result(message="Model loaded successfully", success=True) |
| 88 | + |
| 89 | + def TTS(self, request, context): |
| 90 | + model_name = request.model |
| 91 | + if model_name == "": |
| 92 | + return backend_pb2.Result(success=False, message="request.model is required") |
| 93 | + try: |
| 94 | + # Speed is adjustable |
| 95 | + speed = 1.0 |
| 96 | + model = TTS(language=request.voice, device=self.device) |
| 97 | + speaker_ids = model.hps.data.spk2id |
| 98 | + speaker_key = self.speaker |
| 99 | + modelpath = self.modelpath |
| 100 | + for s in speaker_ids.keys(): |
| 101 | + print(f"Speaker: {s} - ID: {speaker_ids[s]}") |
| 102 | + speaker_id = speaker_ids[speaker_key] |
| 103 | + speaker_key = speaker_key.lower().replace('_', '-') |
| 104 | + source_se = torch.load(f'{modelpath}/base_speakers/ses/{speaker_key}.pth', map_location=self.device) |
| 105 | + model.tts_to_file(request.text, speaker_id, request.dst, speed=speed) |
| 106 | + if self.clonedVoice: |
| 107 | + reference_speaker = self.ClonedVoicePath |
| 108 | + target_se, audio_name = se_extractor.get_se(reference_speaker, self.tone_color_converter, vad=False) |
| 109 | + # Run the tone color converter |
| 110 | + encode_message = "@MyShell" |
| 111 | + self.tone_color_converter.convert( |
| 112 | + audio_src_path=request.dst, |
| 113 | + src_se=source_se, |
| 114 | + tgt_se=target_se, |
| 115 | + output_path=request.dst, |
| 116 | + message=encode_message) |
| 117 | + |
| 118 | + print("[OpenVoice] TTS generated!", file=sys.stderr) |
| 119 | + print("[OpenVoice] TTS saved to", request.dst, file=sys.stderr) |
| 120 | + print(request, file=sys.stderr) |
| 121 | + except Exception as err: |
| 122 | + return backend_pb2.Result(success=False, message=f"Unexpected {err=}, {type(err)=}") |
| 123 | + return backend_pb2.Result(success=True) |
| 124 | + |
| 125 | +def serve(address): |
| 126 | + server = grpc.server(futures.ThreadPoolExecutor(max_workers=MAX_WORKERS)) |
| 127 | + backend_pb2_grpc.add_BackendServicer_to_server(BackendServicer(), server) |
| 128 | + server.add_insecure_port(address) |
| 129 | + server.start() |
| 130 | + print("[OpenVoice] Server started. Listening on: " + address, file=sys.stderr) |
| 131 | + |
| 132 | + # Define the signal handler function |
| 133 | + def signal_handler(sig, frame): |
| 134 | + print("[OpenVoice] Received termination signal. Shutting down...") |
| 135 | + server.stop(0) |
| 136 | + sys.exit(0) |
| 137 | + |
| 138 | + # Set the signal handlers for SIGINT and SIGTERM |
| 139 | + signal.signal(signal.SIGINT, signal_handler) |
| 140 | + signal.signal(signal.SIGTERM, signal_handler) |
| 141 | + |
| 142 | + try: |
| 143 | + while True: |
| 144 | + time.sleep(_ONE_DAY_IN_SECONDS) |
| 145 | + except KeyboardInterrupt: |
| 146 | + server.stop(0) |
| 147 | + |
| 148 | +if __name__ == "__main__": |
| 149 | + parser = argparse.ArgumentParser(description="Run the gRPC server.") |
| 150 | + parser.add_argument( |
| 151 | + "--addr", default="localhost:50051", help="The address to bind the server to." |
| 152 | + ) |
| 153 | + args = parser.parse_args() |
| 154 | + print(f"[OpenVoice] startup: {args}", file=sys.stderr) |
| 155 | + serve(args.addr) |
0 commit comments