JigneshPrajapati18 commited on
Commit
c9a29bf
·
verified ·
1 Parent(s): 32ef455

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +8 -542
app.py CHANGED
@@ -1,549 +1,16 @@
1
- # from fastapi import FastAPI, HTTPException, Depends, status
2
- # from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
3
- # from pydantic import BaseModel
4
- # from typing import List, Optional
5
- # from datetime import datetime, timedelta
6
- # import jwt
7
- # from passlib.context import CryptContext
8
-
9
- # app = FastAPI()
10
-
11
- # # JWT Configuration
12
- # SECRET_KEY = "123456" # Change this to a secure random key
13
- # ALGORITHM = "HS256"
14
- # ACCESS_TOKEN_EXPIRE_MINUTES = 30
15
-
16
- # # Password hashing
17
- # pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
18
-
19
- # # Security scheme
20
- # security = HTTPBearer()
21
-
22
- # # Models
23
- # class Student(BaseModel):
24
- # rollno: int
25
- # name: str
26
- # age: int
27
- # phone: str
28
-
29
- # class User(BaseModel):
30
- # username: str
31
- # email: str
32
-
33
- # class UserCreate(BaseModel):
34
- # username: str
35
- # email: str
36
- # password: str
37
-
38
- # class UserLogin(BaseModel):
39
- # username: str
40
- # password: str
41
-
42
- # class Token(BaseModel):
43
- # access_token: str
44
- # token_type: str
45
-
46
- # # In-memory databases
47
- # Student_db: List[Student] = []
48
- # users_db: List[dict] = [] # Store users with hashed passwords
49
-
50
- # # Utility functions
51
- # def hash_password(password: str) -> str:
52
- # return pwd_context.hash(password)
53
-
54
- # def verify_password(plain_password: str, hashed_password: str) -> bool:
55
- # return pwd_context.verify(plain_password, hashed_password)
56
-
57
- # def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
58
- # to_encode = data.copy()
59
- # if expires_delta:
60
- # expire = datetime.utcnow() + expires_delta
61
- # else:
62
- # expire = datetime.utcnow() + timedelta(minutes=15)
63
- # to_encode.update({"exp": expire})
64
- # encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
65
- # return encoded_jwt
66
-
67
- # def verify_token(credentials: HTTPAuthorizationCredentials = Depends(security)):
68
- # token = credentials.credentials
69
- # try:
70
- # payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
71
- # username: str = payload.get("sub")
72
- # if username is None:
73
- # raise HTTPException(
74
- # status_code=status.HTTP_401_UNAUTHORIZED,
75
- # detail="Invalid authentication credentials",
76
- # headers={"WWW-Authenticate": "Bearer"},
77
- # )
78
- # return username
79
- # except jwt.PyJWTError:
80
- # raise HTTPException(
81
- # status_code=status.HTTP_401_UNAUTHORIZED,
82
- # detail="Invalid authentication credentials",
83
- # headers={"WWW-Authenticate": "Bearer"},
84
- # )
85
-
86
- # def get_user_by_username(username: str):
87
- # for user in users_db:
88
- # if user["username"] == username:
89
- # return user
90
- # return None
91
-
92
- # # Authentication endpoints
93
- # @app.post("/register", response_model=dict)
94
- # def register_user(user: UserCreate):
95
- # # Check if user already exists
96
- # if get_user_by_username(user.username):
97
- # raise HTTPException(
98
- # status_code=400,
99
- # detail="Username already registered"
100
- # )
101
-
102
- # # Hash password and store user
103
- # hashed_password = hash_password(user.password)
104
- # user_dict = {
105
- # "username": user.username,
106
- # "email": user.email,
107
- # "hashed_password": hashed_password
108
- # }
109
- # users_db.append(user_dict)
110
-
111
- # return {"message": "User registered successfully"}
112
-
113
- # @app.post("/login", response_model=Token)
114
- # def login_user(user_credentials: UserLogin):
115
- # user = get_user_by_username(user_credentials.username)
116
-
117
- # if not user or not verify_password(user_credentials.password, user["hashed_password"]):
118
- # raise HTTPException(
119
- # status_code=status.HTTP_401_UNAUTHORIZED,
120
- # detail="Incorrect username or password",
121
- # headers={"WWW-Authenticate": "Bearer"},
122
- # )
123
-
124
- # access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
125
- # access_token = create_access_token(
126
- # data={"sub": user["username"]}, expires_delta=access_token_expires
127
- # )
128
-
129
- # return {"access_token": access_token, "token_type": "bearer"}
130
-
131
- # # Protected student endpoints
132
- # @app.post("/Student/", response_model=Student)
133
- # def create_student(student: Student, current_user: str = Depends(verify_token)):
134
- # for existing in Student_db:
135
- # if existing.rollno == student.rollno:
136
- # raise HTTPException(status_code=400, detail="Student roll number already exists")
137
- # Student_db.append(student)
138
- # return student
139
-
140
- # @app.get("/Student/", response_model=List[Student])
141
- # def get_all_student_details(current_user: str = Depends(verify_token)):
142
- # return Student_db
143
-
144
- # @app.get("/Student/{rollno}", response_model=Student)
145
- # def get_student_details(rollno: int, current_user: str = Depends(verify_token)):
146
- # for student in Student_db:
147
- # if student.rollno == rollno:
148
- # return student
149
- # raise HTTPException(status_code=404, detail="Student not found")
150
-
151
- # @app.put("/Student/{rollno}", response_model=Student)
152
- # def update_student(rollno: int, updated_student: Student, current_user: str = Depends(verify_token)):
153
- # for index, student in enumerate(Student_db):
154
- # if student.rollno == rollno:
155
- # Student_db[index] = updated_student
156
- # return updated_student
157
- # raise HTTPException(status_code=404, detail="Student not found")
158
-
159
- # @app.delete("/Student/{rollno}")
160
- # def delete_student(rollno: int, current_user: str = Depends(verify_token)):
161
- # for index, student in enumerate(Student_db):
162
- # if student.rollno == rollno:
163
- # del Student_db[index]
164
- # return {"message": "Student deleted successfully"}
165
- # raise HTTPException(status_code=404, detail="Student not found")
166
-
167
- # # Protected user info endpoint
168
- # @app.get("/me", response_model=User)
169
- # def get_current_user_info(current_user: str = Depends(verify_token)):
170
- # user = get_user_by_username(current_user)
171
- # if not user:
172
- # raise HTTPException(status_code=404, detail="User not found")
173
- # return User(username=user["username"], email=user["email"])
174
-
175
-
176
-
177
- # from fastapi import FastAPI, HTTPException, Depends, status, Request
178
- # from pydantic import BaseModel
179
- # from typing import List
180
- # import json
181
- # import os
182
- # import random
183
- # import string
184
-
185
- # app = FastAPI()
186
-
187
- # VALID_USERNAME = "Jignesh"
188
- # VALID_PASSWORD = "123456"
189
-
190
- # active_tokens = set()
191
-
192
- # class Login(BaseModel):
193
- # username: str
194
- # password: str
195
-
196
- # class Student(BaseModel):
197
- # rollno: int
198
- # name: str
199
- # age: int
200
- # phone: str
201
-
202
- # def create_random_token() -> str:
203
- # length = random.randint(32, 64)
204
- # characters = string.ascii_letters + string.digits + '-_'
205
- # return ''.join(random.choice(characters) for _ in range(length))
206
-
207
- # def validate_token(token: str) -> bool:
208
- # return token in active_tokens
209
-
210
- # def load_data():
211
- # if os.path.exists("students.json"):
212
- # with open("students.json", "r") as f:
213
- # return json.load(f)
214
- # return []
215
-
216
- # def save_data():
217
- # with open("students.json", "w") as f:
218
- # json.dump(students, f, indent=2)
219
-
220
- # students = load_data()
221
-
222
- # @app.post("/login/")
223
- # def login(user: Login):
224
- # if user.username != VALID_USERNAME or user.password != VALID_PASSWORD:
225
- # raise HTTPException(status_code=400, detail="Invalid credentials")
226
-
227
- # access_token = create_random_token()
228
- # active_tokens.add(access_token)
229
- # return {"access_token": access_token, "token_type": "bearer"}
230
-
231
- # def get_current_user(request: Request):
232
- # token = request.headers.get("authorization")
233
- # if not token:
234
- # raise HTTPException(
235
- # status_code=status.HTTP_401_UNAUTHORIZED,
236
- # detail="Not authenticated",
237
- # headers={"WWW-Authenticate": "Bearer"},
238
- # )
239
-
240
- # if not validate_token(token):
241
- # raise HTTPException(
242
- # status_code=status.HTTP_401_UNAUTHORIZED,
243
- # detail="Invalid or expired token",
244
- # headers={"WWW-Authenticate": "Bearer"},
245
- # )
246
- # return True
247
-
248
- # @app.post("/students/")
249
- # def create_student(student: Student, current_user: bool = Depends(get_current_user)):
250
- # if any(s["rollno"] == student.rollno for s in students):
251
- # raise HTTPException(status_code=400, detail="Roll number already exists")
252
-
253
- # students.append(student.dict())
254
- # save_data()
255
- # return {"message": "Student added successfully", "student": student}
256
-
257
- # @app.get("/students/")
258
- # def get_all_students(current_user: bool = Depends(get_current_user)):
259
- # return students
260
-
261
- # @app.get("/students/{rollno}")
262
- # def get_student(rollno: int, current_user: bool = Depends(get_current_user)):
263
- # student = next((s for s in students if s["rollno"] == rollno), None)
264
- # if not student:
265
- # raise HTTPException(status_code=404, detail="Student not found")
266
- # return student
267
-
268
- # @app.put("/students/{rollno}")
269
- # def update_student(rollno: int, student: Student, current_user: bool = Depends(get_current_user)):
270
- # for i, s in enumerate(students):
271
- # if s["rollno"] == rollno:
272
- # students[i] = student.dict()
273
- # save_data()
274
- # return {"message": "Student updated", "student": student}
275
- # raise HTTPException(status_code=404, detail="Student not found")
276
-
277
- # @app.delete("/students/{rollno}")
278
- # def delete_student(rollno: int, current_user: bool = Depends(get_current_user)):
279
- # for i, s in enumerate(students):
280
- # if s["rollno"] == rollno:
281
- # students.pop(i)
282
- # save_data()
283
- # return {"message": "Student deleted"}
284
- # raise HTTPException(status_code=404, detail="Student not found")
285
-
286
- # import time
287
- # from fastapi import FastAPI, HTTPException, Request, status, Depends
288
- # from fastapi.security.api_key import APIKeyHeader
289
- # from pydantic import BaseModel
290
- # import json
291
- # import os
292
-
293
- # app = FastAPI()
294
-
295
- # # Authentication configuration
296
- # DEFAULT_TOKEN = "a9b7c7e8b0e44157a99c9a8c5f6a172e10b77e2b44693506a32e5a6a0cd749d0"
297
- # api_key_header = APIKeyHeader(name="Token", auto_error=False)
298
-
299
- # def verify_token(token: str = Depends(api_key_header)):
300
- # if token != DEFAULT_TOKEN:
301
- # raise HTTPException(
302
- # status_code=status.HTTP_401_UNAUTHORIZED,
303
- # detail="Invalid or missing token. Use correct Token"
304
- # )
305
-
306
- # # Middleware to add process time header
307
- # @app.middleware("http")
308
- # async def add_process_time_header(request: Request, call_next):
309
- # start_time = time.perf_counter()
310
- # response = await call_next(request)
311
- # process_time = time.perf_counter() - start_time
312
- # response.headers["Time of pro"] = str(process_time)
313
- # return response
314
-
315
- # class Student(BaseModel):
316
- # rollno: int
317
- # name: str
318
- # age: int
319
- # phone: str
320
-
321
- # def load_data():
322
- # if os.path.exists("students.json"):
323
- # with open("students.json", "r") as f:
324
- # return json.load(f)
325
- # return []
326
-
327
- # def save_data():
328
- # with open("students.json", "w") as f:
329
- # json.dump(students, f, indent=2)
330
-
331
- # students = load_data()
332
-
333
- # @app.post("/Student/", dependencies=[Depends(verify_token)])
334
- # def create_student(student: Student):
335
- # if any(s["rollno"] == student.rollno for s in students):
336
- # raise HTTPException(status_code=400, detail="Roll number already exists")
337
-
338
- # students.append(student.dict())
339
- # save_data()
340
- # return student
341
-
342
- # @app.get("/Student/", dependencies=[Depends(verify_token)])
343
- # def get_all_students():
344
- # return students
345
-
346
- # @app.get("/Student/{rollno}", dependencies=[Depends(verify_token)])
347
- # def get_student(rollno: int):
348
- # student = next((s for s in students if s["rollno"] == rollno), None)
349
- # if not student:
350
- # raise HTTPException(status_code=404, detail="Student not found")
351
- # return student
352
-
353
- # @app.put("/Student/{rollno}", dependencies=[Depends(verify_token)])
354
- # def update_student(rollno: int, student: Student):
355
- # for i, s in enumerate(students):
356
- # if s["rollno"] == rollno:
357
- # students[i] = student.dict()
358
- # save_data()
359
- # return student
360
- # raise HTTPException(status_code=404, detail="Student not found")
361
-
362
- # @app.delete("/Student/{rollno}", dependencies=[Depends(verify_token)])
363
- # def delete_student(rollno: int):
364
- # for i, s in enumerate(students):
365
- # if s["rollno"] == rollno:
366
- # students.pop(i)
367
- # save_data()
368
- # return {"message": "Student deleted"}
369
- # raise HTTPException(status_code=404, detail="Student not found")
370
-
371
-
372
-
373
- # import time
374
- # import joblib
375
- # import numpy as np
376
- # from fastapi import FastAPI, HTTPException, Request, status, Depends
377
- # from fastapi.security.api_key import APIKeyHeader
378
- # from pydantic import BaseModel
379
-
380
- # app = FastAPI()
381
- # DEFAULT_TOKEN = "a9b7c7e8b0e44157a99c9a8c5f6a172e10b77e2b44693506a32e5a6a0cd749d0"
382
- # api_key_header = APIKeyHeader(name="Token", auto_error=False)
383
-
384
- # def verify_token(token: str = Depends(api_key_header)):
385
- # if token != DEFAULT_TOKEN:
386
- # raise HTTPException(
387
- # status_code=status.HTTP_401_UNAUTHORIZED,
388
- # detail="Invalid or missing token. Use correct Token"
389
- # )
390
-
391
- # @app.middleware("http")
392
- # async def add_process_time_header(request: Request, call_next):
393
- # start_time = time.perf_counter()
394
- # response = await call_next(request)
395
- # process_time = time.perf_counter() - start_time
396
- # response.headers["Time of pro"] = str(process_time)
397
- # return response
398
-
399
- # model = [joblib.load(r"D:\Igenerate_code\Model\logistic_regression.pkl"),
400
- # joblib.load(r"D:\Igenerate_code\Model\random_forest_model.pkl"),
401
- # joblib.load(r"D:\Igenerate_code\Model\decision_tree_model.pkl"),
402
- # joblib.load(r"D:\Igenerate_code\Model\SVM_model.pkl"),
403
- # joblib.load(r"D:\Igenerate_code\Model\KNeighborsClassifier_model.pkl"),
404
- # joblib.load(r"D:\Igenerate_code\Model\Naive_Bayes_model.pkl"),
405
- # joblib.load(r"D:\Igenerate_code\Model\ANN_model.pkl")]
406
-
407
- # class MusicFeatures(BaseModel):
408
- # danceability: float
409
- # energy: float
410
- # key: int
411
- # loudness: float
412
- # mode: int
413
- # speechiness: float
414
- # acousticness: float
415
- # instrumentalness: float
416
- # liveness: float
417
- # valence: float
418
- # tempo: float
419
- # duration_ms: int
420
- # time_signature: int
421
-
422
- # @app.post("/predict", dependencies=[Depends(verify_token)])
423
- # def predict_music(features: MusicFeatures):
424
- # try:
425
- # input_data = np.array([[ # Format input as 2D array
426
- # features.danceability, features.energy, features.key,
427
- # features.loudness, features.mode, features.speechiness,
428
- # features.acousticness, features.instrumentalness, features.liveness,
429
- # features.valence, features.tempo, features.duration_ms, features.time_signature
430
-
431
- # ]])
432
- # prediction = model.predict(input_data)[0]
433
- # return {"prediction": int(prediction)}
434
- # except Exception as e:
435
- # raise HTTPException(status_code=500, detail=str(e))
436
-
437
-
438
-
439
- # import time
440
- # import joblib
441
- # import numpy as np
442
- # from fastapi import FastAPI, HTTPException, Request, status, Depends
443
- # from fastapi.security.api_key import APIKeyHeader
444
- # from pydantic import BaseModel
445
-
446
- # app = FastAPI()
447
-
448
- # DEFAULT_TOKEN = "a9b7c7e8b0e44157a99c9a8c5f6a172e10b77e2b44693506a32e5a6a0cd749d0"
449
- # api_key_header = APIKeyHeader(name="Token", auto_error=False)
450
-
451
- # def verify_token(token: str = Depends(api_key_header)):
452
- # if token != DEFAULT_TOKEN:
453
- # raise HTTPException(
454
- # status_code=status.HTTP_401_UNAUTHORIZED,
455
- # detail="Invalid or missing token. Use correct Token"
456
- # )
457
-
458
- # @app.middleware("http")
459
- # async def add_process_time_header(request: Request, call_next):
460
- # start_time = time.perf_counter()
461
- # response = await call_next(request)
462
- # process_time = time.perf_counter() - start_time
463
- # response.headers["Time of pro"] = str(process_time)
464
- # return response
465
-
466
- # model_paths = {
467
- # "logistic_regression": r"D:\Igenerate_code\Model\logistic_regression.pkl",
468
- # "random_forest_model": r"D:\Igenerate_code\Model\random_forest_model.pkl",
469
- # "DecisionTreeClassifier_model": r"D:\Igenerate_code\Model\DecisionTreeClassifier.pkl",
470
- # "SVM_model": r"D:\Igenerate_code\Model\SVM_model.pkl",
471
- # "KNeighborsClassifier_model": r"D:\Igenerate_code\Model\KNeighborsClassifier_model.pkl",
472
- # "Naive_Bayes_model": r"D:\Igenerate_code\Model\Naive_Bayes_model.pkl",
473
- # "ANN_model": r"D:\Igenerate_code\Model\ANN_model.pkl"
474
- # }
475
-
476
- # models = {name: joblib.load(path) for name, path in model_paths.items()}
477
-
478
- # class MusicFeatures(BaseModel):
479
- # model_name: "random_forest_model"
480
- # danceability: float
481
- # energy: float
482
- # key: int
483
- # loudness: float
484
- # mode: int
485
- # speechiness: float
486
- # acousticness: float
487
- # instrumentalness: float
488
- # liveness: float
489
- # valence: float
490
- # tempo: float
491
- # duration_ms: int
492
- # time_signature: int
493
-
494
-
495
- # @app.post("/predict", dependencies=[Depends(verify_token)])
496
- # def predict_music(features: MusicFeatures):
497
- # try:
498
- # if features.model_name not in models:
499
- # raise HTTPException(status_code=400, detail="Invalid model name")
500
-
501
- # model = models[features.model_name]
502
-
503
- # input_data = np.array([[
504
- # features.danceability, features.energy, features.key,
505
- # features.loudness, features.mode, features.speechiness,
506
- # features.acousticness, features.instrumentalness, features.liveness,
507
- # features.valence, features.tempo, features.duration_ms, features.time_signature
508
- # ]])
509
-
510
- # prediction = model.predict(input_data)[0]
511
- # return {
512
- # "model_used": features.model_name,
513
- # "prediction": int(prediction)
514
- # }
515
-
516
- # except Exception as e:
517
- # raise HTTPException(status_code=500, detail=str(e))
518
-
519
  import time
