yufii commited on
Commit
b5f20ab
·
verified ·
1 Parent(s): e4d9f27

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +127 -137
app.py CHANGED
@@ -1,137 +1,127 @@
1
- import logging
2
- from contextlib import contextmanager
3
- from fastapi import FastAPI, File, UploadFile, HTTPException
4
- from fastapi.responses import JSONResponse
5
- from fastapi.middleware.cors import CORSMiddleware
6
- import tempfile
7
- import os
8
- import librosa
9
- import numpy as np
10
- import keras
11
-
12
- from fastapi import FastAPI, File, UploadFile, HTTPException
13
- from io import BytesIO
14
- from models import User, Course, connection
15
- from forms import UserRegistration, UserLoginForm
16
- from fastapi.responses import JSONResponse
17
- from utils import (
18
- create_cnn_model,
19
- get_features,
20
- extract_features,
21
- pad_or_trim,
22
- noise,
23
- stretch,
24
- pitch,
25
- )
26
- import numpy as np
27
- import tensorflow as tf
28
- import os
29
- from fastapi.middleware.cors import CORSMiddleware
30
- import logging
31
-
32
- app = FastAPI(port=8000)
33
-
34
- # origins = [
35
- # "http://localhost:3000",
36
- # "http://127.0.0.1:3000",
37
- # # Add more origins if needed
38
- # ]
39
-
40
- app.add_middleware(
41
- CORSMiddleware,
42
- allow_origins=["*"],#origins,
43
- allow_credentials=True,
44
- allow_methods=["*"],
45
- allow_headers=["*"],
46
- )
47
-
48
- filepath = os.path.abspath("cnn_1_v6_final_model.h5")
49
- if not os.path.exists(filepath):
50
- raise FileNotFoundError(f"Model file not found at {filepath}")
51
-
52
- model = keras.models.load_model(filepath, compile=False)
53
- target_shape = (32, 200)
54
-
55
-
56
- @app.post("/save-audio")
57
- async def save_audio(file: UploadFile = File(...)):
58
- if not file.content_type.startswith("audio/"):
59
- raise HTTPException(status_code=400, detail="Invalid file type")
60
-
61
- file_path = os.path.join("audio", file.filename)
62
- os.makedirs("audio", exist_ok=True)
63
- try:
64
- with open(file_path, "wb") as f:
65
- content = await file.read()
66
- f.write(content)
67
- return JSONResponse(
68
- content={"message": "File saved successfully", "filePath": file_path},
69
- status_code=200,
70
- )
71
- except Exception as e:
72
- return JSONResponse(content={"error": str(e)}, status_code=500)
73
-
74
-
75
- logging.basicConfig(
76
- level=logging.INFO,
77
- filename="server.log",
78
- filemode="w",
79
- format="%(asctime)s - %(levelname)s - %(message)s",
80
- )
81
-
82
-
83
- @contextmanager
84
- def temporary_audio_file(audio_bytes):
85
- with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:
86
- tmp_file.write(audio_bytes)
87
- tmp_file.flush() # Make sure data is written to disk
88
- tmp_filename = tmp_file.name
89
- try:
90
- yield tmp_filename
91
- finally:
92
- if os.path.exists(tmp_filename):
93
- os.remove(tmp_filename)
94
-
95
-
96
- @app.post("/process-audio")
97
- async def process_audio(audio: UploadFile = File(...)):
98
- if audio.content_type != "audio/mpeg":
99
- raise HTTPException(
100
- status_code=400, detail="Invalid file type. Only MP3 files are supported."
101
- )
102
-
103
- try:
104
- audio_bytes = await audio.read()
105
- logging.info(
106
- f"Received audio bytes: {len(audio_bytes)} bytes"
107
- ) # Log size of audio bytes
108
- with temporary_audio_file(audio_bytes) as tmp_filename:
109
- logging.info(f"Temporary file created: {tmp_filename}")
110
- audio_data, sample_rate = librosa.load(tmp_filename, sr=None)
111
- logging.info(
112
- f"Audio loaded: sample rate = {sample_rate}, data shape = {audio_data.shape}"
113
- )
114
- if not audio_data.any() or sample_rate == 0:
115
- raise ValueError("Empty or invalid audio data.")
116
-
117
- features = extract_features(audio_data, sample_rate)
118
- logging.info(f"Features extracted: shape = {features.shape}")
119
- target_shape = (1, model.input_shape[1])
120
- features = pad_or_trim(features, target_shape[1])
121
- features = np.expand_dims(features, axis=0)
122
-
123
- prediction = model.predict(features)
124
- # Add interpretation of prediction here (e.g., class labels)
125
- logging.info(f"Prediction: {prediction}")
126
- return {"prediction": prediction.tolist()}
127
-
128
- except librosa.util.exceptions.ParameterError as e:
129
- logging.error(f"Librosa error: {e}")
130
- raise HTTPException(status_code=400, detail=f"Invalid audio file: {e}")
131
- except ValueError as e:
132
- logging.error(f"Value error: {e}")
133
- raise HTTPException(status_code=400, detail=f"Invalid audio data: {e}")
134
- except Exception as e:
135
- logging.exception(f"Error processing audio: {e}") # Log the full traceback
136
- raise HTTPException(status_code=500, detail="Internal server error")
137
-
 
