Spaces:
Sleeping
Sleeping
Update app.py
Browse files
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 |
-
|
| 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 |
-
|
| 113 |
-
)
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 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 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|