520
  import joblib
521
  import numpy as np
522
- from fastapi import FastAPI, HTTPException, Request, status, Depends
523
- from fastapi.security.api_key import APIKeyHeader
524
  from pydantic import BaseModel
525
  from fastapi.templating import Jinja2Templates
526
  from fastapi.responses import HTMLResponse
527
-
528
-
529
  from fastapi.staticfiles import StaticFiles
530
 
531
-
532
  app = FastAPI()
533
  templates = Jinja2Templates(directory="templates")
534
  app.mount("/static", StaticFiles(directory="static"), name="static")
535
 
536
-
537
- DEFAULT_TOKEN = "a9b7c7e8b0e44157a99c9a8c5f6a172e10b77e2b44693506a32e5a6a0cd749d0"
538
- api_key_header = APIKeyHeader(name="Token", auto_error=False)
539
-
540
- def verify_token(token: str = Depends(api_key_header)):
541
- if token != DEFAULT_TOKEN:
542
- raise HTTPException(
543
- status_code=status.HTTP_401_UNAUTHORIZED,
544
- detail="Invalid or missing token. Use correct Token"
545
- )
546
-
547
  @app.middleware("http")
548
  async def add_process_time_header(request: Request, call_next):
549
  start_time = time.perf_counter()
@@ -588,35 +55,34 @@ def make_prediction(model, features: MusicFeatures):
588
  ]])
