Giter VIP home page Giter VIP logo

tiktok-voice's Introduction

TikTok Text-to-speech API

FOR DOCUMENTATION, VISIT THE WIKI

This is a simple Python program that accesses the TikTok API and gives you an .mp3 file with what it says in the specified voice.

If you are stuck and need assistance, please ask me in my Discord server in #tiktok-voice (quickest response) or via the Issues tab.

If you like this project, feel free to support me via this website!

If you are the creator for a project which uses this, I would just like to thank you! I am so glad I am making people's lives easier with things. Please do credit me however either using the GitHub project link or my Twitter username.

Usage

To use this, you need Python 3.8+ and all of the required packages installed.

To install required packages, run pip3 install playsound requests or pip3 install -r requirements.txt

Read from file

  1. Make sure you have your text in plaintext. You can name it anything
  2. Run py main.py -v VOICE -f FILENAME.txt --session SESSION_ID (see voices below)

There is no character limit, though only latin characters are supported.

Read from argument

  1. Run py main.py -v VOICE -t TEXT -n FILENAME.mp3 --session SESSION_ID (see voices below)

This has a 200 character limit, but you can have non-latin characters (as long as it has a TTS supported voice)

Play from text

Optionally, if you want to listen to the file instead of saving to a file, you can use the -p argument to play directly and then delete. If you get error 263, ignore it, it doesn't affect the program itself.

Session ID

Get session id

Voice Options

Since the list has gotten quite large, I have moved it to the wiki

Languages Supported:

  • Portuguese (Brazil)
  • German
  • English (Australia)
  • English (United Kingdom)
  • English (United States)
  • English (Disney)
  • Spanish
  • Spanish (Mexico)
  • French
  • Indonesian
  • Japanese
  • Korean

Samples

You can find samples of all the voices in /samples/

Credits

  • Spotlight for giving me the idea for this program
  • Myself for creating this
  • scanlime for giving the voice options
  • Komfudo for translating the sample text to German
  • Philemax for translating the sample text to French
  • Ash for adding command line arguments
  • BigJ64 for adding a play argument

tiktok-voice's People

Contributors

abirabedinkhan avatar adamatomus avatar brianredbeard avatar catpil avatar detachhead avatar ethan-xd avatar gitlimes avatar jaymo1011 avatar lesageethan avatar oscie57 avatar pasindudineth avatar taiwo0007 avatar weilbyte avatar xenco avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tiktok-voice's Issues

'requests' module not found

i installed requests as well as all other modules but i got this message.

C:\Users\barkley\Desktop\tiktok-voice-main>py main.py -v en_us_001 -f text.txt
Traceback (most recent call last):
File "C:\Users\fatka\Desktop\tiktok-voice-main\main.py", line 1, in
import requests, base64, random, argparse, os, playsound, time, re, textwrap
ModuleNotFoundError: No module named 'requests'

can anyone help me?

Option to play

let people play the sound instead of saving but only for text

API Appears to be down or has been locked

New error vstr = [r.json()["data"]["v_str"]][0] is being thrown because the API returns {'extra': {'log_id': '20220822131552C9EAC8EF9BB84E554DFD'}, 'message': "Couldn't load speech. Try again.", 'status_code': 1, 'status_msg': "Couldn't load speech. Try again."}

Two Issues : pygobject and Session ID is invalid

Hello,
hope you are doing great, just when I'm trying to run the script I have 2 issues :
first one :
playsound is relying on another python subprocess. Please use pip install pygobject if you want playsound to run more efficiently.

PS : when a try to run this command : " pip install pygobject " it's complete with errors so the installation get failled

second :
{'status': 'Session ID is invalid', 'status_code': 5}
.
PS : I have a correct session Id
how to solve them?
thanks in advance.

Timeout & Connection Error on calling main.py

