File size: 8,036 Bytes
1501522
 
 
 
d12fcfd
bd994e8
1501522
 
 
 
 
 
 
2246687
1501522
2246687
 
1501522
 
db071e8
1501522
 
 
 
 
2246687
d12fcfd
2246687
 
 
 
 
 
 
 
 
 
1501522
bd994e8
1501522
 
 
 
 
 
bd994e8
2246687
bd994e8
1501522
 
2246687
 
 
 
d12fcfd
2246687
d12fcfd
1501522
d4d07bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d12fcfd
d4d07bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1501522
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd994e8
1501522
74acf19
 
 
 
 
bd994e8
 
 
 
 
74acf19
 
 
 
 
 
 
 
bd994e8
db071e8
 
bd994e8
 
 
1501522
bd994e8
 
1501522
 
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Process;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use RuntimeException;

class EdgeTtsService
{
    public function synthesize(string $text, ?string $language = null, ?string $gender = null, string $engine = 'edge'): string
    {
        $timeoutSec = max(30, (int) config('services.tts.timeout', 240));
        
        $directory = storage_path('app/public/tts');
        if (! is_dir($directory)) {
            mkdir($directory, 0777, true);
        }

        $filename = 'tts_'.now()->format('Ymd_His').'_'.Str::lower(Str::random(8)).'.mp3';
        $absolutePath = $directory.DIRECTORY_SEPARATOR.$filename;

        if ($engine === 'kokoro') {
            return $this->synthesizeHuggingFace($text, $language, $gender, $absolutePath, $filename, $timeoutSec);
        }

        return $this->synthesizeEdge($text, $language, $gender, $absolutePath, $filename, $timeoutSec);
    }

    private function synthesizeEdge(string $text, ?string $language, ?string $gender, string $absolutePath, string $filename, int $timeoutSec): string
    {
        $voice = $this->resolveVoice($language, $gender);
        $binary = $this->resolveBinary();

        $result = Process::timeout($timeoutSec)->run([
            $binary,
            '--voice', $voice,
            '--text', $text,
            '--write-media', $absolutePath,
        ]);

        if (! $result->successful()) {
            $error = trim($result->errorOutput() ?: $result->output());
            Log::error('Edge-TTS error: ' . $error);
            throw new RuntimeException('Edge-TTS gagal: ' . $error);
        }

        chmod($absolutePath, 0666);
        return Storage::url('tts/'.$filename);
    }

