Mohammedelhakim commited on
Commit
c846a2e
·
1 Parent(s): 4fa298b

Add application file

Browse files
Dockerfile ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.13
2
+
3
+ RUN useradd -m -u 1000 user
4
+ USER user
5
+ ENV PATH="/home/user/.local/bin:$PATH"
6
+
7
+ WORKDIR /app
8
+
9
+ COPY --chown=user ./requirements.txt requirements.txt
10
+ RUN pip install --no-cache-dir --upgrade -r requirements.txt
11
+
12
+ COPY --chown=user . /app
13
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
app.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+ from fastapi import FastAPI, UploadFile, File, HTTPException
3
+ import traceback
4
+ import numpy as np
5
+ import librosa
6
+ import joblib
7
+ import tempfile
8
+ import os
9
+ import tensorflow as tf
10
+ import tensorflow_hub as hub
11
+
12
+ # =========================
13
+ # Configuration
14
+ # =========================
15
+ SR = 16000
16
+
17
+ DETECTOR_MODEL_PATH = "detection_models/yamnet_lr_model.joblib"
18
+ DETECTOR_SCALER_PATH = "detection_models/scaler_yamnet.pkl"
19
+ DETECTOR_PCA_PATH = "detection_models/pca_yamnet.pkl"
20
+
21
+ CLASS_ENSEMBLE_PATH = "classification_models/babycry_ensemble.pkl"
22
+ CLASS_SCALER_PATH = "classification_models/scaler.pkl"
23
+ CLASS_SELECTOR_PATH = "classification_models/feature_selector.pkl"
24
+ CLASS_LE_PATH = "classification_models/label_encoder.pkl"
25
+
26
+ # =========================
27
+ # Load models (ONCE)
28
+ # =========================
29
+ yamnet = hub.load("https://tfhub.dev/google/yamnet/1")
30
+
31
+ det_model = joblib.load(DETECTOR_MODEL_PATH)
32
+ det_scaler = joblib.load(DETECTOR_SCALER_PATH)
33
+ det_pca = joblib.load(DETECTOR_PCA_PATH)
34
+
35
+ ensemble = joblib.load(CLASS_ENSEMBLE_PATH)
36
+ cls_scaler = joblib.load(CLASS_SCALER_PATH)
37
+ feature_selector = joblib.load(CLASS_SELECTOR_PATH)
38
+ label_encoder = joblib.load(CLASS_LE_PATH)
39
+
40
+ # =========================
41
+ # Feature Extraction
42
+ # =========================
43
+ def extract_yamnet_embedding(path):
44
+ wav, _ = librosa.load(path, sr=SR, mono=True)
45
+ waveform = tf.convert_to_tensor(wav, dtype=tf.float32)
46
+
47
+ _, embeddings, _ = yamnet(waveform)
48
+ emb = embeddings.numpy()
49
+
50
+ mean_emb = np.mean(emb, axis=0)
51
+ std_emb = np.std(emb, axis=0)
52
+
53
+ return np.concatenate([mean_emb, std_emb]).reshape(1, -1)
54
+
55
+ def extract_classification_features(path):
56
+ y, sr = librosa.load(path, sr=SR)
57
+ stft = np.abs(librosa.stft(y))
58
+
59
+ mfcc = np.mean(librosa.feature.mfcc(y=y, sr=sr, n_mfcc=40), axis=1)
60
+ chroma = np.mean(librosa.feature.chroma_stft(S=stft, sr=sr), axis=1)
61
+ mel = np.mean(librosa.feature.melspectrogram(y=y, sr=sr), axis=1)
62
+ contrast = np.mean(librosa.feature.spectral_contrast(S=stft, sr=sr), axis=1)
63
+ tonnetz = np.mean(librosa.feature.tonnetz(y=librosa.effects.harmonic(y), sr=sr), axis=1)
64
+
65
+ # Time-domain features (ensure 1D)
66
+ zero_crossing = np.mean(librosa.feature.zero_crossing_rate(y))
67
+ energy = np.mean(librosa.feature.rms(y=y))
68
+
69
+ # Spectral features (ensure 1D)
70
+ spec_centroid = np.mean(librosa.feature.spectral_centroid(y=y, sr=sr))
71
+ spec_bandwidth = np.mean(librosa.feature.spectral_bandwidth(y=y, sr=sr))
72
+ spec_rolloff = np.mean(librosa.feature.spectral_rolloff(y=y, sr=sr))
73
+ spec_flatness = np.mean(librosa.feature.spectral_flatness(y=y))
74
+
75
+ combined_features = np.concatenate([
76
+ mfcc[:40], # First 40 MFCCs
77
+ chroma[:12], # 12 chroma features
78
+ mel[:40], # First 40 mel features
79
+ contrast[:7], # 7 contrast features
80
+ tonnetz[:6], # 6 tonnetz features
81
+ [zero_crossing], # 1 feature
82
+ [energy], # 1 feature
83
+ [spec_centroid], # 1 feature
84
+ [spec_bandwidth], # 1 feature
85
+ [spec_rolloff], # 1 feature
86
+ [spec_flatness] # 1 feature
87
+ ])
88
+
89
+ return combined_features.reshape(1,-1)
90
+
91
+
92
+ # =========================
93
+ # Detection & Classification
94
+ # =========================
95
+ def detect_is_cry(path, threshold):
96
+ feat = extract_yamnet_embedding(path)
97
+ feat = det_scaler.transform(feat)
98
+ feat = det_pca.transform(feat)
99
+
100
+ prob = det_model.predict_proba(feat)[0][0]
101
+
102
+ is_cry = bool(prob >= threshold) # 🔥 الحل هنا
103
+ return is_cry, float(prob)
104
+
105
+
106
+ def classify_cry(path, conf_threshold):
107
+ feat = extract_classification_features(path)
108
+ current_len = feat.shape[1]
109
+ expected_len = getattr(cls_scaler, "n_features_in_", None)
110
+
111
+ if expected_len is not None and current_len != expected_len:
112
+ raise HTTPException(
113
+ status_code=500,
114
+ detail=f"Feature length mismatch: got {current_len}, expected {expected_len}"
115
+ )
116
+ print("feat shape at classify_cry:", feat.shape) # should be (1, 111)
117
+ print("scaler expects:", cls_scaler.n_features_in_) # should be 111
118
+
119
+ feat_scaled = cls_scaler.transform(feat)
120
+ feat_selector = feature_selector.transform(feat_scaled)
121
+
122
+ probs = ensemble.predict_proba(feat_selector)[0]
123
+ max_prob = float(np.max(probs))
124
+
125
+ if max_prob < conf_threshold:
126
+ return "Normal / Not a Cry", None, max_prob
127
+
128
+ label = label_encoder.inverse_transform([np.argmax(probs)])[0]
129
+ return label, probs.tolist(), max_prob
130
+
131
+ # =========================
132
+ # FastAPI App
133
+ # =========================
134
+ app = FastAPI(
135
+ title="Baby Cry Detection & Classification API",
136
+ version="1.0"
137
+ )
138
+
139
+ @app.post("/predict")
140
+ async def predict(
141
+ file: UploadFile = File(...),
142
+ detection_threshold: float = 0.212,
143
+ classification_threshold: float = 0.6
144
+ ):
145
+ if not file.filename.lower().endswith((".wav", ".mp3", ".flac", ".ogg")):
146
+ raise HTTPException(status_code=400, detail="Invalid audio format")
147
+
148
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp:
149
+ tmp.write(await file.read())
150
+ tmp_path = tmp.name
151
+
152
+ try:
153
+ try:
154
+ is_cry, cry_prob = detect_is_cry(tmp_path, detection_threshold)
155
+
156
+ response = {
157
+ "filename": file.filename,
158
+ "cry_probability": cry_prob,
159
+ "is_cry": is_cry,
160
+ }
161
+
162
+ if not is_cry:
163
+ response["result"] = "Not a cry"
164
+ return response
165
+
166
+ label, probs, confidence = classify_cry(
167
+ tmp_path,
168
+ classification_threshold
169
+ )
170
+
171
+ response.update({
172
+ "result": label,
173
+ "confidence": confidence,
174
+ "class_probabilities": probs,
175
+ })
176
+
177
+ return response
178
+ except Exception as e:
179
+ # Log full traceback to the server console
180
+ traceback.print_exc()
181
+ # Return the error message so you see it in the client
182
+ raise HTTPException(
183
+ status_code=500,
184
+ detail=f"Prediction failed: {e}"
185
+ )
186
+ finally:
187
+ os.remove(tmp_path)
classification_models/babycry_ensemble.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e0a01a2aa3a97291870a49b6588debc071458e471d88d7b6395ce337e6f7711a
3
+ size 67580166
classification_models/feature_selector.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:03d498641f16a348d33e5a02b9a82a2971df660327ae3d47ebccab6f0cd2bf09
3
+ size 19013111
classification_models/label_encoder.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:71981ceb1bd0cb5640bb42385899834f2d0686c6b453f4cddda9e2710f63ed1f
3
+ size 527
classification_models/scaler.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:88d831a8a7d9411bc67dc1a756f2d470fc6a73a4b6957153f2accb280fff4bb4
3
+ size 3231
detection_models/emb_test.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:099f6632bc63a5ddb94cd3c0614bebca33a14d46a597b953464710387ebd09a4
3
+ size 2424960
detection_models/emb_train.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bc02a2176f4e07b682e3fe50e1704b9c2b1d90688a2179c6dcdc29d377fca04a
3
+ size 11296896
detection_models/emb_val.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:27e58492b2bc629328a306a1c6b923b23b82b4867c67d4bcd74889cd2477a5bb
3
+ size 2416768
detection_models/pca_yamnet.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:215e13aff4ff1477e1380bbd8b619fc022458d9d3df061dea4b4b1b389c44614
3
+ size 2109354
detection_models/scaler_yamnet.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5f3944740c79f5418f0a9cc950a17a62a5112cca206e3aa781a9c2c80a949cb7
3
+ size 49735
detection_models/y_test.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4ae89854a1c5ee482237593e8dddb7ffb4b3ef29cc91731347fec99ef5358140
3
+ size 1312
detection_models/y_train.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ac93eb0c226983fc38c5791c455d57087161fd9c8f5960f16c6c343bc65b6ca9
3
+ size 5644
detection_models/y_val.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:95ec7190d712d7e97f39ddd58361b209d7b7d680eb5fc6552ec2c9ec3dacde52
3
+ size 1308
detection_models/yamnet_lr_model.joblib ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ca0150d00aeffbe724b53039a072c1ddfc42288607c0ed11e5d46c8ed81b4cc8
3
+ size 1835
requirements.txt ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ fastapi==0.128.6
3
+ uvicorn==0.40.0
4
+ python-multipart==0.0.22
5
+ numpy==2.3.5
6
+ scipy==1.17.0
7
+ joblib==1.4.2
8
+ scikit-learn==1.8.0
9
+ librosa==0.11.0
10
+ soundfile==0.13.1
11
+ audioread==3.1.0
12
+ soxr==1.0.0
13
+ tensorflow==2.20.0
14
+ tensorflow-hub==0.16.1