It was working for me till yesterday.
(I have generated new sessionid. but the same issue persists.)
Now I am getting the following error:

  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\connection.py", line 169, in _new_conn
    conn = connection.create_connection(
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\util\connection.py", line 96, in create_connection
    raise err
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\util\connection.py", line 86, in create_connection
    sock.connect(sa)
TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\connectionpool.py", line 699, in urlopen
    httplib_response = self._make_request(
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\connectionpool.py", line 382, in _make_request
    self._validate_conn(conn)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\connectionpool.py", line 1010, in _validate_conn
    conn.connect()
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\connection.py", line 353, in connect
    conn = self._new_conn()
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\connection.py", line 181, in _new_conn
    raise NewConnectionError(
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPSConnection object at 0x000002470BC56640>: Failed to establish a new connection: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\site-packages\requests\adapters.py", line 486, in send
    resp = conn.urlopen(
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\connectionpool.py", line 755, in urlopen
    retries = retries.increment(
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\site-packages\urllib3\util\retry.py", line 573, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='api16-normal-c-useast2a.tiktokv.com', port=443): Max retries exceeded with url: /media/api/text/speech/invoke/?text_speaker=en_us_006&req_text=To+be+or+not+to+be,+that+is+the+Question!&speaker_map_type=0&aid=1233 (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x000002470BC56640>: Failed to establish a new connection: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\site-packages\requests\api.py", line 59, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\site-packages\requests\sessions.py", line 589, in request
    resp = self.send(prep, **send_kwargs)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\site-packages\requests\sessions.py", line 703, in send
    r = adapter.send(request, **kwargs)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\site-packages\requests\adapters.py", line 519, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='api16-normal-c-useast2a.tiktokv.com', port=443): Max retries exceeded with url: /media/api/text/speech/invoke/?text_speaker=en_us_006&req_text=To+be+or+not+to+be,+that+is+the+Question!&speaker_map_type=0&aid=1233 (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x000002470BC56640>: Failed to establish a new connection: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond'))
python-BaseException```

Is there any other way to find more voice?

This application is great, but when I take the browser's sessionid I am using, the error is not right. But if you use it, use it normally.
Also when using Vietnamese voice will report the status error: 5

I converted it into Streamlit application and put it on my Ubuntu server to be able to use online.

However, I did not try to find a voice as you instructed (Android), so I rarely read.

Anyway, thank you for this great application, it complements my collection to create my voice.
You can see here: https://etools.io.vn

414728353_3721041634831752_706166473335650517_n

New sounds

In app named:
Wacky
Peaceful
Sunshine Soon (Singing)
Warmy Breeze (Singing)

weird sequencing

currently for batch processes, we have numbered files and "for file in listdir", which on some systems mess up (1, 10, 11, 12, 13...., 2, 3...) and idk a workaround

if anyone can help thatd be awesome

KeyError: 'data'

Whenever I try to use the script with a file, it throws me this message which doesn't entirely seem to line up with any status code in particular. I've tried both using a file with multiple lines and one with just one line. I've also tried the recommended Session ID as well as my own, and making sure the aid value is set correctly.

Traceback (most recent call last):
  File "C:\Users\jprig\Downloads\tiktok-voice-main\main.py", line 158, in <module>
    main()
  File "C:\Users\jprig\Downloads\tiktok-voice-main\main.py", line 126, in main
    tts(args.session, text_speaker, item, f'{batch_dir}{i}.mp3', False)
  File "C:\Users\jprig\Downloads\tiktok-voice-main\main.py", line 31, in tts
    vstr = [r.json()["data"]["v_str"]][0]
            ~~~~~~~~^^^^^^^^
KeyError: 'data'

I also tried to use it with just a text argument, but it outputs this instead:

Traceback (most recent call last):
  File "C:\Users\jprig\Downloads\tiktok-voice-main\main.py", line 158, in <module>
    main()
  File "C:\Users\jprig\Downloads\tiktok-voice-main\main.py", line 138, in main
    tts(args.session, text_speaker, req_text, filename, play)
  File "C:\Users\jprig\Downloads\tiktok-voice-main\main.py", line 31, in tts
    vstr = [r.json()["data"]["v_str"]][0]
            ~~~~~~~~^^^^^^^^
KeyError: 'data'

I'm unfortunately not very code-savvy, so I'm a bit confused on what's going on and how I can rectify it.

Session ID is invalid

Hi,

I just tested with 2 diferents account and still get

{'status': 'Session ID is invalid', 'status_code': 5}

It's throwing this issue i'm not sure why

it finished making about 15 videos and then this popped up, I've tried running it again but nothing happened
This is what it shows:

│ Saving Text to MP3 files... │
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
Working... ---------------------------------------- 2.3 it/s
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ Sorry, something went wrong with this version! Try again, and feel free to report this issue at GitHub or the │
│ Discord community. │
│ Version: 3.2.1 │
│ Error: argument should be a bytes-like object or ASCII string, not 'NoneType' │
│ Config: {'allow_nsfw': False, 'theme': 'dark', 'times_to_run': 100, 'opacity': 0.9, 'storymode': True, │
│ 'storymodemethod': 1, 'storymode_max_length': 20000, 'resolution_w': 1080, 'resolution_h': 1920, 'zoom': 1.0, │
│ 'background': {'background_video': 'minecraft', 'background_audio': 'lofi', 'background_audio_volume': 0.15, │
│ 'enable_extra_audio': False, 'background_thumbnail': False, 'background_thumbnail_font_family': 'arial', │
│ 'background_thumbnail_font_size': 96, 'background_thumbnail_font_color': '255,255,255'}, 'tts': {'voice_choice': │
│ 'tiktok', 'random_voice': False, 'elevenlabs_voice_name': 'Bella', 'elevenlabs_api_key': 'REDACTED', │
│ 'aws_polly_voice': 'Matthew', 'streamlabs_polly_voice': 'Matthew', 'tiktok_voice': 'en_uk_003', 'tiktok_sessionid': │
│ 'REDACTED', 'python_voice': '1', 'py_voice_num': '2', 'silence_duration': 0.3, 'no_emojis': False}} │
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
Traceback (most recent call last):
File "D:\RedditVideoMakerBot-master\main.py", line 132, in
raise err
File "D:\RedditVideoMakerBot-master\main.py", line 114, in
run_many(config["settings"]["times_to_run"])
File "D:\RedditVideoMakerBot-master\main.py", line 69, in run_many
main()
File "D:\RedditVideoMakerBot-master\main.py", line 51, in main
length, number_of_comments = save_text_to_mp3(reddit_object)
File "D:\RedditVideoMakerBot-master\video_creation\voices.py", line 49, in save_text_to_mp3
return text_to_mp3.run()
File "D:\RedditVideoMakerBot-master\TTS\engine_wrapper.py", line 88, in run
self.call_tts(f"postaudio-{idx}", process_text(text))
File "D:\RedditVideoMakerBot-master\TTS\engine_wrapper.py", line 149, in call_tts
self.tts_module.run(
File "D:\RedditVideoMakerBot-master\TTS\TikTok.py", line 117, in run
decoded_voices = base64.b64decode(raw_voices)
File "C:\Users\Jeremy\AppData\Local\Programs\Python\Python310\lib\base64.py", line 80, in b64decode
s = _bytes_from_decode_data(s)
File "C:\Users\Jeremy\AppData\Local\Programs\Python\Python310\lib\base64.py", line 45, in _bytes_from_decode_data
raise TypeError("argument should be a bytes-like object or ASCII "
TypeError: argument should be a bytes-like object or ASCII string, not 'NoneType'

D:\RedditVideoMakerBot-master>

Error while generating audio: Invalid base64-encoded string

I get this error:

Error occurred while generating audio: Invalid base64-encoded string: number of data characters (1766705) cannot be 1 more than a multiple of 4

when generating audio with this string: " She don’t like this ".

I found out it's because of the character " ’ ", you should replace this by " ' ".

Could someone fix this issue in code?

I hope this will also help people struggling with finding out why it doesnt want to generate the audio.

Another similar project but using GCloud

Hello there, just here to share another similar Project I made. I am curious how some vtuber like Zentreya from VShojo able to synthesize in realtime.

It receive input from microphone and output the voice using soundpad as middleman.

Command with File does not work - Text-Command works

This Command py main.py -v en_us_001 -p -f "FILENAME.txt" --session 3f***************** does not work and get's back a Status_code 5 error.
This one on the other Hand py main.py -v en_us_001 -p -t "This is a test-text" --session 3f****************** does work.
The content of the FILENAME.txt is just test

Output file names

I was just wondering if you're planning on adding an output file name modifier, somewhat akin to that of youtube-dl's.
Example: -o lorem-ipsum.mp3 instead of && rename voice.mp3 lorem-ipsum.mp3 at the end of the command.

Session ID banned

The script will not work anymore as the session ID within it is linked to a (now) banned account.

How can I put tik tok voices as text to speech in a point reward?

Everything is fine from the configuration from python to write my text with the voice language commands
(language) and the file exported in .mp3, I just don't know how I can allow a twitch user to put any text in the points reward and not accumulate several .mp3 files created by users.

First doubt:
How can I use this python code to link to Streamer.bot?

Second question:
How can I use this python code without generating an .mp3 file and only listening to the text typed by a twitch user?

Plus: the "censored" white boxes are the codes of the tik tok voices

Success mp3 file tik tok voice

Backup URL for API

The current URL set for grabbing TTS data is api16-normal-useast5.us.tiktokv.com. User hakeem#0001 (311414202218708993) on Discord showed me today that there is a second URL in the TikTok APK: api16-normal-c-alisg.tiktokv.com and a third api19-normal-useast1a.tiktokv.com

It might be a good idea that we should make the script check the second URL if there is an error on the first one.

Trying the new URL for possible new voices may also be a good idea too. @ashmonty if you could give that a shot, would be awesome.

Add new voices

I am sure there are TTS voices for other languages, so maybe try and figure out the options?

  • English
  • Arabic
  • German
  • Spanish
  • Suomi
  • French
  • French (CA)
  • Indonesian
  • Japanese
  • Korean
  • Malay
  • Russian
  • Thai
  • Tieng Viet
  • Chinese Simp
  • Chinese Trad
  • Hebrew
  • Cebuano
  • Cestina
  • Italian
  • Magyar
  • Netherlandish
  • Polish
  • Romanian
  • Svenska
  • Filipino
  • Greek
  • Ukrainain
  • Hindi

These are all the languages supported in the app.

Voice is no unavailable?

I'm getting the following error:

{'status': 'This voice is unavailable now', 'status_code': 4, 'duration': '', 'speaker': '', 'log': '20231220113051EA7E6EF827C07F09F5A3'}

Seems that the voice I was using, 'en_us_006' is no longer available. Unsure why

Session ID Randomly Becomes Invalid

After making multiple requests in a row, even after a 60-second time out after requests, passing some text results in a session id invalid code 05 error. Consider that the text also does not exceed the maximum character requirement. This is after the previous requests have not had any issues.

Suggestions

Hey there! I really want to make tiktok-voice better, so, please put any suggestions for the project here!

Status error 1 - unable to find the cause

Is anyone currently using it? I have been getting status error 1. When looking at the error page it says it could be because the params are wrong.. but they seem to be correct here. Any ideas?

Note this is the request url and this is the response I get

https://api16-normal-useast5.us.tiktokv.com/media/api/text/speech/invoke/?text_speaker=en_us_002&req_text=Testing+text+here&speaker_map_type=0&aid=1233
{'status': 'Couldn’t load speech. Try again.', 'status_code': 1, 'status_msg': 'Couldn’t load speech. Try again.'}

(Have tried both of these base urls here:
API_BASE_URL = f"https://api16-normal-v6.tiktokv.com/media/api/text/speech/invoke/"
API_BASE_URL_2="https://api16-normal-useast5.us.tiktokv.com/media/api/text/speech/invoke/")

Note I did try to find a different base url incase that was the issue, but any I got an error when trying to request them, so I don't think its the base url here thats the issue... any ideas on what could be causing the error?

This is what https://github.com/oscie57/tiktok-voice/wiki/Status-Codes says:
status_code: 1

Status Code 1 is caused by an incorrect aid value in the request parameters. The set value should be 1233.

There is another case with status code 1, where a parameter isn't passed, either text_speaker or req_text is missing.

But as you can see in the url's (?text_speaker=en_us_002&req_text=Testing+text+here&speaker_map_type=0&aid=1233), this does not seem to be the reason...

Note this is the top of my function (just edited slightly to stop status error 1 crashing it)

API_BASE_URL = f"https://api16-normal-v6.tiktokv.com/media/api/text/speech/invoke/"
API_BASE_URL_2="https://api16-normal-useast5.us.tiktokv.com/media/api/text/speech/invoke/"

USER_AGENT = f"com.zhiliaoapp.musically/2022600030 (Linux; U; Android 7.1.2; es_ES; SM-G988N; Build/NRD90M;tt-ok/3.12.13.1)"

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")
req_text = req_text.replace("ä", "ae")
req_text = req_text.replace("ö", "oe")
req_text = req_text.replace("ü", "ue")
req_text = req_text.replace("ß", "ss")

print(f"{API_BASE_URL}?text_speaker={text_speaker}&req_text={req_text}&speaker_map_type=0&aid=1233")
r = requests.post(
    f"{API_BASE_URL}?text_speaker={text_speaker}&req_text={req_text}&speaker_map_type=0&aid=1233",
    headers={
        'User-Agent': USER_AGENT,
        'Cookie': f'sessionid={session_id}'
    }
)

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

if r.json()["status_code"] == 1:
    output_data = {"status": r.json()["message"], "status_code": 1, "status_msg": r.json()["status_msg"]}
    print(output_data)
    return output_data

#print("The new data here is ", r.json())

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]

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.