File size: 2,451 Bytes
4720852
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8898712
 
 
 
 
 
 
4720852
 
 
 
 
 
 
 
 
 
 
 
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
import os
from tensorflow.keras.models import load_model
from tensorflow.keras.utils import img_to_array
os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

import tensorflow as tf

from fastapi import FastAPI, File, UploadFile
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
# from tensorflow.keras.preprocessing import image
import numpy as np

import uvicorn
from PIL import Image
import io
import logging




# Suppress TensorFlow warnings
#tf.get_logger().setLevel(logging.ERROR)

app = FastAPI()

# Add CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Adjust as needed
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Replace with your actual model path
model_path = 'face_expression_detection_model3.h5'  # Update with your new model's path
model = load_model(model_path)


# def preprocess_image(img: Image.Image, target_size=(224, 224)):
#     img = img.resize(target_size)
#     x = image.img_to_array(img)
#     x = np.expand_dims(x, axis=0)
#     x = x / 255.0  # Assuming normalization was done during training
#     return x

def preprocess_image(img: Image.Image, target_size=(224, 224)):
    img = img.resize(target_size)
    x = img_to_array(img)
    x = np.expand_dims(x, axis=0)
    x = x / 255.0  # Assuming normalization was done during training
    return x

@app.get("/")
async def read_root():
    return {"message": "Welcome to the Emotion Classification API"}


@app.post("/predict")
async def predict(file: UploadFile = File(...)):
    contents = await file.read()
    img = Image.open(io.BytesIO(contents))
    x = preprocess_image(img)
    prediction = model.predict(x)
    predicted_class = np.argmax(prediction[0])

    class_names = ['angry', 'happy', 'sad', 'surprised', 'neutral', 'disgusted', 'fearful']
    stress_levels = {
        'angry': 'high_stress',
        'happy': 'neutral',
        'sad': 'low_stress',
        'surprised': 'low_stress',
        'neutral': 'neutral',
        'disgusted': 'low_stress',
        'fearful': 'low_stress'
    }

    emotion = class_names[predicted_class]
    stress_level = stress_levels[emotion]

    result = {
        #"predicted_class": emotion,
        "predicted_class": stress_level
    }
    return JSONResponse(content=result)