moghit/Audio_Classification
0
1from flask import Flask, render_template, request, jsonify
2import os
3from predict import model, words, extract_features, sr
4import librosa
5import numpy as np
6# this web app was designed by achraf
7app = Flask(__name__)
8
9# Mapping des mots vers les chiffres
10word_to_digit = {
11 'zero': '0', 'one': '1', 'two': '2', 'three': '3', 'four': '4',
12 'five': '5', 'six': '6', 'seven': '7', 'eight': '8', 'nine': '9'
13}
14
15def report_with_probabilities(prediction):
16 """
17 Fonction modifiée pour retourner le meilleur résultat ET toutes les probabilités
18 """
19 test = []
20 values = prediction[0]
21 for i in range(10):
22 value = np.round(values[i] * 100, 2)
23 value = round(float(value), 2)
24 word = str(words[i])
25 test.append((value, word))
26
27 # Trier par probabilité décroissante
28 values_sorted = sorted(test, key=lambda item: item[0], reverse=True)
29
30 # Retourner le meilleur résultat et toutes les probabilités
31 best_prediction = values_sorted[0][1]
32 all_probabilities = [{"word": word, "probability": prob} for prob, word in values_sorted]
33
34 return best_prediction, all_probabilities
35
36@app.route('/')
37def home():
38 return render_template("index.html")
39
40@app.route('/predict')
41def predict_page():
42 return render_template("predict.html")
43import subprocess
44
45@app.route('/upload', methods=['POST'])
46def upload_audio():
47 if 'audio' not in request.files:
48 return jsonify({'error': 'No audio file found', 'success': False}), 400
49
50 # Sauvegarde du fichier
51 audio_file = request.files['audio']
52 audio_path = 'recording.wav'
53
54 audio_file.save(audio_path)
55 subprocess.run(["ffmpeg", "-y", "-i", "recording.wav", "recording.wav"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
56
57 try:
58 # Chargement de l'audio avec librosa (compatible avec predict.py)
59 audio_signal, _ = librosa.load("recording.wav", sr=sr)
60 # Utilisation des fonctions importées de predict.py
61 X_test = extract_features(audio_signal, sr)
62 prediction = model.predict(X_test)
63 # Utilisation de notre fonction modifiée pour obtenir toutes les probabilités
64 predicted_word, all_probabilities = report_with_probabilities(prediction)
65
66 # Conversion en chiffre
67 predicted_digit = word_to_digit.get(predicted_word.lower(), '?')
68
69 print(f"Predicted word: {predicted_word}, Predicted digit: {predicted_digit}")
70 # Nettoyage
71 os.remove(audio_path)
72
73 return jsonify({
74 'success': True,
75 'prediction': predicted_word,
76 'digit': predicted_digit,
77 'display': f"{predicted_word.capitalize()} ({predicted_digit})",
78 'probabilities': all_probabilities
79 })
80
81 except Exception as e:
82 if os.path.exists(audio_path):
83 os.remove(audio_path)
84 return jsonify({
85 'success': False,
86 'error': str(e)
87 }), 500
88
89if __name__ == '__main__':
90 app.run(debug=True)