File size: 12,073 Bytes
5f32fbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
<?php

namespace App\Http\Controllers;

use App\Helpers\Classes\Helper;
use App\Models\OpenAIGenerator;
use App\Models\RateLimit;
use App\Models\Setting;
use App\Models\SettingTwo;
use App\Models\UserOpenai;
use App\Services\Ai\TTS\AzureService;
use Carbon\Carbon;
use Exception;
use FFMpeg\FFMpeg;
use FFMpeg\Format\Audio\Mp3;
use Google\Cloud\TextToSpeech\V1\AudioConfig;
use Google\Cloud\TextToSpeech\V1\AudioEncoding;
use Google\Cloud\TextToSpeech\V1\SsmlVoiceGender;
use Google\Cloud\TextToSpeech\V1\SynthesisInput;
use Google\Cloud\TextToSpeech\V1\TextToSpeechClient;
use Google\Cloud\TextToSpeech\V1\VoiceSelectionParams;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class TTSController extends Controller
{
    public function generateSpeech(Request $request)
    {
        if (Helper::appIsDemo()) {
            $data = [
                'errors' => [__('This feature is disabled in Demo version.')],
            ];

            return response()->json($data, 429);
        }
        $settings_two = SettingTwo::first();
        if ($settings_two->daily_voice_limit_enabled) {
            if (Helper::appIsDemo()) {
                $msg = __('You have reached the maximum number of voice generation allowed on the demo.');
            } else {
                $msg = __('You have reached the maximum number of voice generation allowed.');
            }
            $ipAddress = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : request()->ip();
            $db_ip_address = RateLimit::where('ip_address', $ipAddress)->where('type', 'voice')->first();
            if ($db_ip_address) {
                if (now()->diffInDays(Carbon::parse($db_ip_address->last_attempt_at)->format('Y-m-d')) > 0) {
                    $db_ip_address->attempts = 0;
                }
            } else {
                $db_ip_address = new RateLimit(['ip_address' => $ipAddress]);
            }

            if ($db_ip_address->attempts >= $settings_two->allowed_voice_count) {
                $data = [
                    'errors' => [$msg],
                ];

                return response()->json($data, 429);
            } else {
                $db_ip_address->attempts++;
                $db_ip_address->type = 'voice';
                $db_ip_address->last_attempt_at = now();
                $db_ip_address->save();
            }
        }

        $settings = Setting::first();

        //If speeches are null
        if ($request->speeches == '[]') {
            $data = [
                'errors' => [__('Please provide inputs.')],
            ];

            return response()->json($data, 419);
        }

        $speeches = json_decode($request->speeches, true);

        //Variables and arrays for store
        $wordCount = 0;
        $langsAndVoices = [];

        // Convert the text to SSML format
        // [{"voice":"eu-ES-Standard-A","lang":"eu-ES","content":""},{"voice":"eu-ES-Standard-A","lang":"eu-ES","content":""}]
        //$ssml = '<speak>';

        $resAudio = '';
        // check if one of the speech is azure
        if (in_array('azure', array_column($speeches, 'platform'))) {
            $azureService = new AzureService;
        } else {
            $azureService = null;
        }
        $user = Auth::user();
        foreach ($speeches as $speech) {
            $model = '';
            if ($speech['platform'] == 'google') {
                $model = 'google';
                //If gcs credentials are empty
                if (empty($settings->gcs_file) || empty($settings->gcs_name)) {
                    $data = [
                        'errors' => ['Google TTS credentials wrong or missing!'],
                    ];

                    return response()->json($data, 419);
                }

                try {
                    $client = new TextToSpeechClient([
                        'credentials' => storage_path($settings->gcs_file),
                        'project_id'  => $settings->gcs_name,
                    ]);
                } catch (Exception $e) {
                    // Connection error occurred
                    $data = [
                        'errors' => ['Failed to connect to Google TTS service: ' . $e->getMessage()],
                    ];

                    return response()->json($data, 419);
                }

                $ssml = '<speak>';
                $ssml .= sprintf(
                    '<lang xml:lang="%3$s">
                        <prosody rate="%4$s">
                            <voice name="%1$s">%2$s</voice>
                            <break time="%5$ss"/>
                        </prosody>
                    </lang>',
                    $speech['voice'],
                    $speech['content'],
                    $speech['lang'],
                    $speech['pace'],
                    $speech['break'],
                );

                $ssml .= '</speak>';

                $langsAndVoices['language'][] = $speech['lang'];
                $langsAndVoices['voices'][] = $speech['voice'];

                // Set the SSML as the synthesis input
                $synthesisInputSsml = (new SynthesisInput)
                    ->setSsml($ssml);

                // Build the voice request, select the language code ("en-US") and the ssml voice gender

                $voice = (new VoiceSelectionParams)
                    ->setLanguageCode('en-US')
                    ->setSsmlGender(SsmlVoiceGender::FEMALE);

                // Effects profile
                // $effectsProfileId = 'telephony-class-application';

                // select the type of audio file you want returned
                $audioConfig = (new AudioConfig)
                    ->setAudioEncoding(AudioEncoding::MP3);
                //->setEffectsProfileId(array($effectsProfileId));

                // Perform text-to-speech request on the SSML input with selected voice parameters and audio file type
                $response = $client->synthesizeSpeech($synthesisInputSsml, $voice, $audioConfig);
                $audioContent = $response->getAudioContent();
                $resAudio = $resAudio . $audioContent;
            } elseif ($speech['platform'] == 'openai') {
                $model = $speech['pace'];
                $settings = Setting::first();
                if ($settings?->user_api_option) {
                    $apiKeys = explode(',', auth()->user()?->api_keys);
                } else {
                    $apiKeys = explode(',', $settings?->openai_api_secret);
                }
                $apiKey = $apiKeys[array_rand($apiKeys)];

                //Variables and arrays for store
                $wordCount = 0;
                $langsAndVoices = [];

                $content = $speech['content'];

                $client_ = new Client;

                $langsAndVoices['language'][] = $speech['lang'];
                $langsAndVoices['voices'][] = $speech['voice'];

                $response = $client_->request('POST', 'https://api.openai.com/v1/audio/speech', [
                    'headers' => [
                        'Authorization' => 'Bearer ' . $apiKey,
                        'Content-Type'  => 'application/json',
                    ],
                    'json' => [
                        'language' => $speech['language'],
                        'model'    => $speech['pace'],
                        'input'    => $speech['content'],
                        'voice'    => $speech['voice'],
                    ],
                ]);

                // $tempInputFile = tempnam(sys_get_temp_dir(), 'input_mp3');
                // file_put_contents($tempInputFile, $response->getBody());

                // // Initialize FFMpeg
                // $ffmpeg = FFMpeg::create();

                // // Open the input file
                // $audio = $ffmpeg->open($tempInputFile);

                // // Convert the audio to 128 kbps MP3
                // $format = new Mp3();
                // $format->setAudioKiloBitrate(128);

                // // Save the converted audio to a new file
                // $tempOutputFile = sys_get_temp_dir() . '/output.mp3';
                // $audio->save($format, $tempOutputFile);

                // // Read the converted MP3 data as a string
                // $convertedMp3DataAsString = file_get_contents($tempOutputFile);

                // // Clean up temporary files
                // unlink($tempInputFile);
                // unlink($tempOutputFile);

                $resAudio = $resAudio . $response->getBody();
            } elseif ($speech['platform'] == 'elevenlabs') {
                $model = 'elevenlabs';
                $settings_two = SettingTwo::first();
                $apiKey = $settings_two->elevenlabs_api_key;

                $content = $speech['content'];

                $client = new Client;

                $response = $client->request('POST', 'https://api.elevenlabs.io/v1/text-to-speech/' . $speech['voice'], [
                    'headers' => [
                        'Content-Type' => 'application/json',
                        'xi-api-key'   => $apiKey,
                    ],
                    'json' => [
                        'text'           => $content,
                        'model_id'       => 'eleven_multilingual_v2',
                        'voice_settings' => [
                            'similarity_boost'  => 0.75,
                            'stability'         => 0.95,
                            'style'             => $speech['pace'] / 100,
                            'use_speaker_boost' => true,
                        ],
                    ],
                ]);

                $langsAndVoices['language'][] = $speech['lang'];
                $langsAndVoices['voices'][] = $speech['name'];

                $resAudio = $resAudio . $response->getBody();
            } elseif ($speech['platform'] == 'azure') {
                $model = 'azure';
                $voice_id = $speech['voice'];
                $text = $speech['content'];
                $lang = $speech['lang'];
                $langsAndVoices['language'][] = $lang;
                $langsAndVoices['voices'][] = $speech['name'];

                $resAudio = $azureService?->synthesizeSpeech($voice_id, $text, $lang);
            }
            $wordCount += countWords($speech['content']);
            userCreditDecreaseForWord($user, $wordCount, $model);
        }

        $ai = OpenAIGenerator::whereSlug('ai_voiceover')->first();

        $audioName = $user->id . '-' . Str::random(20) . '.mp3';
        Storage::disk('public')->put($audioName, $resAudio);

        if (isset($request->preview)) {
            return response()->json(['audioPath' => '/uploads/' . $audioName, 'output' => '<div class="data-audio" data-audio="/uploads/' . $audioName . '"><div class="audio-preview"></div></div>']);
        }

        //Save in workbook
        $entry = new UserOpenai;
        $entry->team_id = $user->team_id;
        $entry->title = $request->workbook_title;
        $entry->slug = Str::random(20) . Str::slug($user->fullName()) . '-workbook';
        $entry->user_id = $user->id;
        $entry->openai_id = $ai->id;
        $entry->input = $request->speeches;
        $entry->response = json_encode($langsAndVoices);
        $entry->output = $audioName;
        $entry->hash = Str::random(256);
        $entry->credits = $wordCount;
        $entry->words = $wordCount;
        $entry->save();
        $user->save();
        $userOpenai = UserOpenai::where('user_id', Auth::id())->where('openai_id', $ai->id)->orderBy('created_at', 'desc')->paginate(10);
        $userOpenai->withPath(route('dashboard.user.openai.generator', 'ai_voiceover'));
        $openai = OpenAIGenerator::where('id', $ai->id)->first();
        $html2 = view('panel.user.openai.components.generator_sidebar_table', compact('userOpenai', 'openai'))->render();

        return response()->json(compact('html2'));
    }
}