Prime810 commited on
Commit
a683413
·
verified ·
1 Parent(s): cd9492f

Update Backend/app.py

Browse files
Files changed (1) hide show
  1. Backend/app.py +96 -92
Backend/app.py CHANGED
@@ -1,92 +1,96 @@
1
- from fastapi import FastAPI, HTTPException
2
- from fastapi.middleware.cors import CORSMiddleware
3
- from fastapi.responses import JSONResponse
4
- from pydantic import BaseModel
5
- import base64
6
- from io import BytesIO
7
- from PIL import Image
8
- import numpy as np
9
- import cv2
10
- import os
11
- import traceback
12
- from keras.models import load_model
13
-
14
- # Load the trained model
15
- model_path = os.path.join(os.path.dirname(__file__), 'emotion_model.keras')
16
- model = load_model(model_path)
17
-
18
- # Emotion and emoji maps
19
- emotion_dict = {
20
- 0: "Angry", 1: "Disgusted", 2: "Fearful", 3: "Happy",
21
- 4: "Neutral", 5: "Sad", 6: "Surprised"
22
- }
23
-
24
- BASE_DIR = os.path.dirname(os.path.abspath(__file__))
25
- emoji_map = {
26
- 0: os.path.join(BASE_DIR, "emojis", "angry.png"),
27
- 1: os.path.join(BASE_DIR, "emojis", "disgusted.png"),
28
- 2: os.path.join(BASE_DIR, "emojis", "fearful.png"),
29
- 3: os.path.join(BASE_DIR, "emojis", "happy.png"),
30
- 4: os.path.join(BASE_DIR, "emojis", "neutral.png"),
31
- 5: os.path.join(BASE_DIR, "emojis", "sad.png"),
32
- 6: os.path.join(BASE_DIR, "emojis", "surprised.png")
33
- }
34
-
35
- # Initialize FastAPI app
36
- app = FastAPI()
37
- app.add_middleware(
38
- CORSMiddleware,
39
- allow_origins=["*"],
40
- allow_credentials=True,
41
- allow_methods=["*"],
42
- allow_headers=["*"],
43
- )
44
-
45
- class ImageData(BaseModel):
46
- image: str
47
-
48
- # Load Haarcascade once
49
- face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
50
-
51
- @app.post("/process-image")
52
- async def process_image(data: ImageData):
53
- try:
54
- header, encoded = data.image.split(",")
55
- img_bytes = base64.b64decode(encoded)
56
- img = Image.open(BytesIO(img_bytes)).convert('RGB')
57
- img_np = np.array(img)
58
-
59
- gray = cv2.cvtColor(img_np, cv2.COLOR_RGB2GRAY)
60
- faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5)
61
-
62
- if len(faces) == 0:
63
- raise HTTPException(status_code=400, detail="No face detected")
64
-
65
- for (x, y, w, h) in faces:
66
- roi_gray = gray[y:y + h, x:x + w]
67
- roi = cv2.resize(roi_gray, (48, 48))
68
- roi = roi.astype("float") / 255.0
69
- roi = np.expand_dims(roi, axis=-1)
70
- roi = np.expand_dims(roi, axis=0)
71
-
72
- preds = model.predict(roi, verbose=0)
73
- emotion_index = int(np.argmax(preds))
74
- emotion_label = emotion_dict[emotion_index]
75
-
76
- emoji_path = emoji_map[emotion_index]
77
- emoji_img = Image.open(emoji_path).convert("RGBA")
78
- buffer = BytesIO()
79
- emoji_img.save(buffer, format="PNG")
80
- encoded_emoji = base64.b64encode(buffer.getvalue()).decode("utf-8")
81
-
82
- return JSONResponse({
83
- "emotion": emotion_label,
84
- "emoji": f"data:image/png;base64,{encoded_emoji}"
85
- })
86
-
87
- raise HTTPException(status_code=400, detail="Face not processed")
88
-
89
- except Exception as e:
90
- print("Error:", str(e))
91
- traceback.print_exc()
92
- raise HTTPException(status_code=500, detail=str(e))
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException
2
+ from fastapi.middleware.cors import CORSMiddleware
3
+ from fastapi.responses import JSONResponse
4
+ from pydantic import BaseModel
5
+ import base64
6
+ from io import BytesIO
7
+ from PIL import Image
8
+ import numpy as np
9
+ import cv2
10
+ import os
11
+ import traceback
12
+ from keras.models import load_model
13
+
14
+ # Load the trained model
15
+ model_path = os.path.join(os.path.dirname(__file__), 'emotion_model.keras')
16
+ model = load_model(model_path)
17
+
18
+ # Emotion and emoji maps
19
+ emotion_dict = {
20
+ 0: "Angry", 1: "Disgusted", 2: "Fearful", 3: "Happy",
21
+ 4: "Neutral", 5: "Sad", 6: "Surprised"
22
+ }
23
+
24
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
25
+ emoji_map = {
26
+ 0: os.path.join(BASE_DIR, "emojis", "angry.png"),
27
+ 1: os.path.join(BASE_DIR, "emojis", "disgusted.png"),
28
+ 2: os.path.join(BASE_DIR, "emojis", "fearful.png"),
29
+ 3: os.path.join(BASE_DIR, "emojis", "happy.png"),
30
+ 4: os.path.join(BASE_DIR, "emojis", "neutral.png"),
31
+ 5: os.path.join(BASE_DIR, "emojis", "sad.png"),
32
+ 6: os.path.join(BASE_DIR, "emojis", "surprised.png")
33
+ }
34
+
35
+ # Initialize FastAPI app
36
+ app = FastAPI()
37
+ app.add_middleware(
38
+ CORSMiddleware,
39
+ allow_origins=["*"],
40
+ allow_credentials=True,
41
+ allow_methods=["*"],
42
+ allow_headers=["*"],
43
+ )
44
+
45
+ class ImageData(BaseModel):
46
+ image: str
47
+
48
+ # Load Haarcascade once
49
+ face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
50
+
51
+ @app.get("/")
52
+ def read_root():
53
+ return {"message": "FaceFeel backend is running"}
54
+
55
+ @app.post("/process-image")
56
+ async def process_image(data: ImageData):
57
+ try:
58
+ header, encoded = data.image.split(",")
59
+ img_bytes = base64.b64decode(encoded)
60
+ img = Image.open(BytesIO(img_bytes)).convert('RGB')
61
+ img_np = np.array(img)
62
+
63
+ gray = cv2.cvtColor(img_np, cv2.COLOR_RGB2GRAY)
64
+ faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5)
65
+
66
+ if len(faces) == 0:
67
+ raise HTTPException(status_code=400, detail="No face detected")
68
+
69
+ for (x, y, w, h) in faces:
70
+ roi_gray = gray[y:y + h, x:x + w]
71
+ roi = cv2.resize(roi_gray, (48, 48))
72
+ roi = roi.astype("float") / 255.0
73
+ roi = np.expand_dims(roi, axis=-1)
74
+ roi = np.expand_dims(roi, axis=0)
75
+
76
+ preds = model.predict(roi, verbose=0)
77
+ emotion_index = int(np.argmax(preds))
78
+ emotion_label = emotion_dict[emotion_index]
79
+
80
+ emoji_path = emoji_map[emotion_index]
81
+ emoji_img = Image.open(emoji_path).convert("RGBA")
82
+ buffer = BytesIO()
83
+ emoji_img.save(buffer, format="PNG")
84
+ encoded_emoji = base64.b64encode(buffer.getvalue()).decode("utf-8")
85
+
86
+ return JSONResponse({
87
+ "emotion": emotion_label,
88
+ "emoji": f"data:image/png;base64,{encoded_emoji}"
89
+ })
90
+
91
+ raise HTTPException(status_code=400, detail="Face not processed")
92
+
93
+ except Exception as e:
94
+ print("Error:", str(e))
95
+ traceback.print_exc()
96
+ raise HTTPException(status_code=500, detail=str(e))