forked from oscie57/tiktok-voice
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
243 lines (186 loc) · 8.1 KB
/
Copy pathmain.py
File metadata and controls
243 lines (186 loc) · 8.1 KB
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
import requests, base64, random, argparse, os, playsound, time, re, textwrap
# https://twitter.com/scanlime/status/1512598559769702406
voices = [
# DISNEY VOICES
'en_us_ghostface', # Ghost Face
'en_us_chewbacca', # Chewbacca
'en_us_c3po', # C3PO
'en_us_stitch', # Stitch
'en_us_stormtrooper', # Stormtrooper
'en_us_rocket', # Rocket
# ENGLISH VOICES
'en_au_001', # English AU - Female
'en_au_002', # English AU - Male
'en_uk_001', # English UK - Male 1
'en_uk_003', # English UK - Male 2
'en_us_001', # English US - Female (Int. 1)
'en_us_002', # English US - Female (Int. 2)
'en_us_006', # English US - Male 1
'en_us_007', # English US - Male 2
'en_us_009', # English US - Male 3
'en_us_010', # English US - Male 4
# EUROPE VOICES
'fr_001', # French - Male 1
'fr_002', # French - Male 2
'de_001', # German - Female
'de_002', # German - Male
'es_002', # Spanish - Male
# AMERICA VOICES
'es_mx_002', # Spanish MX - Male
'br_001', # Portuguese BR - Female 1
'br_003', # Portuguese BR - Female 2
'br_004', # Portuguese BR - Female 3
'br_005', # Portuguese BR - Male
# ASIA VOICES
'id_001', # Indonesian - Female
'jp_001', # Japanese - Female 1
'jp_003', # Japanese - Female 2
'jp_005', # Japanese - Female 3
'jp_006', # Japanese - Male
'kr_002', # Korean - Male 1
'kr_003', # Korean - Female
'kr_004', # Korean - Male 2
# SINGING VOICES
'en_female_f08_salut_damour' # Alto
'en_male_m03_lobby' # Tenor
'en_female_f08_warmy_breeze' # Warmy Breeze
'en_male_m03_sunshine_soon' # Sunshine Soon
# OTHER
'en_male_narration' # narrator
'en_male_funny' # wacky
'en_female_emotional' # peaceful
]
def tts(session_id: str, text_speaker: str = "en_us_002", req_text: str = "TikTok Text To Speech", filename: str = 'voice.mp3', play: bool = False):
req_text = req_text.replace("+", "plus")
req_text = req_text.replace(" ", "+")
req_text = req_text.replace("&", "and")
headers = {
'User-Agent': 'com.zhiliaoapp.musically/2022600030 (Linux; U; Android 7.1.2; es_ES; SM-G988N; Build/NRD90M;tt-ok/3.12.13.1)',
'Cookie': f'sessionid={session_id}'
}
url = f"https://api22-normal-c-useast1a.tiktokv.com/media/api/text/speech/invoke/?text_speaker={text_speaker}&req_text={req_text}&speaker_map_type=0&aid=1233"
r = requests.post(url, headers = headers)
if r.json()["message"] == "Couldn't load speech. Try again.":
output_data = {"status": "Session ID is invalid", "status_code": 5}
print(output_data)
return output_data
vstr = [r.json()["data"]["v_str"]][0]
msg = [r.json()["message"]][0]
scode = [r.json()["status_code"]][0]
log = [r.json()["extra"]["log_id"]][0]
dur = [r.json()["data"]["duration"]][0]
spkr = [r.json()["data"]["speaker"]][0]
b64d = base64.b64decode(vstr)
with open(filename, "wb") as out:
out.write(b64d)
output_data = {
"status": msg.capitalize(),
"status_code": scode,
"duration": dur,
"speaker": spkr,
"log": log
}
print(output_data)
if play is True:
playsound.playsound(filename)
os.remove(filename)
return output_data
def tts_batch(session_id: str, text_speaker: str = 'en_us_002', req_text: str = 'TikTok Text to Speech', filename: str = 'voice.mp3'):
req_text = req_text.replace("+", "plus")
req_text = req_text.replace(" ", "+")
req_text = req_text.replace("&", "and")
headers = {
'User-Agent': 'com.zhiliaoapp.musically/2022600030 (Linux; U; Android 7.1.2; es_ES; SM-G988N; Build/NRD90M;tt-ok/3.12.13.1)',
'Cookie': f'sessionid={session_id}'
}
url = f"https://api22-normal-c-useast1a.tiktokv.com/media/api/text/speech/invoke/?text_speaker={text_speaker}&req_text={req_text}&speaker_map_type=0&aid=1233"
r = requests.post(url, headers=headers)
if r.json()["message"] == "Couldn't load speech. Try again.":
output_data = {"status": "Session ID is invalid", "status_code": 5}
print(output_data)
return output_data
vstr = [r.json()["data"]["v_str"]][0]
msg = [r.json()["message"]][0]
scode = [r.json()["status_code"]][0]
log = [r.json()["extra"]["log_id"]][0]
dur = [r.json()["data"]["duration"]][0]
spkr = [r.json()["data"]["speaker"]][0]
b64d = base64.b64decode(vstr)
with open(filename, "wb") as out:
out.write(b64d)
output_data = {
"status": msg.capitalize(),
"status_code": scode,
"duration": dur,
"speaker": spkr,
"log": log
}
print(output_data)
return output_data
def batch_create(filename: str = 'voice.mp3'):
out = open(filename, 'wb')
def sorted_alphanumeric(data):
convert = lambda text: int(text) if text.isdigit() else text.lower()
alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
return sorted(data, key=alphanum_key)
for item in sorted_alphanumeric(os.listdir('./batch/')):
filestuff = open('./batch/' + item, 'rb').read()
out.write(filestuff)
out.close()
def main():
parser = argparse.ArgumentParser(description = "Simple Python script to interact with the TikTok TTS API")
parser.add_argument("-v", "--voice", help = "the code of the desired voice")
parser.add_argument("-t", "--text", help = "the text to be read")
parser.add_argument("-s", "--session", help = "account session id")
parser.add_argument("-f", "--file", help = "use this if you wanna use 'text.txt'")
parser.add_argument("-n", "--name", help = "The name for the output file (.mp3)")
parser.add_argument("-p", "--play", action='store_true', help = "use this if you want to play your output")
args = parser.parse_args()
text_speaker = args.voice
if args.file is not None:
req_text = open(args.file, 'r', errors='ignore', encoding='utf-8').read()
else:
if args.text == None:
req_text = 'TikTok Text To Speech'
print('You need to have one form of text! (See README.md)')
else:
req_text = args.text
if args.play is not None:
play = args.play
if args.voice == None:
text_speaker = 'en_us_002'
print('You need to have a voice! (See README.md)')
if text_speaker == "random":
text_speaker = randomvoice()
if args.name is not None:
filename = args.name
else:
filename = 'voice.mp3'
if args.session is None:
print('FATAL: You need to have a TikTok session ID!')
exit(1)
if args.file is not None:
chunk_size = 200
textlist = textwrap.wrap(req_text, width=chunk_size, break_long_words=True, break_on_hyphens=False)
os.makedirs('./batch/')
for i, item in enumerate(textlist):
tts_batch(args.session, text_speaker, item, f'./batch/{i}.mp3')
batch_create(filename)
for item in os.listdir('./batch/'):
os.remove('./batch/' + item)
os.removedirs('./batch/')
return
tts(args.session, text_speaker, req_text, filename, play)
def randomvoice():
count = random.randint(0, 15)
text_speaker = voices[count]
return text_speaker
def sampler():
for item in voices:
text_speaker = item
filename = item
print(item)
req_text = 'TikTok Text To Speech Sample'
tts(text_speaker, req_text, filename)
if __name__ == "__main__":
main()