-
Notifications
You must be signed in to change notification settings - Fork 4
/
process.php
219 lines (187 loc) · 8.11 KB
/
process.php
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
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
ob_start();
require __DIR__ . '/vendor/autoload.php';
session_start();
require( 'formkey.class.php' );
$formKey = new formKey();
$error = 'No error';
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();
use Google\Cloud\TextToSpeech\V1\AudioConfig;
use Google\Cloud\TextToSpeech\V1\AudioEncoding;
use Google\Cloud\TextToSpeech\V1\SynthesisInput;
use Google\Cloud\TextToSpeech\V1\TextToSpeechClient;
use Google\Cloud\TextToSpeech\V1\VoiceSelectionParams;
function synthesize_text( $text ) {
// create client object
$client = new TextToSpeechClient();
$voice_name = htmlspecialchars($_POST[ 'voice-name' ]) ?? 'fr-FR-Wavenet-D';
$language = substr($voice_name, 0, 5);
$root = __DIR__ . '/audio/';
$directory = !empty($_COOKIE[ 't2s' ]) ? htmlspecialchars($_COOKIE[ 't2s' ]) : uniqid();
$user_dir = $root . $directory;
$sanitized_filename = htmlspecialchars($_POST[ 'filename' ]);
$filename = !empty($sanitized_filename) ? $sanitized_filename : uniqid();
$filepath = $user_dir . '/' . $filename . '.mp3';
$relative_user_dir = '/audio/' . $directory;
$relative_filepath = $relative_user_dir . '/' . $filename . '.mp3';
$is_multiple = false;
$overwrite = !empty($_POST[ 'overwrite' ]) ? htmlspecialchars($_POST[ 'overwrite' ]) : 'on';
$speed = (float) $_POST[ 'speed' ] ?? '1';
$pitch = (float) $_POST[ 'pitch' ] ?? '0';
$replace = (string) $_POST[ 'replace' ] ?? '';
// note: the voice can also be specified by name
// names of voices can be retrieved with $client->listVoices()
$voice = ( new VoiceSelectionParams() )
->setLanguageCode($language)
->setName($voice_name);
/**
* We choose "LINEAR16" for encoding since it sounds
* much better compared to MP3 as set in Google code examples.
* It is the setting used in Cloud Text To Speech demo
*/
$audioConfig = ( new AudioConfig() )
->setAudioEncoding(AudioEncoding::LINEAR16)
->setSpeakingRate($speed)
->setPitch($pitch);
// Create necessary folders
if( !is_dir($root) ) {
mkdir($root, 0777, true);
}
if( !is_dir($user_dir) ) {
mkdir($user_dir, 0777, true);
}
$actual_name = pathinfo($filepath, PATHINFO_FILENAME);
$original_name = $actual_name;
$extension = pathinfo($filepath, PATHINFO_EXTENSION);
if(!empty($replace)){
$rows = explode("\n", $replace);
// echo json_encode(var_export($rows, true));
foreach ($rows as $row) {
$row = str_replace(' => ', '=>', $row);
// Divisez chaque ligne en utilisant "=>" comme délimiteur
$parts = explode("=>", $row);
// Vérifiez si la ligne a le format attendu (clé => valeur)
if (count($parts) == 2 && !empty($parts[0]) && !empty($parts[1])) {
// Créez un tableau associatif avec la clé et la valeur
// $replacements[$parts[0]] = $parts[1];
$parts[0] = preg_replace('/\r\n|[\r\n]/', '', $parts[0]);
$parts[1] = preg_replace('/\r\n|[\r\n]/', '', $parts[1]);
$text = str_replace(
$parts[0],
$parts[1],
$text
);
// echo json_encode(['$parts[0]' => var_export($parts[0], true)]);
// echo json_encode(['$parts[1]' => var_export($parts[1], true)]);
// echo json_encode(['$text' => var_export($text, true)]);
// die();
// var_dump($parts[0], $parts[1], $text);
// echo json_encode(print_r([$parts[0], $parts[1], $text]));
// die();
}
}
}
/* If we choose to not overwrite, we create files with number after name. Ex: audio(1).mp3 */
if( $overwrite != 'on' ) {
$i = 1;
while( file_exists($user_dir . '/' . $actual_name . "." . $extension) ) {
$actual_name = (string)$original_name . '(' . $i . ')';
$name = $actual_name . "." . $extension;
$filepath = $user_dir . '/' . $name;
$relative_filepath = $relative_user_dir . '/' . $name;
$i++;
}
}
/* Check if multiple : we detect line breaks and split string into array */
if( isset($_POST[ 'multiple' ], $_POST[ 'download' ]) && $_POST[ 'multiple' ] == 'on' && $_POST[ 'download' ] == 1 ) {
// $text = str_replace('"', '', $text);
$text = rtrim($text, ' ');
$text = rtrim($text, '"');
$text = ltrim($text, '"');
$text = str_replace('<p>', "", $text);
$text = stripslashes(str_replace('</p>', "\r\n", $text));
$text = rtrim($text, "\r\n");
$array = preg_split('/\r\n|[\r\n]/', $text);
if( is_array($array) && count($array) > 1 ) {
$is_multiple = true;
}
// echo json_encode(print_r($array, true));
// die();
}
/* If we choose to make multiple files, we iterate and return a zip file */
if( $is_multiple ) {
$i = 1;
$zip = new ZipArchive();
$zipfilename = $original_name . ".zip";
$zipfilepath = $user_dir . '/' . $zipfilename;
$relative_filepath = $relative_user_dir . '/' . $zipfilename;
$tempdir = uniqid();
$tempdirabsolutepath = $user_dir . '/' . $tempdir;
// Make a temp folder
mkdir($tempdirabsolutepath, 0777, true);
// Create a zip archive
$zip->open($zipfilepath, ZipArchive::CREATE);
foreach( $array as $value ) {
$name = $original_name . '.' . $i . ".mp3";
$filepath = $tempdirabsolutepath . '/' . $name;
$input_text = ( new SynthesisInput() )->setSsml('<speak>' . $value . '</speak>');
$response = $client->synthesizeSpeech($input_text, $voice, $audioConfig);
$audioContent = $response->getAudioContent();
// Write audio to file
file_put_contents($filepath, $audioContent, LOCK_EX);
// Add file to zip
$zip->addFile($filepath, $name);
$i++;
}
$zip->close();
// Delete temporary files and temporary folder
array_map('unlink', glob("$tempdirabsolutepath/*.*"));
rmdir($tempdirabsolutepath);
}
else { // We don't want to make multiple audio file, so let's just create one.
$text = rtrim($text, ' ');
$text = rtrim($text, '"');
$text = ltrim($text, '"');
$text = stripslashes(str_replace(' ', "", $text));
$input_text = ( new SynthesisInput() )->setSsml('<speak>' . $text . '</speak>');
$response = $client->synthesizeSpeech($input_text, $voice, $audioConfig);
$audioContent = $response->getAudioContent();
// Write audio to file
file_put_contents($filepath, $audioContent, LOCK_EX);
}
$client->close();
return compact('relative_user_dir', 'relative_filepath', 'text');
}
//Is request?
if( $_SERVER[ 'REQUEST_METHOD' ] == 'POST' ) {
//Validate the form key
if( !isset($_POST[ 'form_key' ]) || !$formKey->validate() ) {
echo json_encode([
'status' => 'error',
'message' => 'Erreur de validation du formulaire'
]);
die();
}
}
if( isset($_POST[ 'text' ]) ) {
$sanitized_text = strip_tags($_POST[ 'text' ], [ '<p>', '<emphasis>', '<prosody>', '<say-as>', '<break>', '<br>' ]);
$result = synthesize_text($sanitized_text);
echo json_encode([
'status' => 'success',
'message' => 'Fichier généré avec succès',
'user_dir' => $result[ 'relative_user_dir' ],
'filepath' => $result[ 'relative_filepath' ],
'original_text' => $sanitized_text,
'output_text' => $result[ 'text' ],
]);
}
else {
echo json_encode([
'status' => 'error',
'message' => 'Le texte est absent'
]);
}