-
Notifications
You must be signed in to change notification settings - Fork 0
/
transcript_generator.py
223 lines (175 loc) · 5.9 KB
/
transcript_generator.py
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
import requests
import json
import wave
import time
import sys
import os
import contextlib
import speech_recognition as sr
import wave
import contextlib
import xlwt
import datetime
import shutil
import math
import argparse
from pydub import AudioSegment
from tinytag import TinyTag
from os import path
from shutil import copyfile
def get_api_key():
return '63880a66d2c745419fdf3dce703d032c'
def get_duration(audioPath):
with contextlib.closing(wave.open(audioPath,'r')) as f:
frames = f.getnframes()
rate = f.getframerate()
duration = frames / float(rate)
return duration;
def create_id_profile():
api_key = get_api_key()
url = 'https://api.projectoxford.ai/spid/v1.0/identificationProfiles';
data = { "locale":"en-us" };
headers = {'Content-Type': 'application/json', 'Ocp-Apim-Subscription-Key': api_key};
r = requests.post(url, data=json.dumps(data), headers=headers)
time.sleep(5)
res = r.json();
return res["identificationProfileId"];
def create_enrollment(profile_id, voice):
api_key = get_api_key()
print "Training..."
url = 'https://api.projectoxford.ai/spid/v1.0/identificationProfiles/' + profile_id + '/enroll';
files = {'file': open(voice, 'rb')}
headers = {'Ocp-Apim-Subscription-Key': api_key};
r = requests.post(url, files=files, headers=headers)
time.sleep(3)
files = {'file': open(voice, 'rb')}
r = requests.post(url, files=files, headers=headers)
time.sleep(3)
files = {'file': open(voice, 'rb')}
r = requests.post(url, files=files, headers=headers)
time.sleep(3)
def get_specific_profile(profile_id):
api_key = get_api_key()
url = 'https://api.projectoxford.ai/spid/v1.0/identificationProfiles/' + profile_id
headers = {'Ocp-Apim-Subscription-Key': api_key};
r = requests.get(url, headers=headers)
return r.json()
def getOperationStatus(url):
api_key = get_api_key()
headers = {'Content-Type': 'application/json', 'Ocp-Apim-Subscription-Key': api_key};
r = requests.get(url, headers=headers)
return r.json()
def speechRecognition(song, start, end):
segment = song[start:end]
filename = "speech.wav"
segment.export(filename, format="wav")
r = sr.Recognizer()
with sr.AudioFile(filename) as source:
audio = r.record(source) # this is for speech -> text
try:
text = r.recognize_google(audio);
os.remove(filename)
print text
return text
except sr.UnknownValueError:
print("Google Speech Recognition could not understand audio")
os.remove(filename)
return ""
except sr.RequestError as e:
print("Could not request results from Google Speech Recognition service; {0}".format(e))
os.remove(filename)
return ""
def speakerRecognition(song, start, end, inc, voiceDict):
segment = song[start:end]
limit = int(math.ceil(63/inc));
for i in range(0, limit):
segment += song[start:end]
# filename = filepath + str(x) + ".wav" # this is for identifying speaker
filename = "speaker.wav"
segment.export(filename, format="wav")
name = identifySpeaker(voiceDict, filename)
os.remove(filename)
return name;
def identifySpeaker(voiceDict, voice_sample):
api_key = get_api_key()
voiceStrings = ''
for key in voiceDict:
voiceStrings = voiceStrings + key + ','
voiceStrings = voiceStrings[:-1]
url = 'https://api.projectoxford.ai/spid/v1.0/identify?identificationProfileIds=' + voiceStrings;
files = {'file': open(voice_sample, 'rb')}
headers = {'Ocp-Apim-Subscription-Key': api_key};
r = requests.post(url, files=files, headers=headers)
# print r.headers
while True:
if 'Operation-Location' in r.headers:
time.sleep(5)
opStatus = getOperationStatus(r.headers['Operation-Location']);
time.sleep(3)
# print opStatus
if opStatus['processingResult']:
if opStatus['processingResult']['identifiedProfileId'] != "00000000-0000-0000-0000-000000000000":
name = voiceDict[opStatus['processingResult']['identifiedProfileId']]
break
else:
if opStatus['processingResult']['identifiedProfileId'] == "00000000-0000-0000-0000-000000000000":
name = "Unknown Speaker"
break
else:
print "Error: The key 'Operation-Location' doesn't exist in r.headers."
exit(1)
print "This is " + name + "'s voice."
return name
def split_list(a_list):
half = len(a_list)/2
return a_list[:half], a_list[half:]
def train_speakers(speaker_arr, voice_dict):
"""
Trains each speaker specified in the command.
"""
for i in range(0, len(speaker_arr)):
speaker_name = speaker_arr[i]
speaker_path = "./training/" + speaker_arr[i] + "_voice.wav"
if os.path.exists(speaker_path):
# enroll speaker
profile_id = create_id_profile();
create_enrollment(profile_id, speaker_path);
# verify that speaker is enrolled
json_obj = get_specific_profile(profile_id)
if json_obj["enrollmentStatus"] == 'Enrolled':
print speaker_name + " has been enrolled."
voice_dict[profile_id] = speaker_name;
else:
print json_obj
print "Something went wrong with path '" + speaker_path + "'...try again."
exit(1)
else:
print "The path '" + speaker_path + "' doesn't exist...try again"
exit(1)
def create_transcript(meeting_path, voice_dict):
song = AudioSegment.from_wav(meeting_path)
count = 0
inc = 5;
start = 0;
end = inc * 1000;
duration = get_duration(meeting_path)
f = open("transcript.txt", 'w')
d = datetime.datetime.fromtimestamp(os.path.getmtime(meeting_path))
while True:
print "From " + str(start/1000) + " to " + str(end/1000)
text = speechRecognition(song, start, end);
name = speakerRecognition(song, start, end, inc, voice_dict)
start += inc * 1000;
end += inc * 1000;
# write transcript
if start < duration * 1000 and end < duration * 1000:
f.write(str(d) + "\t" + name + "\t" + text + "\n")
else:
A = text.split(' ')
B, C = split_list(A)
f.write(str(d) + "\t" + name + "\t" + ' '.join(B) + "\n")
f.write(str(d) + "\t" + name + "\t" + ' '.join(C) + "\n")
break;
d += datetime.timedelta(seconds = inc)
count += 1
print "Transcript completed!"