-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathhandler.py
178 lines (159 loc) · 5.17 KB
/
handler.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
import json
import os
import boto3
import botocore
import string
import random
import traceback
import hashlib
import time
os.environ["PATH"] += ":"+os.path.dirname(os.path.abspath(__file__))+"/bin"
from main import process, crossfade
s3 = boto3.client("s3")
bucket = os.environ["BUCKET"]
expiration = 60*60 # one hour
def random_key():
return "".join(random.choice(string.ascii_letters) for m in range(32))
def params(event):
return json.loads(event["body"])
def upload_url(event, context):
try:
key = random_key()
url = s3.generate_presigned_url(
ClientMethod = "put_object",
Params = {
"Bucket": bucket,
"Key": key,
"ContentType": params(event)["type"],
"Expires": expiration
}
)
return {
"statusCode": 200,
"headers": {
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Credentials": True
},
"body": json.dumps({
"success": True,
"message": "Ready for upload.",
"key": key,
"url": url
})
}
except Exception as e:
print("Unexpected error:")
traceback.print_exc()
return {
"statusCode": 500,
"headers": {
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Credentials": True
},
"body": json.dumps({
"success": False,
"message": "Encountered error. {0}".format(e)
})
}
def wait_and_download(key, target):
for _ in range(0, 10):
try:
s3.download_file(bucket, key, target)
except botocore.exceptions.ClientError as e:
if e.response["Error"]["Code"] in ["404", "403"]:
time.sleep(0.3)
continue # and retry
break
def analyze(event, context):
p = params(event)
try:
fname = "/tmp/"+p["key"]+".mp3"
wait_and_download(p["key"], fname)
sha256 = hashlib.sha256(open(fname, "rb").read()).hexdigest()
try:
s3.download_file(bucket, sha256+".json", fname+".json")
except botocore.exceptions.ClientError as e:
if e.response["Error"]["Code"] == "404":
body = process(fname, 200)
if len(body["results"]) > 40:
with open(fname+".json", "w") as f:
json.dump(body, f)
s3.upload_file(fname+".json", bucket, sha256+".json")
else:
raise
else:
with open(fname+".json") as f:
body = json.loads(f.read())
return {
"statusCode": 200,
"headers": {
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Credentials": True
},
"body": json.dumps({
"success": True,
"message": "Processed file.",
"data": body
}, separators=(",", ":"))
}
except Exception as e:
print("Unexpected error:", p["key"])
traceback.print_exc()
return {
"statusCode": 500,
"headers": {
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Credentials": True
},
"body": json.dumps({
"success": False,
"message": "Encountered error on server. {0}".format(e)
})
}
def export(event, context):
p = params(event)
try:
key = random_key()
nodip = "nodip" in p and p["nodip"]
fname = "/tmp/"+p["key"]+".mp3"
wait_and_download(p["key"], fname)
crossfade(fname, "/tmp/output.mp3", p["overlap"], p["a"], p["b"], nodip)
s3.upload_file("/tmp/output.mp3", bucket, key)
sha256 = hashlib.sha256(open(fname, "rb").read()).hexdigest()
url = s3.generate_presigned_url(
ClientMethod = "get_object",
Params = {
"Bucket": bucket,
"Key": key,
"ResponseContentDisposition": "attachment; filename=snipsnip-"+sha256[:6]+".mp3",
"ResponseContentType" : "audio/mpeg"
}
)
return {
"statusCode": 200,
"headers": {
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Credentials": True
},
"body": json.dumps({
"success": True,
"message": "Exported file.",
"key": key,
"url": url,
"nodip": nodip
})
}
except Exception as e:
print("Unexpected error:", p["key"])
traceback.print_exc()
return {
"statusCode": 500,
"headers": {
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Credentials": True
},
"body": json.dumps({
"success": False,
"message": "Encountered error on server. {0}".format(e)
})
}