589
  return int(model.predict(input_data)[0])
590
 
591
-
592
  @app.get("/", response_class=HTMLResponse)
593
  async def read_home(request: Request):
594
  return templates.TemplateResponse("index.html", {"request": request})
595
 
596
- @app.post("/predict/logistic_regression", dependencies=[Depends(verify_token)])
597
  def predict_logistic(features: MusicFeatures):
598
  return {"model": "Logistic Regression", "prediction": make_prediction(models["logistic_regression"], features)}
599
 
600
- @app.post("/predict/random_forest", dependencies=[Depends(verify_token)])
601
  def predict_rf(features: MusicFeatures):
602
  return {"model": "Random Forest", "prediction": make_prediction(models["random_forest_model"], features)}
603
 
604
- @app.post("/predict/decision_tree", dependencies=[Depends(verify_token)])
605
  def predict_dt(features: MusicFeatures):
606
  return {"model": "Decision Tree", "prediction": make_prediction(models["decision_tree"], features)}
607
 
608
- @app.post("/predict/svm", dependencies=[Depends(verify_token)])
609
  def predict_svm(features: MusicFeatures):
610
  return {"model": "SVM", "prediction": make_prediction(models["svm"], features)}
611
 
612
- @app.post("/predict/knn", dependencies=[Depends(verify_token)])
613
  def predict_knn(features: MusicFeatures):
