HSB3119-22080292-daothivananh commited on
Commit
b599a7e
·
1 Parent(s): c915e1f
Files changed (1) hide show
  1. controllers/main.py +10 -591
controllers/main.py CHANGED
@@ -1,584 +1,3 @@
1
- # import os
2
- # import sys
3
- # import threading # <-- Đã thêm thư viện threading
4
- # from pathlib import Path
5
-
6
- # # ─── 1. CẤU HÌNH ĐƯỜNG DẪN TUYỆT ĐỐI (TRÁNH LẠC ĐƯỜNG) ──────────────────────
7
- # # Lấy đường dẫn của thư mục 'controllers' hiện tại
8
- # current_dir = os.path.dirname(os.path.abspath(__file__))
9
- # # Lấy đường dẫn của thư mục gốc 'server'
10
- # root_dir = os.path.dirname(current_dir)
11
-
12
- # # Đưa các thư mục vào tầm ngắm của Python
13
- # sys.path.insert(0, current_dir)
14
- # sys.path.insert(0, os.path.join(current_dir, 'DetecInfoBoxes'))
15
- # if root_dir not in sys.path:
16
- # sys.path.insert(0, root_dir)
17
-
18
- # # ─── 2. BIẾN MÔI TRƯỜNG ───────────────────────────────────────────────────────
19
- # os.environ["FLAGS_use_mkldnn"] = "0"
20
- # os.environ["FLAGS_use_onednn"] = "0"
21
-
22
- # import uuid, json, time, logging
23
- # import cv2
24
- # import numpy as np
25
- # from contextlib import asynccontextmanager
26
- # from datetime import date
27
- # from dotenv import load_dotenv
28
-
29
- # # ─── 3. IMPORT CHUẨN (KHÔNG CÒN LỖI MODULE) ───────────────────────────────────
30
- # from readInfoIdCard import ReadInfo
31
- # from DetecInfoBoxes.GetBoxes import Detect
32
- # from Vocr.tool.predictor import Predictor
33
- # from Vocr.tool.config import Cfg as Cfg_vietocr
34
- # from config import opt
35
-
36
- # # ─── 4. KHỞI TẠO FASTAPI & DATABASE ───────────────────────────────────────────
37
- # load_dotenv(dotenv_path=Path(root_dir) / ".env")
38
-
39
- # from fastapi import FastAPI, UploadFile, File, Form, BackgroundTasks
40
- # from fastapi.middleware.cors import CORSMiddleware
41
- # from fastapi.responses import JSONResponse
42
- # from fastapi.staticfiles import StaticFiles
43
- # from pydantic import BaseModel
44
-
45
- # from database.database import get_db_connection, init_database
46
- # from service.face_service import face_ai_service, face_memory_store, UPLOAD_DIR
47
-
48
- # logging.basicConfig(level=logging.INFO)
49
- # logger = logging.getLogger(__name__)
50
-
51
-
52
- # # ─── KHỞI TẠO AI CHẠY NGẦM ───────────────────────────────────────────────────
53
- # ocr_predictor = None
54
- # read_info = None
55
- # is_ai_ready = False
56
-
57
- # def load_ai_background():
58
- # global ocr_predictor, read_info, is_ai_ready
59
- # try:
60
- # logger.info("[AI_LOADER] Bắt đầu nạp mô hình AI chạy ngầm (Chống sập Render)...")
61
-
62
- # # Nạp VietOCR
63
- # vocr_config_path = os.path.join(current_dir, 'Vocr', 'config', 'vgg-seq2seq.yml')
64
- # config_vietocr = Cfg_vietocr.load_config_from_file(vocr_config_path)
65
- # config_vietocr['weights'] = os.path.join(current_dir, 'Models', 'seq2seqocr.pth')
66
- # config_vietocr['device'] = 'cpu'
67
- # ocr_predictor = Predictor(config_vietocr)
68
-
69
- # # Nạp YOLOv7
70
- # get_dictionary = Detect(opt)
71
- # scan_weight = os.path.join(current_dir, 'Models', 'cccdYoloV7.pt')
72
- # imgsz, stride, device, half, model, names = get_dictionary.load_model(scan_weight)
73
-
74
- # read_info = ReadInfo(imgsz, stride, device, half, model, names, ocr_predictor)
75
-
76
- # is_ai_ready = True
77
- # logger.info("[AI_LOADER] HOÀN TẤT! Hệ thống YOLO + VietOCR đã sẵn sàng nhận diện.")
78
- # except Exception as e:
79
- # logger.error(f"[AI_LOADER] Lỗi khi nạp AI: {e}")
80
-
81
-
82
- # # ─── Startup (Vượt qua vòng kiểm duyệt của Render) ────────────────────────────
83
- # @asynccontextmanager
84
- # async def lifespan(app: FastAPI):
85
- # logger.info("[Startup] Khởi tạo cấu trúc Database (nếu chưa có)...")
86
- # init_database()
87
-
88
- # logger.info("[Startup] Nạp embedding vào RAM...")
89
- # _load_embeddings_to_ram()
90
- # logger.info(f"[Startup] {face_memory_store.count} khuôn mặt trên RAM")
91
-
92
- # # BẬT LUỒNG CHẠY NGẦM: Server mở cổng ngay lập tức, AI từ từ nạp
93
- # threading.Thread(target=load_ai_background, daemon=True).start()
94
-
95
- # yield
96
- # logger.info("[Shutdown] Bye!")
97
-
98
- # def _load_embeddings_to_ram():
99
- # conn = None
100
- # cursor = None
101
- # try:
102
- # conn = get_db_connection()
103
- # cursor = conn.cursor(dictionary=True)
104
- # cursor.execute("""
105
- # SELECT e.person_id, p.name, p.role, p.img_path,
106
- # p.work_expiry_date, e.embedding_vector
107
- # FROM face_embeddings e
108
- # JOIN persons p ON e.person_id = p.id
109
- # WHERE p.status = 'active'
110
- # """)
111
- # rows = cursor.fetchall()
112
- # parsed = []
113
- # for row in rows:
114
- # try:
115
- # parsed.append({
116
- # "person_id": row["person_id"],
117
- # "name": row["name"],
118
- # "role": row.get("role", ""),
119
- # "img_path": row.get("img_path", ""),
120
- # "work_expiry_date": str(row["work_expiry_date"]) if row.get("work_expiry_date") else None,
121
- # "embedding_vector": json.loads(row["embedding_vector"]),
122
- # })
123
- # except Exception as e:
124
- # logger.warning(f"[Startup] Bỏ qua khuôn mặt lỗi: {e}")
125
-
126
- # face_memory_store.load_all(parsed)
127
-
128
- # except Exception as e:
129
- # logger.error(f"[Startup] Lỗi kết nối DB khi nạp dữ liệu: {e}")
130
- # face_memory_store.load_all([])
131
-
132
- # finally:
133
- # if cursor: cursor.close()
134
- # if conn and conn.is_connected(): conn.close()
135
-
136
-
137
- # # ─── App ──────────────────────────────────────────────────────────────────────
138
- # app = FastAPI(lifespan=lifespan)
139
-
140
- # app.add_middleware(
141
- # CORSMiddleware,
142
- # allow_origins=["*"],
143
- # allow_credentials=True,
144
- # allow_methods=["*"],
145
- # allow_headers=["*"],
146
- # )
147
-
148
- # app.mount("/uploads", StaticFiles(directory=UPLOAD_DIR), name="uploads")
149
-
150
- # class PersonUpdate(BaseModel):
151
- # name: str
152
- # role: str
153
- # department: str
154
-
155
- # def save_log_to_db(log_queries: list) -> None:
156
- # if not log_queries:
157
- # return
158
- # try:
159
- # conn = get_db_connection()
160
- # cursor = conn.cursor()
161
- # cursor.executemany(
162
- # "INSERT INTO recognition_logs (id,person_id,status,confidence,camera,action) VALUES (%s,%s,%s,%s,%s,%s)",
163
- # log_queries,
164
- # )
165
- # conn.commit()
166
- # cursor.close()
167
- # conn.close()
168
- # except Exception as e:
169
- # logger.error(f"[Log] {e}")
170
-
171
-
172
- # @app.post("/api/face/ocr")
173
- # async def extract_ocr_local(file: UploadFile = File(...), side: str = Form(...)):
174
- # # BẢO VỆ: Chặn request nếu AI chưa nạp xong
175
- # if not is_ai_ready:
176
- # return {"success": False, "message": "Hệ thống AI đang khởi động, vui lòng thử lại sau 1-2 phút!"}
177
-
178
- # temp_path = ""
179
- # try:
180
- # temp_filename = f"temp_cccd_{uuid.uuid4().hex}.jpg"
181
- # temp_path = os.path.join(UPLOAD_DIR, temp_filename)
182
- # file_bytes = await file.read()
183
- # with open(temp_path, "wb") as f:
184
- # f.write(file_bytes)
185
-
186
- # logger.info(f"[OCR] Phân tích mặt {side} bằng YOLOv7 + VietOCR...")
187
-
188
- # if side == "front":
189
- # raw = read_info.get_all_info(temp_path)
190
- # logger.info(f"[OCR] Mặt trước raw: {raw}")
191
- # mapped_data = {
192
- # "id_number": raw.get("id", ""),
193
- # "full_name": raw.get("full_name", ""),
194
- # "dob": raw.get("date_of_birth", ""),
195
- # "gender": raw.get("sex", ""),
196
- # "nationality": raw.get("nationality", ""),
197
- # "hometown": raw.get("place_of_origin", ""),
198
- # "address": raw.get("place_of_residence", ""),
199
- # "expiry_date": raw.get("date_of_expiry", ""),
200
- # }
201
-
202
- # else: # back
203
- # raw = read_info.get_back_info(temp_path)
204
- # logger.info(f"[OCR] Mặt sau raw: {raw}")
205
- # mapped_data = {
206
- # "issue_date": raw.get("issue_date", ""),
207
- # "issued_by": raw.get("issued_by", ""),
208
- # "special_features": raw.get("special_features", ""),
209
- # }
210
-
211
- # if os.path.exists(temp_path):
212
- # os.remove(temp_path)
213
-
214
- # logger.info(f"[OCR] Trả về React: {mapped_data}")
215
- # return {"success": True, "data": mapped_data}
216
-
217
- # except Exception as e:
218
- # logger.error(f"[OCR] Lỗi: {e}", exc_info=True)
219
- # if os.path.exists(temp_path):
220
- # os.remove(temp_path)
221
- # return {"success": False, "message": str(e), "data": {}}
222
-
223
-
224
- # # ═════════════════════════════════════════════════════════════════════════════
225
- # # NHẬN DIỆN KHUÔN MẶT
226
- # # ═════════════════════════════════════════════════════════════════════════════
227
- # @app.post("/api/face/recognize")
228
- # async def recognize(
229
- # background_tasks: BackgroundTasks,
230
- # image: UploadFile = File(...),
231
- # ):
232
- # t0 = time.time()
233
- # file_bytes = await image.read()
234
- # detections = face_ai_service.extract_faces(file_bytes)
235
-
236
- # if not detections:
237
- # return {"success": True, "data": {"detected": False, "faces": []}}
238
-
239
- # results, log_queries = [], []
240
- # today = date.today()
241
-
242
- # for face in detections:
243
- # bbox = face["box"]
244
- # match = face_memory_store.find_best_match(np.array(face["descriptor"], dtype=np.float32))
245
-
246
- # if match:
247
- # # ── Kiểm tra hết hạn làm việc ────────────────────────────
248
- # expiry_str = match.get("work_expiry_date")
249
- # if expiry_str:
250
- # if date.fromisoformat(expiry_str) < today:
251
- # logger.info(f"[Recognize] {match['name']} — HẾT HẠN {expiry_str}")
252
- # results.append({
253
- # "id": match["person_id"], "name": match["name"],
254
- # "role": match["role"], "img": "",
255
- # "status": "expired", "confidence": 0, "bbox": bbox,
256
- # "expired": True, "expiry_date": expiry_str,
257
- # })
258
- # log_queries.append((str(uuid.uuid4()), match["person_id"], "unknown", 0, "Cổng Chính", "Từ chối"))
259
- # continue
260
-
261
- # confidence = round(max(0.0, (1.0 - match["distance"]) * 100.0), 2)
262
- # img_url = f"/uploads/{Path(match['img_path']).name}" if match.get("img_path") else ""
263
- # logger.info(f"[Recognize] {match['name']} dist={match['distance']:.4f} conf={confidence:.1f}%")
264
- # results.append({
265
- # "id": match["person_id"], "name": match["name"],
266
- # "role": match["role"], "img": img_url,
267
- # "status": "success", "confidence": confidence,
268
- # "bbox": bbox, "expiry_date": expiry_str,
269
- # })
270
- # log_queries.append((str(uuid.uuid4()), match["person_id"], "success", confidence, "Cổng Chính", "Vào"))
271
- # else:
272
- # results.append({
273
- # "id": None, "name": "Người Lạ", "role": "", "img": "",
274
- # "status": "unknown", "confidence": 0, "bbox": bbox,
275
- # })
276
- # log_queries.append((str(uuid.uuid4()), None, "unknown", 0, "Cổng Chính", "Từ chối"))
277
-
278
- # background_tasks.add_task(save_log_to_db, log_queries)
279
- # return {
280
- # "success": True,
281
- # "data": {
282
- # "detected": True,
283
- # "faces": results,
284
- # "processTime": int((time.time() - t0) * 1000),
285
- # "model": "InsightFace-buffalo_sc-RAM",
286
- # "ramCount": face_memory_store.count,
287
- # },
288
- # }
289
-
290
- # # ═════════════════════════════════════════════════════════════════════════════
291
- # # ĐĂNG KÝ
292
- # # ═════════════════════════════════════════════════════════════════════════════
293
- # @app.post("/api/face/register")
294
- # async def register(
295
- # name: str = Form(...),
296
- # role: str = Form(""),
297
- # department: str = Form(""),
298
- # work_expiry_date: str = Form(""), # YYYY-MM-DD hoặc ""
299
- # cccd_info: str = Form("{}"), # JSON string từ StepCCCD
300
- # images: list[UploadFile] = File(...),
301
- # cccd_front: UploadFile = File(None),
302
- # cccd_back: UploadFile = File(None),
303
- # ):
304
- # conn = get_db_connection()
305
- # cursor = conn.cursor()
306
- # person_id = str(uuid.uuid4())
307
- # new_encodings: list[tuple] = []
308
- # avatar_path = ""
309
- # saved_files = [] # Lưu danh sách file đã tạo để xóa nếu có lỗi
310
- # COSINE_THRESHOLD = 0.5 # Bổ sung biến ngưỡng vì thấy bạn nhắc tới trong code
311
-
312
- # try:
313
- # cccd = json.loads(cccd_info) if cccd_info else {}
314
- # expiry_val = work_expiry_date or None
315
- # cccd_number = cccd.get("id_number")
316
-
317
- # # ── 1. CHECK TRÙNG CCCD ─────────────────────────────────────────────
318
- # if cccd_number:
319
- # cursor.execute("SELECT id FROM citizen_ids WHERE id_number = %s", (cccd_number,))
320
- # if cursor.fetchone():
321
- # raise Exception("Số CCCD này đã được đăng ký trong hệ thống!")
322
-
323
- # # ── 2. XỬ LÝ ẢNH KHUÔN MẶT WEBCAM/UPLOAD ────────────────────────────
324
- # user_descriptor = None
325
- # for i, img_file in enumerate(images):
326
- # img_bytes = await img_file.read()
327
- # detections = face_ai_service.extract_faces(img_bytes)
328
-
329
- # if len(detections) == 0:
330
- # raise Exception(f"Không tìm thấy khuôn mặt trong ảnh mẫu thứ {i + 1}.")
331
- # if len(detections) > 1:
332
- # raise Exception(f"Ảnh mẫu thứ {i + 1} có nhiều hơn 1 khuôn mặt.")
333
-
334
- # descriptor = detections[0]["descriptor"]
335
- # emb_id = str(uuid.uuid4())
336
-
337
- # if i == 0:
338
- # user_descriptor = descriptor # Lưu ảnh đầu tiên để so sánh với CCCD
339
-
340
- # # Lưu file cứng
341
- # saved_path = face_ai_service.save_image(img_bytes, person_id, index=i)
342
- # saved_files.append(saved_path)
343
-
344
- # if i == 0:
345
- # avatar_path = saved_path
346
- # cursor.execute(
347
- # """INSERT INTO persons
348
- # (id, name, role, department, status, img_path, work_expiry_date)
349
- # VALUES (%s, %s, %s, %s, 'active', %s, %s)""",
350
- # (person_id, name, role, department, avatar_path, expiry_val),
351
- # )
352
-
353
- # cursor.execute(
354
- # "INSERT INTO face_embeddings (id, person_id, embedding_vector) VALUES (%s, %s, %s)",
355
- # (emb_id, person_id, json.dumps(descriptor)),
356
- # )
357
- # new_encodings.append((person_id, name, role, avatar_path, expiry_val, descriptor))
358
-
359
- # # ── 3. XỬ LÝ CCCD VÀ SO SÁNH KHUÔN MẶT ──────────────────────────────
360
- # front_path, back_path = "", ""
361
-
362
- # if cccd_front:
363
- # fb_bytes = await cccd_front.read()
364
- # if fb_bytes:
365
- # # Trích xuất khuôn mặt từ ảnh mặt trước CCCD
366
- # cccd_detections = face_ai_service.extract_faces(fb_bytes)
367
- # if len(cccd_detections) == 0:
368
- # raise Exception("Không tìm thấy khuôn mặt trên ảnh mặt trước CCCD.")
369
-
370
- # cccd_descriptor = cccd_detections[0]["descriptor"]
371
-
372
- # # So sánh độ tương đồng (Cosine Similarity)
373
- # q = face_memory_store._norm(np.array(user_descriptor, dtype=np.float32))
374
- # c = face_memory_store._norm(np.array(cccd_descriptor, dtype=np.float32))
375
- # score = float(np.dot(q, c))
376
-
377
- # # Nếu nhỏ hơn ngưỡng -> Không phải cùng một người
378
- # if score < COSINE_THRESHOLD:
379
- # logger.warning(f"Cảnh báo giả mạo: Score {score} < {COSINE_THRESHOLD}")
380
- # raise Exception("Cảnh báo: Khuôn mặt trên thẻ CCCD KHÔNG KHỚP với ảnh chụp trực tiếp!")
381
-
382
- # front_path = face_ai_service.save_image(fb_bytes, f"cccd_front_{person_id}", index=0)
383
- # saved_files.append(front_path)
384
-
385
- # if cccd_back:
386
- # bb_bytes = await cccd_back.read()
387
- # if bb_bytes:
388
- # back_path = face_ai_service.save_image(bb_bytes, f"cccd_back_{person_id}", index=0)
389
- # saved_files.append(back_path)
390
-
391
- # cursor.execute("""
392
- # INSERT INTO citizen_ids
393
- # (id, person_id, front_img_path, back_img_path,
394
- # id_number, full_name, dob, gender, nationality,
395
- # hometown, address, expiry_date, issue_date, special_features)
396
- # VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
397
- # """, (
398
- # str(uuid.uuid4()), person_id,
399
- # front_path or None, back_path or None,
400
- # cccd.get("id_number"), cccd.get("full_name"),
401
- # cccd.get("dob"), cccd.get("gender"),
402
- # cccd.get("nationality", "Việt Nam"),
403
- # cccd.get("hometown"), cccd.get("address"),
404
- # cccd.get("expiry_date"), cccd.get("issue_date"),
405
- # cccd.get("special_features"),
406
- # ))
407
-
408
- # conn.commit()
409
-
410
- # # ── 4. CẬP NHẬT RAM NGAY LẬP TỨC ─────────────────────────────────
411
- # for pid, pname, prole, pimg, pexpiry, enc in new_encodings:
412
- # face_memory_store.add(pid, pname, prole, pimg, enc, work_expiry_date=pexpiry)
413
-
414
- # logger.info(f"[Register] {name} | {len(new_encodings)} mẫu | RAM: {face_memory_store.count}")
415
- # return {
416
- # "success": True,
417
- # "message": f"Đã đăng ký {name} với {len(new_encodings)} mẫu.",
418
- # "img_url": f"/uploads/{Path(avatar_path).name}" if avatar_path else "",
419
- # "ramCount": face_memory_store.count,
420
- # }
421
-
422
- # except Exception as e:
423
- # conn.rollback()
424
- # logger.error(f"[Register Lỗi] {e}")
425
- # # Rollback: Xóa các file ảnh vừa tạo nếu có lỗi xảy ra
426
- # for path in saved_files:
427
- # p = Path(path)
428
- # if p.exists():
429
- # p.unlink()
430
- # return JSONResponse(status_code=400, content={"success": False, "error": str(e)})
431
- # finally:
432
- # cursor.close()
433
- # conn.close()
434
-
435
- # # ═════════════════════════════════════════════════════════════════════════════
436
- # # DANH SÁCH NGƯỜI DÙNG
437
- # # ═════════════════════════════════════════════════════════════════════════════
438
- # @app.get("/api/face/persons")
439
- # async def get_persons():
440
- # conn = get_db_connection()
441
- # cursor = conn.cursor(dictionary=True)
442
- # try:
443
- # cursor.execute("""
444
- # SELECT p.id, p.name, p.role, p.department, p.status,
445
- # p.img_path, p.work_expiry_date,
446
- # p.registered_at AS registered,
447
- # (SELECT COUNT(*) FROM face_embeddings e WHERE e.person_id = p.id) AS embeddings,
448
- # (SELECT COUNT(*) FROM recognition_logs l WHERE l.person_id = p.id AND l.status = 'success') AS recognitions,
449
- # c.id_number, c.full_name AS cccd_name, c.dob, c.gender, c.nationality,
450
- # c.hometown, c.address, c.expiry_date AS cccd_expiry,
451
- # c.front_img_path, c.back_img_path
452
- # FROM persons p
453
- # LEFT JOIN citizen_ids c ON c.person_id = p.id
454
- # ORDER BY p.registered_at DESC
455
- # """)
456
- # rows = cursor.fetchall()
457
- # today = str(date.today())
458
- # for row in rows:
459
- # raw = row.get("img_path") or ""
460
- # row["img"] = f"/uploads/{Path(raw).name}" if raw else ""
461
- # exp = row.get("work_expiry_date")
462
- # row["is_expired"] = bool(exp and str(exp) < today)
463
- # return {"success": True, "data": rows, "total": len(rows), "ramCount": face_memory_store.count}
464
- # finally:
465
- # cursor.close()
466
- # conn.close()
467
-
468
-
469
- # # ═════════════════════════════════════════════════════════════════════════════
470
- # # CẬP NHẬT & XÓA & LOGS & THỐNG KÊ
471
- # # ═════════════════════════════════════════════════════════════════════════════
472
- # @app.put("/api/face/persons/{id}")
473
- # async def update_person(id: str, person_data: PersonUpdate):
474
- # conn = get_db_connection()
475
- # cursor = conn.cursor()
476
- # try:
477
- # cursor.execute(
478
- # "UPDATE persons SET name=%s, role=%s, department=%s WHERE id=%s",
479
- # (person_data.name, person_data.role, person_data.department, id),
480
- # )
481
- # conn.commit()
482
- # if cursor.rowcount == 0:
483
- # return JSONResponse(status_code=404, content={"success": False, "error": "Không tìm thấy"})
484
- # face_memory_store.update_info(id, person_data.name, person_data.role)
485
- # return {"success": True, "message": "Cập nhật thành công"}
486
- # finally:
487
- # cursor.close()
488
- # conn.close()
489
-
490
- # @app.delete("/api/face/persons/{id}")
491
- # async def delete_person(id: str):
492
- # conn = get_db_connection()
493
- # cursor = conn.cursor(dictionary=True)
494
- # try:
495
- # cursor.execute("SELECT img_path FROM persons WHERE id=%s", (id,))
496
- # row = cursor.fetchone()
497
- # cur2 = conn.cursor()
498
- # cur2.execute("DELETE FROM persons WHERE id=%s", (id,))
499
- # conn.commit()
500
- # if cur2.rowcount == 0:
501
- # return JSONResponse(status_code=404, content={"success": False, "error": "Không tìm thấy"})
502
- # if row and row.get("img_path"):
503
- # p = Path(row["img_path"])
504
- # if p.exists():
505
- # p.unlink()
506
- # removed = face_memory_store.remove_by_person(id)
507
- # return {"success": True, "message": "Đã xóa", "removedFromRam": removed}
508
- # finally:
509
- # cursor.close()
510
- # conn.close()
511
-
512
- # @app.get("/api/face/logs")
513
- # async def get_logs():
514
- # conn = get_db_connection()
515
- # cursor = conn.cursor(dictionary=True)
516
- # try:
517
- # cursor.execute("""
518
- # SELECT l.id, COALESCE(p.name, 'Người lạ') AS name,
519
- # DATE_FORMAT(l.created_at, '%H:%i:%s') AS time,
520
- # DATE_FORMAT(l.created_at, '%d/%m/%Y') AS date,
521
- # l.status, l.confidence, l.camera, l.action,
522
- # p.img_path AS img_raw
523
- # FROM recognition_logs l
524
- # LEFT JOIN persons p ON l.person_id = p.id
525
- # ORDER BY l.created_at DESC LIMIT 100
526
- # """)
527
- # rows = cursor.fetchall()
528
- # for row in rows:
529
- # raw = row.pop("img_raw", "") or ""
530
- # row["img"] = f"/uploads/{Path(raw).name}" if raw else ""
531
- # return {"success": True, "data": rows, "total": len(rows)}
532
- # finally:
533
- # cursor.close()
534
- # conn.close()
535
-
536
- # @app.get("/api/face/statistics")
537
- # async def get_statistics():
538
- # conn = get_db_connection()
539
- # cursor = conn.cursor(dictionary=True)
540
- # try:
541
- # cursor.execute("SELECT status, created_at FROM recognition_logs ORDER BY created_at DESC LIMIT 1000")
542
- # all_logs = cursor.fetchall()
543
- # hourly = {f"{i:02d}:00": {"nhận_diện": 0, "từ_chối": 0, "lạ": 0} for i in range(24)}
544
- # days = ["T2", "T3", "T4", "T5", "T6", "T7", "CN"]
545
- # weekly = {d: 0 for d in days}
546
- # for log in all_logs:
547
- # h = f"{log['created_at'].hour:02d}:00"
548
- # d = days[log["created_at"].weekday()]
549
- # if log["status"] == "success":
550
- # hourly[h]["nhận_diện"] += 1
551
- # weekly[d] += 1
552
- # elif log["status"] == "unknown":
553
- # hourly[h]["lạ"] += 1
554
- # return {
555
- # "success": True,
556
- # "data": {
557
- # "hourlyData": [{"time": t, **v} for t, v in hourly.items()],
558
- # "weeklyData": [{"day": d, "value": v} for d, v in weekly.items()],
559
- # },
560
- # }
561
- # finally:
562
- # cursor.close()
563
- # conn.close()
564
-
565
- # @app.get("/api/face/memory-status")
566
- # async def memory_status():
567
- # return {
568
- # "success": True,
569
- # "loaded": face_memory_store.is_loaded,
570
- # "ramCount": face_memory_store.count,
571
- # }
572
-
573
- # @app.post("/api/face/reload-memory")
574
- # async def reload_memory():
575
- # _load_embeddings_to_ram()
576
- # return {"success": True, "ramCount": face_memory_store.count}
577
-
578
- # if __name__ == "__main__":
579
- # import uvicorn
580
- # uvicorn.run(app, host="0.0.0.0", port=3001)
581
-
582
  import os