    private function synthesizeHuggingFace(string $text, ?string $language, ?string $gender, string $absolutePath, string $filename, int $timeoutSec): string
    {
        $token = config('services.huggingface.api_token');

        // Model candidates: Kokoro (multilingual, high quality) → MMS language-specific fallback
        $models = ($language === 'id')
            ? ['hexgrad/Kokoro-82M', 'facebook/mms-tts-ind']
            : ['hexgrad/Kokoro-82M', 'facebook/mms-tts-eng'];

        // Kokoro needs a voice hint via the inputs array; other models just need plain text
        $payloads = [
            'hexgrad/Kokoro-82M' => [
                'inputs' => $text,
                'parameters' => [
                    'voice' => ($language === 'id')
                        ? (($gender === 'male') ? 'im' : 'if')
                        : (($gender === 'male') ? 'am_michael' : 'af_heart'),
                ],
            ],
            'facebook/mms-tts-ind' => ['inputs' => $text],
            'facebook/mms-tts-eng' => ['inputs' => $text],
        ];

        $deadline = time() + $timeoutSec;
        $lastError = 'Unknown HF-TTS error';

        foreach ($models as $model) {
            $url     = "https://router.huggingface.co/hf-inference/models/{$model}";
            $payload = $payloads[$model] ?? ['inputs' => $text];

            while (time() < $deadline) {
                $response = Http::withToken($token)
                    ->timeout(min(60, $deadline - time()))
                    ->accept('audio/flac, audio/wav, audio/mpeg, application/octet-stream')
                    ->post($url, $payload);

                $status = $response->status();

                // Binary audio returned directly
                if ($status === 200) {
                    $body = $response->body();
                    if (strlen($body) > 1024) {
                        // Persist; extension stays .mp3 but content may be flac/wav — player handles it
                        file_put_contents($absolutePath, $body);
                        chmod($absolutePath, 0666);
                        return Storage::url('tts/' . $filename);
                    }
                    // Tiny body = likely JSON error wrapped in 200
                    $lastError = $response->json('error') ?? 'Empty audio body';
                    Log::warning("HF-TTS [{$model}] 200 but empty body: {$lastError}");
                    break; // try next model
                }

                // Model still loading — wait and retry
                if ($status === 503) {
                    $wait = (int) ($response->json('estimated_time') ?? 5);
                    $wait = max(3, min($wait, 20));
                    Log::info("HF-TTS [{$model}] loading, retrying in {$wait}s…");
                    sleep($wait);
                    continue;
                }

                // Rate limit — short back-off then retry current model
                if ($status === 429) {
                    Log::warning("HF-TTS [{$model}] rate limited, waiting 10s…");
                    sleep(10);
                    continue;
                }

                // Any other error: log and try next model
                $lastError = $response->json('error') ?? $response->body();
                Log::warning("HF-TTS [{$model}] HTTP {$status}: {$lastError}");
                break;
            }
        }

        // All HF models failed — fall back to Edge TTS
        Log::error("HF-TTS all models failed: {$lastError} — falling back to Edge TTS");
        return $this->synthesizeEdge($text, $language, $gender, $absolutePath, $filename, $timeoutSec);
    }

    public function languageOptions(): array
    {
        return [
            'id' => 'Indonesia',
            'en' => 'English (US)',
            'ja' => 'Japanese',
            'ko' => 'Korean',
            'es' => 'Spanish',
        ];
    }

    public function genderOptions(): array
    {
        return [
            'female' => 'Female',
            'male' => 'Male',
        ];
    }

    private function resolveVoice(?string $language, ?string $gender): string
    {
        $language = $language ?: 'id';
        $gender = $gender ?: 'female';

        $catalog = $this->voiceCatalog();

        if (isset($catalog[$language][$gender])) {
            return $catalog[$language][$gender];
        }

        return (string) config('services.edge_tts.voice', 'id-ID-GadisNeural');
    }

    private function voiceCatalog(): array
    {
        return [
            'id' => [
                'female' => 'id-ID-GadisNeural',
                'male' => 'id-ID-ArdiNeural',
            ],
            'en' => [
                'female' => 'en-US-JennyNeural',
                'male' => 'en-US-GuyNeural',
            ],
            'ja' => [
                'female' => 'ja-JP-NanamiNeural',
                'male' => 'ja-JP-KeitaNeural',
            ],
            'ko' => [
                'female' => 'ko-KR-SunHiNeural',
                'male' => 'ko-KR-InJoonNeural',
            ],
            'es' => [
                'female' => 'es-ES-ElviraNeural',
                'male' => 'es-ES-AlvaroNeural',
            ],
        ];
    }

    private function resolveBinary(): string
    {
        $configuredBinary = trim((string) config('services.edge_tts.binary', ''));
        $candidates = [
            $configuredBinary,
            'edge-tts',
            base_path('.venv-edge-tts/bin/edge-tts'),
            '/usr/local/bin/edge-tts',
            '/usr/bin/edge-tts',
            '/home/www-data/.local/bin/edge-tts',
        ];

        foreach ($candidates as $candidate) {
            if ($candidate === '') {
                continue;
            }

            $check = Process::timeout(5)->run([$candidate, '--version']);
            if ($check->successful()) {
                return $candidate;
            }
        }

        $find = Process::timeout(5)->run(['which', 'edge-tts']);
        if ($find->successful() && filled($find->output())) {
            return trim($find->output());
        }

        throw new RuntimeException('edge-tts belum terinstall atau tidak ditemukan di PATH.');
    }
}