614
  return {"model": "K-Nearest Neighbors", "prediction": make_prediction(models["knn"], features)}
615
 
616
- @app.post("/predict/naive_bayes", dependencies=[Depends(verify_token)])
617
  def predict_nb(features: MusicFeatures):
618
  return {"model": "Naive Bayes", "prediction": make_prediction(models["naive_bayes"], features)}
619
 
620
- @app.post("/predict/ann", dependencies=[Depends(verify_token)])
621
  def predict_ann(features: MusicFeatures):
622
  return {"model": "Artificial Neural Network", "prediction": make_prediction(models["ann"], features)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import time
2
  import joblib
3
  import numpy as np
4
+ from fastapi import FastAPI, HTTPException, Request
 
5
  from pydantic import BaseModel
6
  from fastapi.templating import Jinja2Templates
7
  from fastapi.responses import HTMLResponse
 
 
8
  from fastapi.staticfiles import StaticFiles
9
 
 
10
  app = FastAPI()
11
  templates = Jinja2Templates(directory="templates")
12
  app.mount("/static", StaticFiles(directory="static"), name="static")
13
 
 
 
 
 
 
 
 
 
 
 
 
14
  @app.middleware("http")
15
  async def add_process_time_header(request: Request, call_next):
16
  start_time = time.perf_counter()
 
55
  ]])
