Skip to content

Commit 3c28bd5

Browse files
committed
Rewrote classtoemotion in views.py; completed the following user story:As a user, I want that when I ask the system for a prediction, the system prompts me the index of the website with the prediction inserted in the string The emotion predicted for your file is. Actually, it is prompting an API view.
1 parent bafeb6f commit 3c28bd5

File tree

13 files changed

+58
-48
lines changed

13 files changed

+58
-48
lines changed
0 Bytes
Binary file not shown.
0 Bytes
Binary file not shown.
-93 Bytes
Binary file not shown.
424 Bytes
Binary file not shown.

App/forms.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,4 +10,3 @@ class FileForm(ModelForm):
1010
class Meta:
1111
model = FileModel
1212
fields = ['file']
13-

App/models.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,4 +6,3 @@ class FileModel(models.Model):
66
file = models.FileField(null=True, blank=True)
77
timestamp = models.DateTimeField(auto_now_add=True)
88
path = models.FilePathField(path=settings.MEDIA_ROOT, default=settings.MEDIA_ROOT)
9-

App/templates/index.html

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,20 +17,27 @@
1717
<div class="jumbotron text-center" id="myJumbotron" style="background-color:white">
1818
<h2>Deep Learning to predict human emotions.</h2>
1919
</div>
20-
2120
<div class="container" id="Container1">
2221
<div class="row">
23-
<div class="col-sm-4" id="FileUpload">
22+
<div class="col-sm-6 text-center" id="FileUpload">
2423
<a href="{% url 'upload_file' %}" class="btn btn-primary">Upload your audio file</a>
2524
</div>
26-
<div class="col-sm-4" id="makePredictions">
25+
<div class="col-sm-6 text-center" id="makePredictions">
2726
<a href="{% url 'file_select' %}" class="btn btn-primary">Make your prediction</a>
2827
</div>
29-
<div class="col-sm-4" id="PredictionsOutput">
30-
<h4>The emotion predicted for your file is: </h4>
31-
</div>
3228
</div>
3329
</div>
30+
<div class="jumbotron text-center" id="myJumbotron2" style="background-color:white">
31+
<div class="container" id="Container2">
32+
<div class="row">
33+
<div class="col-sm-12 text-center" id="PredictionsOutput">
34+
{% for pred in predictions %}
35+
<h4>The emotion of the speaker in your file is: <strong>{{ pred }}</strong> </h4>
36+
{% endfor %}
37+
</div>
38+
</div>
39+
</div>
40+
</div>
3441
</body>
35-
{% endblock %}
36-
</html>
42+
</html>
43+
{% endblock %}

App/urls.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
1-
from django.urls import path
2-
from App.views import Predict, FileView, IndexView
1+
from App.views import Predict, FileView
32
from django.conf.urls import url
43

54
app_name = 'App'
65

76
urlpatterns = [
8-
path('index/', IndexView.as_view(), name="index"),
97
url(r'^predict/$', Predict.as_view(), name="APIpredict"),
108
url(r'^upload/$', FileView.as_view(), name='APIupload'),
119
]

App/views.py

Lines changed: 40 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
from rest_framework.response import Response
1414
from django.views.generic import TemplateView
1515
from django.views.generic.edit import CreateView
16+
from rest_framework.renderers import TemplateHTMLRenderer
1617
from rest_framework.parsers import MultiPartParser, FormParser
1718

1819

@@ -97,6 +98,10 @@ class Predict(views.APIView):
9798
Example of output:
9899
[["neutral"]]
99100
"""
101+
102+
template_name = 'index.html'
103+
renderer_classes = [TemplateHTMLRenderer]
104+
100105
def __init__(self, **kwargs):
101106
super().__init__(**kwargs)
102107
modelname = 'Emotion_Voice_Detection_Model.h5'
@@ -105,24 +110,37 @@ def __init__(self, **kwargs):
105110
self.loaded_model = keras.models.load_model(os.path.join(settings.MODEL_ROOT, modelname))
106111
self.predictions = []
107112

113+
def file_elaboration(self, filepath):
114+
"""
115+
This function is used to elaborate the file used for the predictions with librosa.
116+
:param filepath:
117+
:return: predictions
118+
"""
119+
data, sampling_rate = librosa.load(filepath)
120+
try:
121+
mfccs = np.mean(librosa.feature.mfcc(y=data, sr=sampling_rate, n_mfcc=40).T, axis=0)
122+
x = np.expand_dims(mfccs, axis=2)
123+
x = np.expand_dims(x, axis=0)
124+
numpred = self.loaded_model.predict_classes(x)
125+
self.predictions.append([self.classtoemotion(numpred)])
126+
return self.predictions
127+
except Exception as err:
128+
return Response(str(err), status=status.HTTP_400_BAD_REQUEST)
129+
108130
def post(self, request):
109131
"""
110132
This method is used to making predictions on audio files previously loaded with FileView.post
111133
"""
112134
with graph.as_default():
113135
filename = request.POST.getlist('file_name').pop()
114136
filepath = str(os.path.join(settings.MEDIA_ROOT, filename))
115-
data, sampling_rate = librosa.load(filepath)
137+
predictions = self.file_elaboration(filepath)
116138
try:
117-
mfccs = np.mean(librosa.feature.mfcc(y=data, sr=sampling_rate, n_mfcc=40).T, axis=0)
118-
x = np.expand_dims(mfccs, axis=2)
119-
x = np.expand_dims(x, axis=0)
120-
numpred = self.loaded_model.predict_classes(x)
121-
self.predictions.append([self.classtoemotion(numpred)])
139+
return Response({'predictions': predictions.pop()})
122140
except Exception as err:
123141
return Response(str(err), status=status.HTTP_400_BAD_REQUEST)
124142

125-
return Response(self.predictions, status=status.HTTP_200_OK)
143+
return Response(predictions, status=status.HTTP_200_OK)
126144

127145
@staticmethod
128146
def classtoemotion(pred):
@@ -134,29 +152,18 @@ def classtoemotion(pred):
134152
Example:
135153
>>> classtoemotion(0) == neutral
136154
"""
137-
if pred == 0:
138-
pred = "neutral"
139-
return pred
140-
elif pred == 1:
141-
pred = "calm"
142-
return pred
143-
elif pred == 2:
144-
pred = "happy"
145-
return pred
146-
elif pred == 3:
147-
pred = "sad"
148-
return pred
149-
elif pred == 4:
150-
pred = "angry"
151-
return pred
152-
elif pred == 5:
153-
pred = "fearful"
154-
return pred
155-
elif pred == 6:
156-
pred = "disgust"
157-
return pred
158-
elif pred == 7:
159-
pred = "surprised"
160-
return pred
161-
else:
162-
return "Prediction out of the expected range (1-7)"
155+
156+
label_conversion = {"0": "neutral",
157+
"1": "calm",
158+
"2": "happy",
159+
"3": "sad",
160+
"4": "angry",
161+
"5": "fearful",
162+
"6": "disgust",
163+
"7": "surprised"}
164+
165+
for key in label_conversion.keys():
166+
if int(key) == pred:
167+
return label_conversion[key]
168+
else:
169+
continue
0 Bytes
Binary file not shown.

0 commit comments

Comments
 (0)