Skip to content

Instantly share code, notes, and snippets.

@kristian-io
Created February 20, 2022 09:16
Show Gist options
  • Save kristian-io/b2c4cc1d3c1583ffe92062a5c559bbfd to your computer and use it in GitHub Desktop.
Save kristian-io/b2c4cc1d3c1583ffe92062a5c559bbfd to your computer and use it in GitHub Desktop.
Listen to any article on web with few lines of Python.
# pip install newspaper3k
# pip install requests
# or
# pip3 install newspaper3k
# pip3 install requests
from newspaper import Article
import requests, json, time
# try with any URL you want to turn into "audio article" :)
url = 'https://www.space.com/atomic-clock-one-second-300-billion-years'
# lets name it somehow
file_name = "article.wav"
# get your FREE API key at https://rapidapi.com/k_1/api/large-text-to-speech/
api_key = "YOUR_API_KEY"
# lets get the article, combine the title and the text
article = Article(url)
article.download()
article.parse()
text = article.title + ". " + article.text
# print(text)
# lets prepared data which we will send to the API
url = "https://large-text-to-speech.p.rapidapi.com/tts"
payload = {"text": text}
headers = {
'content-type': "application/json",
'x-rapidapi-host': "large-text-to-speech.p.rapidapi.com",
'x-rapidapi-key': api_key,
}
# POST request for TTS job
response = requests.request("POST", url, data=json.dumps(payload), headers=headers)
try:
# get id and eta of the job from the response
id = json.loads(response.text)['id']
eta = json.loads(response.text)['eta']
except:
print(response.text)
print(f'Waiting {eta} seconds for the job to finish...')
time.sleep(eta)
# GET the result from the API
response = requests.request("GET", url, headers=headers, params={'id': id})
# if the job takes longer than expected url is not returned yet, wait more and try again
while "url" not in json.loads(response.text):
response = requests.get(url, headers=headers, params={'id': id})
eta = json.loads(response.text)['eta']
print(f'Waiting some more...')
if "error" in json.loads(response.text):
print(json.loads(response.text))
break
time.sleep(3)
result_url = json.loads(response.text)['url']
# download the waw file from results_url
response = requests.get(result_url)
# save the waw file to disk
with open(file_name, 'wb') as f:
f.write(response.content)
print(f'File saved to {file_name} ! \Or download it from {result_url}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment