File size: 2,231 Bytes
0a4019a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import os
import uuid
from django.http import FileResponse
from rest_framework import status
from rest_framework.response import Response
from rest_framework.generics import CreateAPIView
from TTS.api import TTS
from .serializers import TextToSpeechSerializer

class TextToSpeechCreateView(CreateAPIView):
    serializer_class = TextToSpeechSerializer

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            text = serializer.validated_data.get("text")
            speaker_wav = serializer.validated_data.get("speaker_wav")
            language = serializer.validated_data.get("language")
            output_filename = f"output_{uuid.uuid4()}.wav"

            try:
                # Save the uploaded speaker file to a temporary location
                speaker_file_path = os.path.join("/tmp", speaker_wav.name)
                with open(speaker_file_path, "wb") as destination:
                    for chunk in speaker_wav.chunks():
                        destination.write(chunk)

                # Generate speech using tts.tts_to_file
                tts = TTS("tts_models/multilingual/multi-dataset/xtts_v2", gpu=False)
                tts.tts_to_file(text=text, file_path=output_filename, speaker_wav=speaker_file_path, language=language)

                # Define a function to delete the output file
                def file_iterator(file_name):
                    with open(file_name, 'rb') as f:
                        yield from f

                    # Delete the file after sending it
                    try:
                        os.remove(file_name)
                    except Exception as e:
                        # You might want to log this error
                        pass

                # Use the file_iterator to create a FileResponse
                response = FileResponse(file_iterator(output_filename), as_attachment=True, content_type='audio/wav')
                return response

            except Exception as e:
                return Response({"error": str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)