File size: 9,365 Bytes
9062d0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
813f9c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9062d0b
 
 
 
 
813f9c0
 
9062d0b
 
 
 
 
 
 
 
 
 
 
813f9c0
 
9062d0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
813f9c0
 
 
 
 
 
 
9062d0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
813f9c0
9062d0b
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
# import time
# import pickle
# import numpy as np
# from fastapi import FastAPI, Request, status, HTTPException, Depends
# from fastapi.security.api_key import APIKeyHeader
# from pydantic import BaseModel
# from typing import List
# import os
# import joblib

# app = FastAPI(
#     title="ML Music Classifier API",
#     description="Predict 'liked' or not from audio features using 8 ML models.",
#     version="1.0.0"
# )

# DEFAULT_TOKEN = "a9b7c7e8b0e44157a99c9a8c5f6a172e10b77e2b44693506a32e5a6a0cd749d0"
# api_key_header = APIKeyHeader(name="X-Token", auto_error=False)

# @app.middleware("http")
# async def add_process_time_header(request: Request, call_next):
#     start_time = time.perf_counter()
#     response = await call_next(request)
#     process_time = time.perf_counter() - start_time
#     response.headers["X-Process-Time"] = str(process_time)
#     return response

# def verify_token(x_token: str = Depends(api_key_header)):
#     if x_token != DEFAULT_TOKEN:
#         raise HTTPException(
#             status_code=status.HTTP_401_UNAUTHORIZED,
#             detail="Invalid or missing token. Use correct 'X-Token' in headers."
#         )

# class SongFeatures(BaseModel):
#     danceability: float
#     energy: float
#     key: int
#     loudness: float
#     mode: int
#     speechiness: float
#     acousticness: float
#     instrumentalness: float
#     liveness: float
#     valence: float
#     tempo: float
#     duration_ms: int
#     time_signature: int

# MODEL_DIR = "models"
# model_names = [
#     "ANN_model", "knn_model", "logistic_regression_model",
#     "neural_model", "Naive_Bayes_model",
#     "random_forest_model", "svm_model", "XGBoost_model"
# ]
# models = {}


# for name in model_names:
#     path = os.path.join(MODEL_DIR, f"{name}.pkl")
#     try:
#         models[name] = joblib.load(path)
#     except Exception as e:
#         print(f"Error loading {name}: {e}")


# @app.post("/predict/{model_name}", dependencies=[Depends(verify_token)])
# def predict(model_name: str, features: SongFeatures):
#     if model_name not in models:
#         raise HTTPException(status_code=404, detail="Model not found")

#     model = models[model_name]
#     input_array = np.array([[getattr(features, field) for field in features.model_fields]])
    
#     try:
#         prediction = model.predict(input_array)
#         return {
#             "model": model_name,
#             "input": features,
#             "prediction": int(prediction[0]),
#             "prediction_label": "liked" if int(prediction[0]) == 1 else "not_liked"
#         }
#     except Exception as e:
#         raise HTTPException(status_code=500, detail=f"Prediction error: {str(e)}")





# import time
# import pickle
# import numpy as np
# from fastapi import FastAPI, Request, status, HTTPException, Depends
# from fastapi.security.api_key import APIKeyHeader
# from pydantic import BaseModel
# from typing import List
# import os
# import joblib

# app = FastAPI(
#     title="ML Music Classifier API",
#     description="Predict 'liked' or not from audio features using 8 ML models.",
#     version="1.0.0"
# )

# DEFAULT_TOKEN = "a9b7c7e8b0e44157a99c9a8c5f6a172e10b77e2b44693506a32e5a6a0cd749d0"
# api_key_header = APIKeyHeader(name="X-Token", auto_error=False)

# @app.middleware("http")
# async def add_process_time_header(request: Request, call_next):
#     start_time = time.perf_counter()
#     response = await call_next(request)
#     process_time = time.perf_counter() - start_time
#     response.headers["X-Process-Time"] = str(process_time)
#     return response

# def verify_token(x_token: str = Depends(api_key_header)):
#     if x_token != DEFAULT_TOKEN:
#         raise HTTPException(
#             status_code=status.HTTP_401_UNAUTHORIZED,
#             detail="Invalid or missing token. Use correct 'X-Token' in headers."
#         )

# class SongFeatures(BaseModel):
#     danceability: float
#     energy: float
#     key: int
#     loudness: float
#     mode: int
#     speechiness: float
#     acousticness: float
#     instrumentalness: float
#     liveness: float
#     valence: float
#     tempo: float
#     duration_ms: int
#     time_signature: int

