-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
81 lines (66 loc) · 2.3 KB
/
Copy pathapp.py
File metadata and controls
81 lines (66 loc) · 2.3 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
from flask import Flask, render_template, request, send_from_directory
from db import get_db_connection
from deepface import DeepFace
import json
import os
import numpy as np
app = Flask(__name__)
UPLOAD_FOLDER = "uploads"
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
# ✅ THIS ROUTE IS REQUIRED (VERY IMPORTANT)
@app.route("/uploads/<filename>")
def uploaded_file(filename):
return send_from_directory(UPLOAD_FOLDER, filename)
# Home page
@app.route("/", methods=["GET", "POST"])
def index():
if request.method == "POST":
file = request.files.get("photo")
if not file:
return render_template("index.html")
filename = file.filename
filepath = os.path.join(UPLOAD_FOLDER, filename)
file.save(filepath)
# Face detection + embedding
try:
result = DeepFace.represent(
img_path=filepath,
model_name="Facenet",
enforce_detection=True
)
query_embedding = np.array(result[0]["embedding"])
except Exception:
return render_template(
"results.html",
error="❌ No face detected. Please upload a clear face image.",
matches=[],
uploaded_filename=None
)
# Fetch embeddings from DB
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute("SELECT image_name, embedding FROM face_embeddings")
db_results = cursor.fetchall()
conn.close()
similarities = []
for name, emb_json in db_results:
db_emb = np.array(json.loads(emb_json))
sim = np.dot(query_embedding, db_emb) / (
np.linalg.norm(query_embedding) * np.linalg.norm(db_emb)
)
similarities.append({
"name": name,
"similarity": float(sim),
"image_url": f"/static/dataset/{name}"
})
similarities.sort(key=lambda x: x["similarity"], reverse=True)
top_matches = similarities[:5]
return render_template(
"results.html",
matches=top_matches,
uploaded_filename=filename,
error=None
)
return render_template("index.html")
if __name__ == "__main__":
app.run(debug=True)