Created
October 25, 2024 04:22
-
-
Save zironycho/5867171f45d8a4a128f4925d3df27473 to your computer and use it in GitHub Desktop.
Typecast api with quick cloning (python)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import time | |
import requests | |
API_TOKEN = {{your API token}} | |
REFERENCE_AUDIO_FILENAME = {{your audio filename}} | |
HEADERS = {'Authorization': f'Bearer {API_TOKEN}'} | |
_, reference_audio_format = os.path.splitext(REFERENCE_AUDIO_FILENAME) | |
reference_audio_format = reference_audio_format[1:] | |
# 1. request upload url | |
r = requests.post( | |
"https://typecast.ai/api/speak/resource", | |
headers=HEADERS, | |
json={"audio_format": reference_audio_format}, | |
) | |
result = r.json()["result"] | |
speak_resource_id = result["speak_resource_id"] | |
presigned_url = result["presigned_url"] | |
# 2. upload audio file | |
with open(REFERENCE_AUDIO_FILENAME, "rb") as f: | |
requests.put(presigned_url, data=f.read()) | |
# 3. request speech | |
r = requests.post( | |
"https://typecast.ai/api/speak", | |
headers=HEADERS, | |
json={ | |
"tts_mode": "audio_file", | |
"speak_resource_id": speak_resource_id, | |
"text": "Hello world!", | |
"lang": "en-us", | |
"xapi_hd": True, | |
}, | |
) | |
speak_url = r.json()["result"]["speak_v2_url"] | |
# 4. polling the speech result | |
for _ in range(120): | |
r = requests.get(speak_url, headers=HEADERS) | |
ret = r.json()['result'] | |
# audio is ready | |
if ret['status'] == 'done': | |
# download audio file | |
r = requests.get(ret['audio_download_url']) | |
with open('out.wav', 'wb') as f: | |
f.write(r.content) | |
print(f"finish") | |
break | |
else: | |
print(f"status: {ret['status']}, waiting 1 second") | |
time.sleep(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment