· 6 years ago · Jan 12, 2020, 02:24 AM
1#!/usr/bin/env python3
2import os,sys
3import requests
4import time
5from xml.etree import ElementTree
6from bs4 import BeautifulSoup
7
8
9try:
10 input = raw_input
11except NameError:
12 pass
13
14
15
16class TextToSpeech(object):
17 def __init__(self, subscription_key,text):
18 self.subscription_key = subscription_key
19 self.tts = text #input("What would you like to convert to speech: ")
20 self.timestr = time.strftime("%Y%m%d-%H%M")
21 self.access_token = None
22
23 def get_token(self):
24 print("Fetching API token...")
25 fetch_token_url = "https://westus.api.cognitive.microsoft.com/sts/v1.0/issueToken"
26 headers = {
27 'Ocp-Apim-Subscription-Key': self.subscription_key
28 }
29 response = requests.post(fetch_token_url, headers=headers)
30 self.access_token = str(response.text)
31
32 def save_audio(self):
33
34 base_url = 'https://westus.tts.speech.microsoft.com/' #https://westus2.tts.speech.microsoft.com/cognitiveservices/v1
35 path = 'cognitiveservices/v1'
36 constructed_url = base_url + path
37 headers = {
38 'Authorization': 'Bearer ' + self.access_token,
39 'Content-Type': 'application/ssml+xml',
40 'X-Microsoft-OutputFormat': 'riff-24khz-16bit-mono-pcm',
41 'User-Agent': 'YOUR_RESOURCE_NAME'
42 }
43 xml_body = ElementTree.Element('speak', version='1.0')
44 xml_body.set('{http://www.w3.org/XML/1998/namespace}lang', 'en-us')
45 voice = ElementTree.SubElement(xml_body, 'voice')
46 voice.set('{http://www.w3.org/XML/1998/namespace}lang', 'en-US')
47 voice.set('name', 'Microsoft Server Speech Text to Speech Voice (en-US, Guy24KRUS)') # Guy24KRUS,BenjaminRUS,GuyNeural
48 prosody = ElementTree.SubElement(voice, 'prosody')
49 prosody.set("rate","-10.00%")
50 prosody.set("volume","loud")
51 # <say-as interpret-as="ordinal"> 1st </say-as>
52 # sayas = ElementTree.SubElement(prosody, 'say-as')
53 # sayas.set('detail','3')
54 prosody.text = self.tts # voice.text = self.tts
55
56 body = ElementTree.tostring(xml_body)
57 bs = BeautifulSoup(body, 'xml')
58 print("Sending XML to speech server...")
59 print('\n-------------------------------------------\n')
60 print(bs.prettify())
61 print('\n-------------------------------------------\n')
62
63
64 response = requests.post(constructed_url, headers=headers, data=body)
65 if response.status_code == 200:
66 with open('drift.wav', 'wb') as audio:
67 audio.write(response.content)
68 print("Saving audio file ...")
69 os.system('aplay /box/ai/drift.wav')
70 else:
71 print("\nStatus code: " + str(response.status_code) +
72 "\nSomething went wrong. Check your subscription key and headers.\n")
73 exit()
74
75def SendIt(file,text):
76 print("Sending %s to AI... \n\n" %file)
77 with open(file, 'rb') as data:
78 filedata = data.read()
79
80 proxies={"http": "http://127.0.0.1:8080"}
81 header={
82 "Host": "ai",
83 "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0",
84 "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
85 "Accept-Language": "en-US,en;q=0.5",
86 "Accept-Encoding": "gzip, deflate",
87 "Referer": "http://ai/ai.php"
88 }
89 url = 'http://ai/ai.php'
90 files = {'fileToUpload': ('filename',filedata,'audio/x-wav')}
91 data = {'submit':'Process It!'}
92 r = requests.post(url, headers=header,files=files,data=data) # ,proxies=proxies)
93
94 soup = BeautifulSoup(r.text, 'html.parser')
95 link = soup.find("h3")
96 link = str(link).replace('<h3>','').replace('</h3>','').replace('<br/>','\n')
97 with open('/box/ai/word.log',"a+") as log:
98 log.write("Original Input: %s\n" %text)
99 log.write(link)
100 log.write("\n----------------------------------------------------------------------------------\n")
101
102 print("Original Input: %s" %text)
103 print(link)
104
105def DoIt(text):
106 text = text
107 subscription_key = "" #### SUBSCRIPTION KEY GOES HERE
108 app = TextToSpeech(subscription_key,text)
109 app.get_token()
110 app.save_audio()
111 SendIt("/box/ai/drift.wav",text)
112
113if __name__ == "__main__":
114 DoIt(sys.argv[1])
115 # with open('/box/ai/apo.lst') as wl:
116 # for line in wl.readlines():
117 # line = line.rstrip('\n')
118 # DoIt(line)