# MODEL_DIR = "models"
# model_names = [
#     "ANN_model", "knn_model", "logistic_regression_model",
#     "neural_model", "Naive_Bayes_model",
#     "random_forest_model", "svm_model", "XGBoost_model"
# ]
# models = {}

# for name in model_names:
#     path = os.path.join(MODEL_DIR, f"{name}.pkl")
#     try:
#         models[name] = joblib.load(path)
#         print(f"✅ Successfully loaded {name}")
#     except Exception as e:
#         print(f"❌ Error loading {name}: {e}")

# @app.get("/")
# def root():
#     return {
#         "message": "ML Music Classifier API is running!",
#         "loaded_models": len(models),
#         "available_models": list(models.keys()),
#         "endpoints": {
#             "predict": "/predict/{model_name}",
#             "docs": "/docs",
#             "health": "/health"
#         }
#     }

# @app.get("/health")
# def health_check():
#     return {
#         "status": "healthy",
#         "loaded_models": len(models),
#         "available_models": list(models.keys())
#     }

# @app.post("/predict/{model_name}", dependencies=[Depends(verify_token)])
# def predict(model_name: str, features: SongFeatures):
#     if model_name not in models:
#         raise HTTPException(status_code=404, detail="Model not found")

#     model = models[model_name]
#     input_array = np.array([[getattr(features, field) for field in features.model_fields]])
    
#     try:
#         prediction = model.predict(input_array)
#         return {
#             "model": model_name,
#             "input": features.dict(),
#             "prediction": int(prediction[0]),
#             "prediction_label": "liked" if int(prediction[0]) == 1 else "not_liked"
#         }
#     except Exception as e:
#         raise HTTPException(status_code=500, detail=f"Prediction error: {str(e)}")

# if __name__ == "__main__":
#     import uvicorn
#     uvicorn.run(app, host="0.0.0.0", port=7860)




import time
import pickle
import numpy as np
from fastapi import FastAPI, Request, status, HTTPException, Depends
from fastapi.security.api_key import APIKeyHeader
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse
from pydantic import BaseModel
from typing import List
import os
import joblib

app = FastAPI(
    title="ML Music Classifier API",
    description="Predict 'liked' or not from audio features using 8 ML models.",
    version="1.0.0"
)

templates = Jinja2Templates(directory="templates")

DEFAULT_TOKEN = "a9b7c7e8b0e44157a99c9a8c5f6a172e10b77e2b44693506a32e5a6a0cd749d0"
api_key_header = APIKeyHeader(name="X-Token", auto_error=False)

@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    start_time = time.perf_counter()
    response = await call_next(request)
    process_time = time.perf_counter() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    return response

def verify_token(x_token: str = Depends(api_key_header)):
    if x_token != DEFAULT_TOKEN:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid or missing token. Use correct 'X-Token' in headers."
        )

class SongFeatures(BaseModel):
    danceability: float
    energy: float
    key: int
    loudness: float
    mode: int
    speechiness: float
    acousticness: float
    instrumentalness: float
    liveness: float
    valence: float
    tempo: float
    duration_ms: int
    time_signature: int

MODEL_DIR = "models"
model_names = [
    "ANN_model", "knn_model", "logistic_regression_model",
    "neural_model", "Naive_Bayes_model",
    "random_forest_model", "svm_model", "XGBoost_model"
]
models = {}

for name in model_names:
    path = os.path.join(MODEL_DIR, f"{name}.pkl")
    try:
        models[name] = joblib.load(path)
        print(f"✅ Successfully loaded {name}")
    except Exception as e:
        print(f"❌ Error loading {name}: {e}")

@app.get("/", response_class=HTMLResponse)
def home(request: Request):
    return templates.TemplateResponse("index.html", {
        "request": request,
        "models": list(models.keys())
    })
    
@app.get("/health")
def health_check():
    return {
        "status": "healthy",
        "loaded_models": len(models),
        "available_models": list(models.keys())
    }

@app.post("/predict/{model_name}", dependencies=[Depends(verify_token)])
def predict(model_name: str, features: SongFeatures):
    if model_name not in models:
        raise HTTPException(status_code=404, detail="Model not found")

    model = models[model_name]
    input_array = np.array([[getattr(features, field) for field in features.model_fields]])
    
    try:
        prediction = model.predict(input_array)
        return {
            "model": model_name,
            "input": features.dict(),
            "prediction": int(prediction[0]),
            "prediction_label": "liked" if int(prediction[0]) == 1 else "Not liked"
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Prediction error: {str(e)}")

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=7860)