1
+ import logging
2
+ from contextlib import contextmanager
3
+ from fastapi import FastAPI, File, UploadFile, HTTPException
4
+ from fastapi.responses import JSONResponse
5
+ from fastapi.middleware.cors import CORSMiddleware
6
+ import tempfile
7
+ import os
8
+ import librosa
9
+ import numpy as np
10
+ import keras
11
+ from utils import (
12
+ create_cnn_model,
13
+ get_features,
14
+ extract_features,
15
+ pad_or_trim,
16
+ noise,
17
+ stretch,
18
+ pitch,
19
+ )
20
+ import numpy as np
21
+
22
+ app = FastAPI(port=8000)
23
+
24
+ # origins = [
25
+ # "http://localhost:3000",
26
+ # "http://127.0.0.1:3000",
27
+ # # Add more origins if needed
28
+ # ]
29
+
30
+ app.add_middleware(
31
+ CORSMiddleware,
32
+ allow_origins=["*"],#origins,
33
+ allow_credentials=True,
34
+ allow_methods=["*"],
35
+ allow_headers=["*"],
36
+ )
37
+
38
+ filepath = os.path.abspath("cnn_1_v6_final_model.h5")
39
+ if not os.path.exists(filepath):
40
+ raise FileNotFoundError(f"Model file not found at {filepath}")
41
+
42
+ model = keras.models.load_model(filepath, compile=False)
43
+ target_shape = (32, 200)
44
+
45
+
46
+ @app.post("/save-audio")
47
+ async def save_audio(file: UploadFile = File(...)):
48
+ if not file.content_type.startswith("audio/"):
49
+ raise HTTPException(status_code=400, detail="Invalid file type")
50
+
51
+ file_path = os.path.join("audio", file.filename)
52
+ os.makedirs("audio", exist_ok=True)
53
+ try:
54
+ with open(file_path, "wb") as f:
55
+ content = await file.read()
56
+ f.write(content)
57
+ return JSONResponse(
58
+ content={"message": "File saved successfully", "filePath": file_path},
59
+ status_code=200,
60
+ )
61
+ except Exception as e:
62
+ return JSONResponse(content={"error": str(e)}, status_code=500)
63
+
64
+
65
+ logging.basicConfig(
66
+ level=logging.INFO,
67
+ filename="server.log",
68
+ filemode="w",
69
+ format="%(asctime)s - %(levelname)s - %(message)s",
70
+ )
71
+
72
+
73
+ @contextmanager
74
+ def temporary_audio_file(audio_bytes):
75
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:
76
+ tmp_file.write(audio_bytes)
77
+ tmp_file.flush() # Make sure data is written to disk
78
+ tmp_filename = tmp_file.name
79
+ try:
80
+ yield tmp_filename
81
+ finally:
82
+ if os.path.exists(tmp_filename):
83
+ os.remove(tmp_filename)
84
+
85
+
86
+ @app.post("/process-audio")
87
+ async def process_audio(audio: UploadFile = File(...)):
88
+ if audio.content_type != "audio/mpeg":
89
+ raise HTTPException(
90
+ status_code=400, detail="Invalid file type. Only MP3 files are supported."
91
+ )
92
+
93
+ try:
94
+ audio_bytes = await audio.read()
95
+ logging.info(
96
+ f"Received audio bytes: {len(audio_bytes)} bytes"
97
+ ) # Log size of audio bytes
98
+ with temporary_audio_file(audio_bytes) as tmp_filename:
99
+ logging.info(f"Temporary file created: {tmp_filename}")
100
+ audio_data, sample_rate = librosa.load(tmp_filename, sr=None)
101
+ logging.info(
102
+ f"Audio loaded: sample rate = {sample_rate}, data shape = {audio_data.shape}"
103
+ )
104
+ if not audio_data.any() or sample_rate == 0:
105
+ raise ValueError("Empty or invalid audio data.")
106
+
107
+ features = extract_features(audio_data, sample_rate)
108
+ logging.info(f"Features extracted: shape = {features.shape}")
109
+ target_shape = (1, model.input_shape[1])
110
+ features = pad_or_trim(features, target_shape[1])
111
+ features = np.expand_dims(features, axis=0)
112
+
113
+ prediction = model.predict(features)
114
+ # Add interpretation of prediction here (e.g., class labels)
115
+ logging.info(f"Prediction: {prediction}")
116
+ return {"prediction": prediction.tolist()}
117
+
118
+ except librosa.util.exceptions.ParameterError as e:
119
+ logging.error(f"Librosa error: {e}")
120
+ raise HTTPException(status_code=400, detail=f"Invalid audio file: {e}")
121
+ except ValueError as e:
122
+ logging.error(f"Value error: {e}")
123
+ raise HTTPException(status_code=400, detail=f"Invalid audio data: {e}")
124
+ except Exception as e:
125
+ logging.exception(f"Error processing audio: {e}") # Log the full traceback
126
+ raise HTTPException(status_code=500, detail="Internal server error")
127
+