huy00001 commited on
Commit
cabb75b
·
verified ·
1 Parent(s): 152845e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -41
app.py CHANGED
@@ -4,65 +4,76 @@ import numpy as np
4
  from PIL import Image
5
  import json
6
  import uuid
7
- from pydrive2.auth import GoogleAuth
8
- from pydrive2.drive import GoogleDrive
9
-
10
- # --- Google Drive setup với Service Account ---
11
- gauth = GoogleAuth()
12
- gauth.ServiceAuth(settings_file="service_account.json") # file JSON của service account
13
- drive = GoogleDrive(gauth)
14
-
15
- # ID folder public trên Google Drive
16
- FOLDER_ID = "1MwGdJbVbLNSLnmHrR-mGlH8EAJ3gy50R"
17
-
18
- # Dictionary lưu mapping image_id -> {'file_id':..., 'name':...}
19
- image_drive_map = {}
20
-
21
- # 1️⃣ Upload ảnh lên Google Drive
 
22
  def upload_image(image, name):
23
  try:
24
  if isinstance(image, Image.Image):
25
  image = np.array(image)
 
26
  image_id = str(uuid.uuid4())
27
- filename = f"{image_id}.png"
28
  pil_image = Image.fromarray(image)
29
- pil_image.save(filename) # tạm lưu local
30
-
31
- gfile = drive.CreateFile({'title': filename, 'parents':[{'id': FOLDER_ID}]})
32
- gfile.SetContentFile(filename)
33
- gfile.Upload()
 
 
 
 
 
 
 
34
 
35
- image_drive_map[image_id] = {'file_id': gfile['id'], 'name': name}
36
- file_link = f"https://drive.google.com/file/d/{gfile['id']}/view?usp=sharing"
37
- return f"Ảnh lưu thành công với ID: {image_id}\nTên: {name}\nLink: {file_link}", image_id
38
  except Exception as e:
39
- return f"Lỗi khi upload: {str(e)}", None
40
 
41
- # 2️⃣ Nhận diện khuôn mặt
 
 
42
  def recognize_face(image, image_id):
43
  try:
44
- if image_id not in image_drive_map:
45
- return "Ảnh ID không tồn tại"
 
 
 
 
 
 
 
46
  if isinstance(image, Image.Image):
47
  image = np.array(image)
48
 
49
- # Download ảnh từ Drive
50
- file_id = image_drive_map[image_id]['file_id']
51
- stored_name = image_drive_map[image_id]['name']
52
- gfile = drive.CreateFile({'id': file_id})
53
- gfile.GetContentFile(f"temp_{image_id}.png")
54
-
55
- result = DeepFace.verify(img1_path=image, img2_path=f"temp_{image_id}.png")
56
  output = {
57
  "Verified": result["verified"],
58
  "Khoảng cách": round(result["distance"], 4),
59
- "Tên ảnh gốc": stored_name
60
  }
61
  return json.dumps(output, ensure_ascii=False, indent=2)
62
  except Exception as e:
63
- return f"Lỗi khi nhận diện: {str(e)}"
64
 
65
- # 3️⃣ Phân tích khuôn mặt
 
 
66
  def analyze_face(image):
67
  try:
68
  if isinstance(image, Image.Image):
@@ -81,11 +92,13 @@ def analyze_face(image):
81
  }
82
  return json.dumps(output, ensure_ascii=False, indent=2)
83
  except Exception as e:
84
- return f"Lỗi khi phân tích: {str(e)}"
85
 
86
- # --- Gradio interface ---
 
 
87
  with gr.Blocks() as demo:
88
- gr.Markdown("## 📁 Upload ảnh lên Google Drive")
89
  with gr.Row():
90
  upload_input = gr.Image(label="Upload ảnh", type="numpy")
91
  name_input = gr.Textbox(label="Tên người trong ảnh")
 
4
  from PIL import Image
5
  import json
6
  import uuid
7
+ import base64
8
+ import pymongo
9
+ from io import BytesIO
10
+
11
+ # =======================
12
+ # MongoDB setup
13
+ # =======================
14
+ client = pymongo.MongoClient(
15
+ "mongodb+srv://huyh01480_db_user:OGNNUaT14nlYh2Uu@cluster0.n8pboqq.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0"
16
+ )
17
+ db = client["faceDB"]
18
+ face_collection = db["faceImg"]
19
+
20
+ # =======================
21
+ # Upload ảnh + lưu MongoDB
22
+ # =======================
23
  def upload_image(image, name):
24
  try:
25
  if isinstance(image, Image.Image):
26
  image = np.array(image)
27
+
28
  image_id = str(uuid.uuid4())
 
29
  pil_image = Image.fromarray(image)
30
+ buffer = BytesIO()
31
+ pil_image.save(buffer, format="PNG")
32
+ img_bytes = buffer.getvalue()
33
+ img_base64 = base64.b64encode(img_bytes).decode('utf-8')
34
+
35
+ # Lưu vào MongoDB
36
+ doc = {
37
+ "_id": image_id,
38
+ "name": name,
39
+ "image": img_base64
40
+ }
41
+ face_collection.insert_one(doc)
42
 
43
+ return f"✅ Upload thành công!\nID: {image_id}\nTên: {name}", image_id
 
 
44
  except Exception as e:
45
+ return f"Lỗi upload: {str(e)}", None
46
 
47
+ # =======================
48
+ # Nhận diện khuôn mặt
49
+ # =======================
50
  def recognize_face(image, image_id):
51
  try:
52
+ doc = face_collection.find_one({"_id": image_id})
53
+ if not doc:
54
+ return "❌ Ảnh ID không tồn tại"
55
+
56
+ # Decode base64 từ MongoDB
57
+ img_bytes = base64.b64decode(doc['image'])
58
+ pil_image = Image.open(BytesIO(img_bytes))
59
+ img2 = np.array(pil_image)
60
+
61
  if isinstance(image, Image.Image):
62
  image = np.array(image)
63
 
64
+ result = DeepFace.verify(img1_path=image, img2_path=img2)
 
 
 
 
 
 
65
  output = {
66
  "Verified": result["verified"],
67
  "Khoảng cách": round(result["distance"], 4),
68
+ "Tên ảnh gốc": doc['name']
69
  }
70
  return json.dumps(output, ensure_ascii=False, indent=2)
71
  except Exception as e:
72
+ return f"Lỗi nhận diện: {str(e)}"
73
 
74
+ # =======================
75
+ # Phân tích khuôn mặt
76
+ # =======================
77
  def analyze_face(image):
78
  try:
79
  if isinstance(image, Image.Image):
 
92
  }
93
  return json.dumps(output, ensure_ascii=False, indent=2)
94
  except Exception as e:
95
+ return f"Lỗi phân tích: {str(e)}"
96
 
97
+ # =======================
98
+ # Gradio interface
99
+ # =======================
100
  with gr.Blocks() as demo:
101
+ gr.Markdown("## 📁 Upload ảnh vào MongoDB")
102
  with gr.Row():
103
  upload_input = gr.Image(label="Upload ảnh", type="numpy")
104
  name_input = gr.Textbox(label="Tên người trong ảnh")