-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathapp.py
112 lines (87 loc) · 2.95 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import os
import sys
import json
from deepgram import Deepgram
from django.conf import settings
from django.core.wsgi import get_wsgi_application
from django.http import JsonResponse, HttpResponseBadRequest
from django.shortcuts import render
from django.urls import path
from django.utils.crypto import get_random_string
from dotenv import load_dotenv
from whitenoise import WhiteNoise
load_dotenv()
settings.configure(
ALLOWED_HOSTS=["localhost"],
DEBUG=(os.environ.get("DEBUG", "") == "1"),
ROOT_URLCONF=__name__,
SECRET_KEY=get_random_string(40),
MIDDLEWARE=[
"whitenoise.middleware.WhiteNoiseMiddleware",
],
STATIC_URL="/",
STATIC_ROOT="static/",
STATICFILES_STORAGE="whitenoise.storage.CompressedManifestStaticFilesStorage",
TEMPLATES=[
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": ["static"],
},
],
)
deepgram = Deepgram(os.environ.get("DEEPGRAM_API_KEY"))
async def transcribe(request):
if request.method == "POST":
form = request.POST
files = request.FILES
url = form.get("url")
features = form.get("features")
model = form.get("model")
version = form.get("version")
tier = form.get("tier")
dgFeatures = json.loads(features)
dgRequest = None
try:
if url and url.startswith("https://res.cloudinary.com/deepgram"):
dgRequest = {"url": url}
if "file" in files:
file = files["file"]
dgRequest = {"mimetype": file.content_type, "buffer": file.read()}
dgFeatures["model"] = model
if version:
dgFeatures["version"] = version
if model == "whisper":
dgFeatures["tier"] = tier
if not dgRequest:
raise Exception(
"Error: You need to choose a file to transcribe your own audio."
)
transcription = await deepgram.transcription.prerecorded(
dgRequest, dgFeatures
)
return JsonResponse(
{
"model": model,
"version": version,
"tier": tier,
"dgFeatures": dgFeatures,
"transcription": transcription,
}
)
except Exception as error:
return json_abort(str(error))
else:
return HttpResponseBadRequest("Invalid HTTP method")
def json_abort(message):
return HttpResponseBadRequest(json.dumps({"err": str(message)}))
def index(request):
return render(request, "index.html")
urlpatterns = [
path("", index),
path("api", transcribe, name="transcribe"),
]
app = get_wsgi_application()
app = WhiteNoise(app, root="static/", prefix="/")
if __name__ == "__main__":
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)