56
  return int(model.predict(input_data)[0])
57
 
 
58
  @app.get("/", response_class=HTMLResponse)
59
  async def read_home(request: Request):
60
  return templates.TemplateResponse("index.html", {"request": request})
61
 
62
+ @app.post("/predict/logistic_regression")
63
  def predict_logistic(features: MusicFeatures):
64
  return {"model": "Logistic Regression", "prediction": make_prediction(models["logistic_regression"], features)}
65
 
66
+ @app.post("/predict/random_forest")
67
  def predict_rf(features: MusicFeatures):
68
  return {"model": "Random Forest", "prediction": make_prediction(models["random_forest_model"], features)}
69
 
70
+ @app.post("/predict/decision_tree")
71
  def predict_dt(features: MusicFeatures):
72
  return {"model": "Decision Tree", "prediction": make_prediction(models["decision_tree"], features)}
73
 
74
+ @app.post("/predict/svm")
75
  def predict_svm(features: MusicFeatures):
76
  return {"model": "SVM", "prediction": make_prediction(models["svm"], features)}
77
 
78
+ @app.post("/predict/knn")
79
  def predict_knn(features: MusicFeatures):
80
  return {"model": "K-Nearest Neighbors", "prediction": make_prediction(models["knn"], features)}
81
 
82
+ @app.post("/predict/naive_bayes")
83
  def predict_nb(features: MusicFeatures):
84
  return {"model": "Naive Bayes", "prediction": make_prediction(models["naive_bayes"], features)}
85
 
86
+ @app.post("/predict/ann")
87
  def predict_ann(features: MusicFeatures):
88
  return {"model": "Artificial Neural Network", "prediction": make_prediction(models["ann"], features)}