-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
97 lines (80 loc) · 2.64 KB
/
app.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
import os
import boto3
import uuid
import webpack_boilerplate
from src.variables import (
AWS_ACCESS_KEY_ID,
AWS_SECRET_ACCESS_KEY,
AWS_LINK_LIFETIME,
BASE_DIR,
BUCKET_NAME,
HOSTNAME,
MAX_FILE_SIZE,
PORT
)
from src.utils import allowed_file, upload_file_to_s3
from pathlib import Path
from flask import Flask, render_template, request
from webpack_boilerplate.config import setup_jinja2_ext
from cookiecutter.main import cookiecutter
s3 = boto3.client(
"s3",
aws_access_key_id=AWS_ACCESS_KEY_ID,
aws_secret_access_key=AWS_SECRET_ACCESS_KEY
)
app = Flask(__name__, static_folder="frontend/build", static_url_path="/static/")
app.config['MAX_CONTENT_LENGTH'] = int(MAX_FILE_SIZE) * 1000 * 1000 # max upload size is 20MB
app.config.update({
'WEBPACK_LOADER': {
'MANIFEST_FILE': os.path.join(BASE_DIR, "frontend/build/manifest.json"),
}
})
setup_jinja2_ext(app)
@app.cli.command("webpack_init")
def webpack_init():
pkg_path = os.path.dirname(webpack_boilerplate.__file__)
cookiecutter(pkg_path, directory="frontend_template")
## ROUTES ##
@app.route("/")
def hello():
return render_template('index.html')
@app.route("/api/upload-audio", methods=["POST"])
def upload_audio():
status = {'uploadSuccessful': False}
message = 'File uploaded successfully'
if 'File' not in request.files:
message = "No file found in the request"
file = request.files['File']
if file.filename == '':
message = 'No file name specified'
if not file or not allowed_file(file.filename):
message = 'File type not allowed'
file.filename = str(uuid.uuid4()) + "-" + file.filename
output = upload_file_to_s3(s3, file)
if not output:
message = 'File upload failed'
else:
status = {'uploadSuccessful': True, 'name': output}
return {**status, "message": message}
@app.route("/api/query-audio", methods=["GET"])
def query_audio():
# this will require pagination later on if we want to make this scalable
s3_resource = boto3.resource('s3')
bucket = s3_resource.Bucket(BUCKET_NAME)
files = []
for file in bucket.objects.all():
url = s3.generate_presigned_url('get_object', Params={
'Bucket': BUCKET_NAME,
'Key': file.key
}, ExpiresIn=AWS_LINK_LIFETIME)
if not url: continue
audio = {
'url': url,
'name': file.key,
'type': Path(file.key).suffix.replace(".", ""),
'size': file.size,
}
files.append(audio)
return {'message': 'Query successful', 'files': files}
if __name__ == "__main__":
app.run(host=HOSTNAME, port=PORT)