583
  import sys
584
  import threading # <-- Đã thêm thư viện threading
@@ -750,7 +169,7 @@ def save_log_to_db(log_queries: list) -> None:
750
  logger.error(f"[Log] {e}")
751
 
752
 
753
- @app.post("https://vananhcs-face-id.hf.space/api/face/ocr")
754
  async def extract_ocr_local(file: UploadFile = File(...), side: str = Form(...)):
755
  # BẢO VỆ: Chặn request nếu AI chưa nạp xong
756
  if not is_ai_ready:
@@ -805,7 +224,7 @@ async def extract_ocr_local(file: UploadFile = File(...), side: str = Form(...))
805
  # ═════════════════════════════════════════════════════════════════════════════
806
  # NHẬN DIỆN KHUÔN MẶT
807
  # ═════════════════════════════════════════════════════════════════════════════
808
- @app.post("https://vananhcs-face-id.hf.space/api/face/recognize")
809
  async def recognize(
810
  background_tasks: BackgroundTasks,
811
  image: UploadFile = File(...),
@@ -871,7 +290,7 @@ async def recognize(
871
  # ═════════════════════════════════════════════════════════════════════════════
872
  # ĐĂNG KÝ
873
  # ═════════════════════════════════════════════════════════════════════════════
874
- @app.post("https://vananhcs-face-id.hf.space/api/face/register")
875
  async def register(
876
  name: str = Form(...),
877
  role: str = Form(""),
@@ -1016,7 +435,7 @@ async def register(
1016
  # ═════════════════════════════════════════════════════════════════════════════
1017
  # DANH SÁCH NGƯỜI DÙNG
1018
  # ═════════════════════════════════════════════════════════════════════════════
1019
- @app.get("https://vananhcs-face-id.hf.space/api/face/persons")
1020
  async def get_persons():
1021
  conn = get_db_connection()
1022
  cursor = conn.cursor(dictionary=True)
@@ -1050,7 +469,7 @@ async def get_persons():
1050
  # ═════════════════════════════════════════════════════════════════════════════
1051
  # CẬP NHẬT & XÓA & LOGS & THỐNG KÊ
1052
  # ════════════════════════════════════════════════��════════════════════════════
1053
- @app.put("https://vananhcs-face-id.hf.space/api/face/persons/{id}")
1054
  async def update_person(id: str, person_data: PersonUpdate):
1055
  conn = get_db_connection()
1056
  cursor = conn.cursor()
@@ -1068,7 +487,7 @@ async def update_person(id: str, person_data: PersonUpdate):
1068
  cursor.close()
1069
  conn.close()
1070
 
1071
- @app.delete("https://vananhcs-face-id.hf.space/api/face/persons/{id}")
1072
  async def delete_person(id: str):
1073
  conn = get_db_connection()
1074
  cursor = conn.cursor(dictionary=True)
@@ -1090,7 +509,7 @@ async def delete_person(id: str):
1090
  cursor.close()
1091
  conn.close()
1092
 
1093
- @app.get("https://vananhcs-face-id.hf.space/api/face/logs")
1094
  async def get_logs():
1095
  conn = get_db_connection()
1096
  cursor = conn.cursor(dictionary=True)
@@ -1114,7 +533,7 @@ async def get_logs():
1114
  cursor.close()
1115
  conn.close()
1116
 
1117
- @app.get("https://vananhcs-face-id.hf.space/api/face/statistics")
1118
  async def get_statistics():
1119
  conn = get_db_connection()
1120
  cursor = conn.cursor(dictionary=True)
@@ -1143,7 +562,7 @@ async def get_statistics():
1143
  cursor.close()
1144
  conn.close()
1145
 
1146
- @app.get("https://vananhcs-face-id.hf.space/api/face/memory-status")
1147
  async def memory_status():
1148
  return {
1149
  "success": True,
@@ -1151,7 +570,7 @@ async def memory_status():
1151
  "ramCount": face_memory_store.count,
1152
  }
1153
 
1154
- @app.post("https://vananhcs-face-id.hf.space/api/face/reload-memory")
1155
  async def reload_memory():
1156
  _load_embeddings_to_ram()
1157
  return {"success": True, "ramCount": face_memory_store.count}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
  import sys
3
  import threading # <-- Đã thêm thư viện threading
 
169
  logger.error(f"[Log] {e}")
170
 
171
 
172
+ @app.post("/api/face/ocr")
173
  async def extract_ocr_local(file: UploadFile = File(...), side: str = Form(...)):
174
  # BẢO VỆ: Chặn request nếu AI chưa nạp xong
175
  if not is_ai_ready:
 
224
  # ═════════════════════════════════════════════════════════════════════════════
225
  # NHẬN DIỆN KHUÔN MẶT
226
  # ═════════════════════════════════════════════════════════════════════════════
227
+ @app.post("/api/face/recognize")
228
  async def recognize(
229
  background_tasks: BackgroundTasks,
230
  image: UploadFile = File(...),
 
290
  # ═════════════════════════════════════════════════════════════════════════════
291
  # ĐĂNG KÝ
292
  # ═════════════════════════════════════════════════════════════════════════════
293
+ @app.post("/api/face/register")
294
  async def register(
295
  name: str = Form(...),
296
  role: str = Form(""),
 
435
  # ═════════════════════════════════════════════════════════════════════════════
436
  # DANH SÁCH NGƯỜI DÙNG
437
  # ═════════════════════════════════════════════════════════════════════════════
438
+ @app.get("/api/face/persons")
439
  async def get_persons():
440
  conn = get_db_connection()
441
  cursor = conn.cursor(dictionary=True)
 
469
  # ═════════════════════════════════════════════════════════════════════════════
470
  # CẬP NHẬT & XÓA & LOGS & THỐNG KÊ
471
  # ════════════════════════════════════════════════��════════════════════════════
472
+ @app.put("/api/face/persons/{id}")
473
  async def update_person(id: str, person_data: PersonUpdate):
474
  conn = get_db_connection()
475
  cursor = conn.cursor()
 
487
  cursor.close()
488
  conn.close()
489
 
490
+ @app.delete("/api/face/persons/{id}")
491
  async def delete_person(id: str):
492
  conn = get_db_connection()
493
  cursor = conn.cursor(dictionary=True)
 
509
  cursor.close()
510
  conn.close()
511
 
512
+ @app.get("/api/face/logs")
513
  async def get_logs():
514
  conn = get_db_connection()
515
  cursor = conn.cursor(dictionary=True)
 
533
  cursor.close()
534
  conn.close()
535
 
536
+ @app.get("/api/face/statistics")
537
  async def get_statistics():
538
  conn = get_db_connection()
539
  cursor = conn.cursor(dictionary=True)
 
562
  cursor.close()
563
  conn.close()
564
 
565
+ @app.get("/api/face/memory-status")
566
  async def memory_status():
567
  return {
568
  "success": True,
 
570
  "ramCount": face_memory_store.count,
571
  }
572
 
573
+ @app.post("/api/face/reload-memory")
574
  async def reload_memory():
575
  _load_embeddings_to_ram()
576
  return {"success": True, "ramCount": face_memory_store.count}