ruminasval commited on
Commit
26fd668
·
verified ·
1 Parent(s): e33f0be

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +85 -0
app.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import torch
3
+ import cv2
4
+ import mediapipe as mp
5
+ from transformers import SwinForImageClassification, AutoFeatureExtractor
6
+ from PIL import Image
7
+ import numpy as np
8
+
9
+ # Initialize face detection
10
+ mp_face_detection = mp.solutions.face_detection.FaceDetection(
11
+ model_selection=1, min_detection_confidence=0.5)
12
+
13
+ # Initialize model and labels
14
+ @st.cache_resource
15
+ def load_model():
16
+ id2label = {0: 'Heart', 1: 'Oblong', 2: 'Oval', 3: 'Round', 4: 'Square'}
17
+ label2id = {v: k for k, v in id2label.items()}
18
+
19
+ model = SwinForImageClassification.from_pretrained(
20
+ "microsoft/swin-tiny-patch4-window7-224",
21
+ label2id=label2id,
22
+ id2label=id2label,
23
+ ignore_mismatched_sizes=True
24
+ )
25
+
26
+ model.load_state_dict(torch.load('swin.pth', map_location='cpu'))
27
+ model.eval()
28
+ return model, AutoFeatureExtractor.from_pretrained("microsoft/swin-tiny-patch4-window7-224")
29
+
30
+ model, feature_extractor = load_model()
31
+
32
+ glasses_recommendations = {
33
+ "Heart": "Rimless (tanpa bingkai bawah)",
34
+ "Oblong": "Kotak",
35
+ "Oval": "Berbagai bentuk bingkai",
36
+ "Round": "Kotak",
37
+ "Square": "Oval atau bundar"
38
+ }
39
+
40
+ def preprocess_image(image):
41
+ results = mp_face_detection.process(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
42
+
43
+ if results.detections:
44
+ detection = results.detections[0]
45
+ bbox = detection.location_data.relative_bounding_box
46
+ h, w, _ = image.shape
47
+ x1 = int(bbox.xmin * w)
48
+ y1 = int(bbox.ymin * h)
49
+ x2 = int((bbox.xmin + bbox.width) * w)
50
+ y2 = int((bbox.ymin + bbox.height) * h)
51
+ image = image[y1:y2, x1:x2]
52
+ else:
53
+ raise ValueError("No face detected")
54
+
55
+ image = cv2.resize(image, (224, 224))
56
+ image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
57
+ return feature_extractor(images=image, return_tensors="pt")['pixel_values']
58
+
59
+ def predict(image):
60
+ image_tensor = preprocess_image(image)
61
+ with torch.no_grad():
62
+ outputs = model(image_tensor)
63
+ return id2label[torch.argmax(outputs.logits).item()]
64
+
65
+ # Streamlit UI
66
+ st.title("Face Shape & Glasses Recommender")
67
+ st.write("Upload a face photo for shape analysis and glasses recommendations")
68
+
69
+ uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
70
+
71
+ if uploaded_file is not None:
72
+ image = Image.open(uploaded_file).convert('RGB')
73
+ img_array = np.array(image)
74
+
75
+ st.image(image, caption='Uploaded Image', use_column_width=True)
76
+
77
+ try:
78
+ with st.spinner('Analyzing...'):
79
+ prediction = predict(cv2.cvtColor(img_array, cv2.COLOR_RGB2BGR))
80
+ recommendation = glasses_recommendations[prediction]
81
+
82
+ st.success(f"Predicted Face Shape: **{prediction}**")
83
+ st.info(f"Recommended Glasses Frame: **{recommendation}**")
84
+ except Exception as e:
85
+ st.error(f"Error: {str(e)}")