-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
145 lines (120 loc) · 4.46 KB
/
app.py
File metadata and controls
145 lines (120 loc) · 4.46 KB
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
import io, base64, json, time
import numpy as np
import requests
from PIL import Image
from flask import Flask, request, jsonify, send_from_directory
from flask_cors import CORS # ✅ NEW
# Torch / FaceNet
import torch
from torchvision import transforms
from facenet_pytorch import InceptionResnetV1
# ----------------- CONFIG -----------------
SHEETDB_URL = "https://sheetdb.io/api/v1/8el5n1fegoheh"
SIMILARITY_THRESHOLD = 0.65
# Flask app
app = Flask(__name__)
CORS(app) # ✅ allow Flutter app to talk with Flask
# ----------------- MODEL -----------------
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = InceptionResnetV1(pretrained="vggface2").eval().to(device)
transform = transforms.Compose([
transforms.Resize((160, 160)),
transforms.ToTensor(),
transforms.Normalize([0.5]*3, [0.5]*3),
])
def dataurl_to_pil(data_url):
if not data_url or len(data_url) < 50: # ✅ skip empty frames
raise ValueError("Invalid image data")
if "," in data_url:
_, b64 = data_url.split(",", 1)
else:
b64 = data_url
return Image.open(io.BytesIO(base64.b64decode(b64))).convert("RGB")
def compute_embedding(img: Image.Image):
x = transform(img).unsqueeze(0).to(device)
with torch.no_grad():
emb = model(x).cpu().numpy()[0]
emb = emb / np.linalg.norm(emb) # normalize
return emb
def emb_to_str(emb):
return ",".join([f"{float(v):.8f}" for v in emb])
def str_to_emb(s):
arr = np.array([float(x) for x in s.split(",")], dtype=np.float32)
return arr / np.linalg.norm(arr)
def cosine(a, b):
return float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)))
# ----------------- ROUTES -----------------
@app.route("/")
def home():
return send_from_directory(".", "index.html")
@app.route("/style.css")
def css():
return send_from_directory(".", "style.css")
@app.route("/script.js")
def js():
return send_from_directory(".", "script.js")
@app.route("/register", methods=["POST"])
def register():
try:
form = request.form.to_dict()
img_data = form.pop("image_data", None)
if not img_data:
return jsonify({"error": "no image"}), 400
img = dataurl_to_pil(img_data)
emb = compute_embedding(img)
payload = {
"data": {
"roll_no": form.get("roll_no", ""),
"name": form.get("name", ""),
"phone": form.get("phone", ""),
"class": form.get("class", ""),
"division": form.get("division", ""),
"gf_name": form.get("gf_name", ""),
"cgpa": form.get("cgpa", ""),
"address": form.get("address", ""),
"embedding": emb_to_str(emb),
}
}
r = requests.post(SHEETDB_URL, json=payload)
return jsonify(r.json())
except Exception as e:
return jsonify({"error": str(e)}), 500
# ----------------- SCAN -----------------
last_request_time = 0 # ✅ limit too many frames
@app.route("/scan", methods=["POST"])
def scan():
global last_request_time
try:
now = time.time()
if now - last_request_time < 1: # ✅ only 1 request per second
return jsonify({"skip": True})
last_request_time = now
data = request.get_json()
if not data or "image_data" not in data:
return jsonify({"error": "no image"}), 400
probe_img = dataurl_to_pil(data["image_data"])
probe_emb = compute_embedding(probe_img)
r = requests.get(SHEETDB_URL)
if r.status_code != 200:
return jsonify({"error": "sheetdb fetch failed"}), 500
records = r.json()
best, best_score = None, -1
for rec in records:
if not rec.get("embedding"):
continue
try:
db_emb = str_to_emb(rec["embedding"])
score = cosine(probe_emb, db_emb)
if score > best_score:
best, best_score = rec, score
except:
continue
if best and best_score >= SIMILARITY_THRESHOLD:
best.pop("embedding", None) # don’t send big vector
return jsonify({"match": True, "details": best})
else:
return jsonify({"match": False, "message": "Face not found"})
except Exception as e:
return jsonify({"error": str(e)}), 500
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000, debug=True) # ✅ allow Render hosting