-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
499 lines (399 loc) · 11.3 KB
/
main.py
File metadata and controls
499 lines (399 loc) · 11.3 KB
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
#
# Client-side python app for my TRANSCRIPTO APP, which is calling
# a set of lambda functions in AWS through API Gateway.
# The overall purpose of the app is to process audio and text files and
# translate between them.
#
# Authors:
# Ellen Tomlins
#
# Prof. Joe Hummel (initial template)
# Northwestern University
# CS 310
#
import random
import requests
import jsons
import uuid
import pathlib
import logging
import sys
import os
import base64
import time
from configparser import ConfigParser
############################################################
#
# classes
#
class User:
def __init__(self, row):
self.userid = row[0]
self.username = row[1]
self.pwdhash = row[2]
class Job:
def __init__(self, row):
self.jobid = row[0]
self.userid = row[1]
self.status = row[2]
self.originaldatafile = row[3]
self.datafilekey = row[4]
self.resultsfilekey = row[5]
###################################################################
#
# web_service_get
#
# When calling servers on a network, calls can randomly fail.
# The better approach is to repeat at least N times (typically
# N=3), and then give up after N tries.
#
def web_service_get(url):
"""
Submits a GET request to a web service at most 3 times, since
web services can fail to respond e.g. to heavy user or internet
traffic. If the web service responds with status code 200, 400
or 500, we consider this a valid response and return the response.
Otherwise we try again, at most 3 times. After 3 attempts the
function returns with the last response.
Parameters
----------
url: url for calling the web service
Returns
-------
response received from web service
"""
try:
retries = 0
while True:
response = requests.get(url)
if response.status_code in [200, 400, 480, 481, 482, 500]:
#
# we consider this a successful call and response
#
break;
#
# failed, try again?
#
retries = retries + 1
if retries < 3:
# try at most 3 times
time.sleep(retries)
continue
#
# if get here, we tried 3 times, we give up:
#
break
return response
except Exception as e:
print("**ERROR**")
logging.error("web_service_get() failed:")
logging.error("url: " + url)
logging.error(e)
return None
############################################################
#
# prompt
#
def prompt():
"""
Prompts the user and returns the command number
Parameters
----------
None
Returns
-------
Command number entered by user (0, 1, 2, ...)
"""
try:
print()
print(">> Enter a command:")
print(" 0 => end")
print(" 1 => upload a file")
print(" 2 => get status of a job")
print(" 3 => upload and poll")
print(" 4 => translate")
cmd = input()
if cmd == "":
cmd = -1
elif not cmd.isnumeric():
cmd = -1
else:
cmd = int(cmd)
return cmd
except Exception as e:
print("**ERROR")
print("**ERROR: invalid input")
print("**ERROR")
return -1
##############################################################
##############################################################
##############################################################
def upload_file(baseurl):
"""
Upload mp3 or txt file to be processed (either transcribed or text-to-speech).
Parameters
----------
baseurl: str
Returns
-------
jobid
"""
api = '/upload'
url = baseurl + api
print("Enter local path to file:")
path = input().strip()
try:
with open(path, "rb") as file:
file_bytes = file.read()
except FileNotFoundError:
print("error: file not found")
return
extension = path.split('.')[-1].lower()
job_type = input("Enter job type (transcription or text_to_speech): ").strip().lower()
if job_type not in {"transcription", "text_to_speech"}:
print("error: invalid job type")
return
if extension not in {'mp3','txt'}:
print("error: only mp3 and txt files for now")
return
encoded = base64.b64encode(file_bytes).decode("utf-8")
filename = path.split("/")[-1]
payload = {
"filename": filename,
"data": encoded
}
params = {"job_type": job_type}
headers = {
"Content-Type": "application/json"
}
print(f"Uploading {filename} as a {job_type} job...")
response = requests.post(url, json=payload, params=params, headers=headers)
if response.status_code == 200:
print("Success!")
print(response.json())
else:
print(f"Failed with status code: {response.status_code}")
print(response.text)
def get_status(baseurl):
"""
get status of a job
Parameters
----------
baseurl: str
Returns
-------
status of job
"""
print("enter jobid> ")
jobid = input().strip()
url = f"{baseurl}/results/{jobid}/"
print('url: ', url)
response = requests.get(url)
status_code = response.status_code
print('status code: ', status_code)
if status_code == 200:
transcript = response.json()
print('status: completed')
print(transcript)
return transcript
elif status_code == 480:
print('status: uploaded')
return 'uploaded'
elif status_code == 481:
print('status: processing')
return 'processing'
elif status_code == 482:
error_msg = response.json()
print('error:')
print(error_msg)
return 'error'
elif status_code == 400:
print('job id not found.')
return 'wrong id'
else:
print('weird error bro')
def upload_and_poll(baseurl):
try:
error = False
api = '/upload'
url = baseurl + api
print("Enter local path to file:")
path = input().strip()
try:
with open(path, "rb") as file:
file_bytes = file.read()
except FileNotFoundError:
print("Error: File not found.")
return
extension = path.split('.')[-1].lower()
job_type = input("Enter job type (transcription or text_to_speech): ").strip().lower()
if job_type not in {"transcription", "text_to_speech"}:
print("Error: invalid job type.")
return
encoded = base64.b64encode(file_bytes).decode("utf-8")
filename = path.split("/")[-1]
payload = {
"filename": filename,
"data": encoded
}
params = {"job_type": job_type}
headers = {"Content-Type": "application/json"}
print(f"Uploading {filename} as a {job_type} job...")
response = requests.post(url, json=payload, params=params, headers=headers)
if response.status_code != 200:
print(f"Upload failed with status code: {response.status_code}")
print(response.text)
return
jobid = response.json()
print("Upload succeeded. Job ID:", jobid)
result_url = f"{baseurl}/results/{jobid}/"
while True:
res = requests.get(result_url)
status_code = res.status_code
msg = res.json()
print("Status code:", status_code)
if status_code == 200:
break
if 400 <= status_code < 500:
print("Job status:", msg)
if 'error' in msg or status_code >= 500:
error = True
break
time.sleep(random.randint(1, 5))
if error:
print("Job failed or encountered error:")
print(msg)
return
if job_type == "transcription":
print("TRANSCRIPTION RESULTS BELOW:\n")
print(msg)
elif job_type == "text_to_speech":
mp3_url = msg.get("results_url")
if not mp3_url:
print("Unexpected response for text_to_speech job:", msg)
return
output_filename = f"tts-result-{jobid}.mp3"
print("Downloading MP3 file from:", mp3_url)
audio = requests.get(mp3_url)
with open(output_filename, 'wb') as f:
f.write(audio.content)
print(f"Audio saved to: {output_filename}")
else:
print("Unsupported job type in client handler.")
except Exception as e:
logging.error("**ERROR: upload_and_poll() failed:")
logging.error(e)
return
def translate(baseurl):
try:
api = '/translate'
url = baseurl + api
path = input("Enter local path to .txt file: ").strip()
lang = input("Enter target language ('es' = Spanish, 'fr' = French): ").strip()
try:
with open(path, "r", encoding="utf-8") as f:
text = f.read()
except FileNotFoundError:
print("Error: wrong path.")
return
payload = {
"text": text,
"target_language": lang
}
headers = {"Content-Type": "application/json"}
print(f"Sending file for translation to '{lang}'...")
response = requests.post(url, json=payload, headers=headers)
if response.status_code == 200:
res = response.json()
print("Job ID:", res["job_id"])
print("TRANSLATION RESULTS BELOW:\n")
translation = requests.get(res["results_url"])
print(translation.text)
else:
print("Failed with status code:", response.status_code)
print(response.text)
except Exception as e:
logging.error("**ERROR: upload_and_poll() failed:")
logging.error(e)
return
############################################################
# main
#
try:
print('** Welcome to Transcripto! **')
print()
# eliminate traceback so we just get error message:
sys.tracebacklimit = 0
#
# what config file should we use for this session?
#
config_file = 'transcripto-client-config.ini'
print("Config file to use for this session?")
print("Press ENTER to use default, or")
print("enter config file name>")
s = input()
if s == "": # use default
pass # already set
else:
config_file = s
#
# does config file exist?
#
if not pathlib.Path(config_file).is_file():
print("**ERROR: config file '", config_file, "' does not exist, exiting")
sys.exit(0)
#
# setup base URL to web service:
#
configur = ConfigParser()
configur.read(config_file)
baseurl = configur.get('client', 'webservice')
#
# make sure baseurl does not end with /, if so remove:
#
if len(baseurl) < 16:
print("**ERROR: baseurl '", baseurl, "' is not nearly long enough...")
sys.exit(0)
if baseurl == "https://YOUR_GATEWAY_API.amazonaws.com":
print("**ERROR: update config file with your gateway endpoint")
sys.exit(0)
if baseurl.startswith("http:"):
print("**ERROR: your URL starts with 'http', it should start with 'https'")
sys.exit(0)
lastchar = baseurl[len(baseurl) - 1]
if lastchar == "/":
baseurl = baseurl[:-1]
#
# main processing loop:
#
cmd = prompt()
while cmd != 0:
#
if cmd == 1:
upload_file(baseurl)
elif cmd == 2:
get_status(baseurl)
elif cmd == 3:
upload_and_poll(baseurl)
elif cmd == 4:
translate(baseurl)
elif cmd == 5:
pass
# download(baseurl)
elif cmd == 6:
pass
# upload_and_poll(baseurl)
else:
print("** Unknown command, try again...")
#
cmd = prompt()
#
# done
#
print()
print('** done **')
sys.exit(0)
except Exception as e:
logging.error("**ERROR: main() failed:")
logging.error(e)
sys.exit(0)