Spaces:
Sleeping
Sleeping
Download main.py from Hoanha2101/FPTCheckInFastAPI: direct link, hf CLI and curl.
- Browser
- Download file 31.3 kB
-
https://huggingface.co/spaces/Hoanha2101/FPTCheckInFastAPI/resolve/main/main.py
- Command line
-
hf download hf://spaces/Hoanha2101/FPTCheckInFastAPI/main.py
-
curl -L -o main.py https://huggingface.co/spaces/Hoanha2101/FPTCheckInFastAPI/resolve/main/main.py
31.3 kB
| from fastapi import FastAPI, Request, Form | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from pydantic import BaseModel | |
| import base64 | |
| import os | |
| import shutil | |
| import cv2 | |
| import numpy as np | |
| from unidecode import unidecode | |
| from FaceNet import * | |
| # from faceDetect import faceDetector | |
| from faceDetect import face_cascade | |
| from connectDatabase import get_connection | |
| import csv | |
| from typing import List | |
| from fastapi import Body, Query | |
| from config import * | |
| from fastapi import HTTPException | |
| from pydantic import BaseModel | |
| from datetime import datetime | |
| from typing import Optional | |
| from email.message import EmailMessage | |
| import io | |
| import smtplib | |
| from fastapi.responses import JSONResponse | |
| from email.mime.text import MIMEText | |
| from email.mime.multipart import MIMEMultipart | |
| from email.mime.application import MIMEApplication | |
| os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE" | |
| os.environ["TF_ENABLE_ONEDNN_OPTS"] = "0" | |
| EMAILSENDER = os.getenv("emailsender") | |
| PASSWORDEMAILSENDER = os.getenv("passwordemailsender") | |
| app = FastAPI() | |
| # CORS cho tất cả các domain | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], # Allow all origins, or specify trusted ones | |
| allow_credentials=True, | |
| allow_methods=["*"], # Allow all methods | |
| allow_headers=["*"], # Allow all headers | |
| ) | |
| # ==== MODEL ĐẦU VÀO ==== | |
| class ImageData(BaseModel): | |
| image_base64: str | |
| class SignupData(BaseModel): | |
| name_: str | |
| phone: str | |
| email: str | |
| birthday: str | |
| province: str | |
| school: str | |
| major: str | |
| class SavePersonData(BaseModel): | |
| number_id: int | |
| name_: str | |
| birthday: str | |
| phone: str | |
| major: str | |
| class Major(BaseModel): | |
| ID: int | |
| Major: str | |
| Script: str | |
| VideoLink: str | |
| class GETNEWID(BaseModel): | |
| number_id: int | |
| class PersonID(BaseModel): | |
| person_id: int | |
| class PeopleDataResponse(BaseModel): | |
| Number: int | |
| Name: str | |
| YearOfBirth: str | |
| NoPhone: str | |
| Major: str | |
| No_checkIn_ed: int | |
| class UserLogin(BaseModel): | |
| username: str | |
| password: str | |
| class UserRegister(BaseModel): | |
| username: str | |
| password: str | |
| role: int | |
| class GmailAccountData(BaseModel): | |
| account: str | |
| last_time: Optional[datetime] = None | |
| number: Optional[int] = 0 | |
| # # ==== API: PHÁT HIỆN VÀ XÁC NHẬN KHUÔN MẶT ==== | |
| # @app.post("/Capture", tags=["CheckIn API"]) | |
| # async def Capture(data: ImageData): | |
| # try: | |
| # # Giải mã base64 và lưu ảnh | |
| # imgData = base64.b64decode(data.image_base64) | |
| # with open(filename_path, 'wb') as f: | |
| # f.write(imgData) | |
| # # Đọc ảnh và phát hiện khuôn mặt | |
| # img = cv2.imread(filename_path) | |
| # results = faceDetector(img, classes=0, conf=0.3, verbose=False, device="cpu") | |
| # face_location = len(results[0].boxes) | |
| # if face_location == 0: | |
| # # Không có khuôn mặt nào trong ảnh | |
| # return {"lock": 0, "person_id": None} | |
| # elif face_location > 1: | |
| # # Có quá nhiều khuôn mặt trong ảnh | |
| # return {"lock": 1, "person_id": None} | |
| # with get_connection() as conn: | |
| # with conn.cursor() as cursor: | |
| # # Kiểm tra xem có ai trong danh sách chưa | |
| # cursor.execute("SELECT COUNT(*) FROM PeopleData") | |
| # result = cursor.fetchone() | |
| # count = result[0] if result else 0 | |
| # if count == 0: | |
| # # Nếu danh sách trống, người trong ảnh là người đầu tiên | |
| # return {"lock": 2, "person_id": 1} | |
| # else: | |
| # # Cắt khuôn mặt và lưu vào file | |
| # for result in results[0]: | |
| # boxes = result.boxes.cpu().numpy() | |
| # for box in boxes: | |
| # if box.cls[0] == 0: # Kiểm tra đối tượng là người | |
| # x_min, y_min, x_max, y_max = map(int, box.xyxy[0]) | |
| # faceArea = img[y_min:y_max, x_min:x_max] | |
| # cv2.imwrite(face_img_path, faceArea) | |
| # # So sánh khuôn mặt mới với các khuôn mặt trong cơ sở dữ liệu | |
| # cursor.execute(""" | |
| # SELECT PeopleImage.Number, PeopleImage.VectoFaceNet, PeopleData.Name, PeopleData.No_checkIn_ed | |
| # FROM PeopleImage | |
| # JOIN PeopleData ON PeopleImage.Number = PeopleData.Number | |
| # """) | |
| # rows = cursor.fetchall() | |
| # list_True_threshold = [] | |
| # list_identity = [] | |
| # encoding = img_to_encoding(face_img_path, model_FV) | |
| # best_idx = -99 | |
| # for row in rows: | |
| # person_id, vector_str, name, checkin_count = row | |
| # if vector_str: | |
| # vector_clean = vector_str.strip('[] \n') # Loại bỏ dấu [] và xuống dòng | |
| # vector_list = list(map(float, vector_clean.split())) # Tách các giá trị và chuyển sang float | |
| # vector_np = np.array(vector_list, dtype=np.float32) # Chuyển thành numpy array | |
| # distance = verifyFace(encoding, vector_np, model_FV) # Tính khoảng cách giữa khuôn mặt | |
| # if distance[0] <= 0.4: | |
| # list_True_threshold.append(distance[0]) | |
| # if list_True_threshold: | |
| # best_idx = np.argmin(np.array(list_True_threshold)) | |
| # # Nếu khuôn mặt đã có trong danh sách | |
| # return { | |
| # "lock": 3, | |
| # "person_id": int(best_idx + 1) | |
| # } | |
| # else: | |
| # # Nếu khuôn mặt chưa có trong danh sách, tạo ID mới | |
| # cursor.execute("SELECT COUNT(*) FROM PeopleData") | |
| # num_rows_id = cursor.fetchone()[0] | |
| # new_id = num_rows_id + 1 | |
| # return { | |
| # "lock": 4, | |
| # "person_id": new_id | |
| # } | |
| # except Exception as e: | |
| # return {"lock": None, "error": str(e)} | |
| # ==== API: PHÁT HIỆN VÀ XÁC NHẬN KHUÔN MẶT ==== | |
| async def Capture(data: ImageData): | |
| try: | |
| # Giải mã ảnh base64 | |
| imgData = base64.b64decode(data.image_base64) | |
| with open(filename_path, 'wb') as f: | |
| f.write(imgData) | |
| # Đọc ảnh và chuyển sang grayscale | |
| img = cv2.imread(filename_path) | |
| gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) | |
| # Phát hiện khuôn mặt bằng Haarcascade | |
| faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(60, 60)) | |
| face_location = len(faces) | |
| if face_location == 0: | |
| return {"lock": 0, "person_id": None} | |
| elif face_location > 1: | |
| return {"lock": 1, "person_id": None} | |
| # Kết nối DB | |
| with get_connection() as conn: | |
| with conn.cursor() as cursor: | |
| # Kiểm tra số người trong danh sách | |
| cursor.execute("SELECT COUNT(*) FROM PeopleData") | |
| result = cursor.fetchone() | |
| count = result[0] if result else 0 | |
| if count == 0: | |
| return {"lock": 2, "person_id": 1} | |
| # Cắt khuôn mặt từ ảnh | |
| for (x, y, w, h) in faces: | |
| faceArea = img[y:y+h, x:x+w] | |
| cv2.imwrite(face_img_path, faceArea) | |
| # So sánh khuôn mặt với DB | |
| cursor.execute(""" | |
| SELECT PeopleImage.Number, PeopleImage.VectoFaceNet, PeopleData.Name, PeopleData.No_checkIn_ed | |
| FROM PeopleImage | |
| JOIN PeopleData ON PeopleImage.Number = PeopleData.Number | |
| """) | |
| rows = cursor.fetchall() | |
| list_True_threshold = [] | |
| encoding = img_to_encoding(face_img_path, model_FV) | |
| for row in rows: | |
| person_id, vector_str, name, checkin_count = row | |
| if vector_str: | |
| vector_clean = vector_str.strip('[] \n') | |
| vector_list = list(map(float, vector_clean.split())) | |
| vector_np = np.array(vector_list, dtype=np.float32) | |
| distance = verifyFace(encoding, vector_np, model_FV) | |
| if distance[0] <= 0.4: | |
| list_True_threshold.append((distance[0], person_id)) | |
| if list_True_threshold: | |
| # Lấy người có khoảng cách nhỏ nhất | |
| best_match = min(list_True_threshold, key=lambda x: x[0]) | |
| return { | |
| "lock": 3, | |
| "person_id": int(best_match[1]) | |
| } | |
| else: | |
| # Nếu không có khớp -> gán ID mới | |
| cursor.execute("SELECT COUNT(*) FROM PeopleData") | |
| num_rows_id = cursor.fetchone()[0] | |
| new_id = num_rows_id + 1 | |
| return { | |
| "lock": 4, | |
| "person_id": new_id | |
| } | |
| except Exception as e: | |
| return {"lock": None, "error": str(e)} | |
| # ==== API: cập nhật số lần check-in add ==== | |
| async def add_checkin(data: PersonID): | |
| try: | |
| with get_connection() as conn: | |
| with conn.cursor() as cursor: | |
| # Tăng số lần check-in | |
| cursor.execute( | |
| "UPDATE PeopleData SET No_checkIn_ed = No_checkIn_ed + 1 WHERE Number = %s", | |
| (data.person_id,) | |
| ) | |
| conn.commit() | |
| # Lấy số lần check-in mới nhất | |
| cursor.execute( | |
| "SELECT No_checkIn_ed FROM PeopleData WHERE Number = %s", | |
| (data.person_id,) | |
| ) | |
| result = cursor.fetchone() | |
| checkin_count = result[0] if result else None | |
| # Lấy tổng số người | |
| cursor.execute("SELECT COUNT(*) FROM PeopleData") | |
| num_rows_id = cursor.fetchone()[0] | |
| return { | |
| "message": "Check-in updated successfully", | |
| "person_id": data.person_id, | |
| "checkin_info_number": checkin_count, | |
| "number_id": num_rows_id | |
| } | |
| except Exception as e: | |
| return {"message": "Error", "error": str(e)} | |
| # ==== API: cập nhật số lần check-in sub ==== | |
| async def Sub_checkin(data: PersonID): | |
| try: | |
| with get_connection() as conn: | |
| with conn.cursor() as cursor: | |
| # Giảm số lần check-in | |
| cursor.execute( | |
| "UPDATE PeopleData SET No_checkIn_ed = No_checkIn_ed - 1 WHERE Number = %s", | |
| (data.person_id,) | |
| ) | |
| conn.commit() | |
| # Lấy số lần check-in mới nhất | |
| cursor.execute( | |
| "SELECT No_checkIn_ed FROM PeopleData WHERE Number = %s", | |
| (data.person_id,) | |
| ) | |
| result = cursor.fetchone() | |
| checkin_count = result[0] if result else None | |
| # Lấy tổng số người | |
| cursor.execute("SELECT COUNT(*) FROM PeopleData") | |
| num_rows_id = cursor.fetchone()[0] | |
| return { | |
| "message": "Check-in updated successfully", | |
| "person_id": data.person_id, | |
| "checkin_info_number": checkin_count, | |
| "number_id": num_rows_id | |
| } | |
| except Exception as e: | |
| return {"message": "Error", "error": str(e)} | |
| # ==== API: GetNewId ==== | |
| def GetNewId(): | |
| try: | |
| with get_connection() as conn: | |
| with conn.cursor() as cursor: | |
| cursor.execute("SELECT COUNT(*) FROM PeopleData") | |
| num_rows_id = cursor.fetchone()[0] | |
| new_id = num_rows_id + 1 | |
| return GETNEWID(number_id=new_id) | |
| except Exception as e: | |
| return {"error": str(e)} | |
| # ==== API: LƯU NGƯỜI MỚI ==== | |
| async def SaveNewPeople(data: SavePersonData): | |
| try: | |
| number_id_save = data.number_id | |
| name_save = data.name_ | |
| birthday_save = data.birthday | |
| phone_save = data.phone | |
| major_save = data.major | |
| with get_connection() as conn: | |
| with conn.cursor() as cursor: | |
| # Insert dữ liệu người mới vào PeopleData | |
| cursor.execute(""" | |
| INSERT INTO PeopleData (Number, Name, YearOfBirth, NoPhone, Major, No_checkIn_ed) | |
| VALUES (%s, %s, %s, %s, %s, %s) | |
| """, (number_id_save, name_save, birthday_save, phone_save, major_save, 1)) | |
| conn.commit() | |
| # Detect & extract vector (xử lý ngoài database) | |
| img = cv2.imread(filename_path) | |
| results = faceDetector.predict(img, classes=0, conf=0.3, verbose=False, device="cpu") | |
| # Cắt và lưu khuôn mặt | |
| for result in results[0]: | |
| boxes = result.boxes.cpu().numpy() | |
| for box in boxes: | |
| if box.cls[0] == 0: | |
| x_min, y_min, x_max, y_max = map(int, box.xyxy[0]) | |
| faceArea = img[y_min:y_max, x_min:x_max] | |
| cv2.imwrite(face_img_path, faceArea) | |
| vecto_extract = img_to_encoding(face_img_path, model_FV) | |
| print("vecto_extract:", vecto_extract) | |
| with open(filename_path, "rb") as f: | |
| full_img_base64 = base64.b64encode(f.read()).decode("utf-8") | |
| with open(face_img_path, "rb") as f: | |
| face_img_base64 = base64.b64encode(f.read()).decode("utf-8") | |
| vecto_string = ",".join(map(str, vecto_extract)) | |
| print("vecto_string:", vecto_string) | |
| # Insert hình ảnh và vector vào PeopleImage | |
| with get_connection() as conn: | |
| with conn.cursor() as cursor: | |
| cursor.execute(""" | |
| INSERT INTO PeopleImage (Number, FullImageBase64, FaceImageBase64, VectoFaceNet) | |
| VALUES (%s, %s, %s, %s) | |
| """, (number_id_save, full_img_base64, face_img_base64, vecto_string)) | |
| conn.commit() | |
| return {"content": "Saved"} | |
| except Exception as e: | |
| return {"error": str(e)} | |
| # ==== API: LẤY TẤT CẢ DỮ LIỆU PeopleData ==== | |
| def get_all_people_data(): | |
| try: | |
| with get_connection() as conn: | |
| with conn.cursor() as cursor: | |
| cursor.execute("SELECT Number, Name, YearOfBirth, NoPhone, Major, No_checkIn_ed FROM PeopleData") | |
| rows = cursor.fetchall() | |
| return [ | |
| PeopleDataResponse( | |
| Number=row[0], | |
| Name=row[1], | |
| YearOfBirth=row[2], | |
| NoPhone=row[3], | |
| Major=row[4], | |
| No_checkIn_ed=row[5] | |
| ) | |
| for row in rows | |
| ] | |
| except Exception as e: | |
| return {"error": str(e)} | |
| # ==== API: XÓA MỘT NGƯỜI ==== | |
| async def delete_person(data: PersonID): | |
| try: | |
| with get_connection() as conn: | |
| with conn.cursor() as cursor: | |
| cursor.execute("DELETE FROM PeopleImage WHERE Number = %s", (data.person_id,)) | |
| cursor.execute("DELETE FROM PeopleData WHERE Number = %s", (data.person_id,)) | |
| conn.commit() | |
| return { | |
| "message": f"Person with ID {data.person_id} deleted successfully." | |
| } | |
| except Exception as e: | |
| return { | |
| "message": "Error during deletion", | |
| "error": str(e) | |
| } | |
| # ==== API: LẤY THÔNG TIN ĐẦY ĐỦ CỦA 1 NGƯỜI ==== | |
| async def get_full_person_info(person_id: int = Query(..., description="ID của người cần lấy thông tin")): | |
| try: | |
| with get_connection() as conn: | |
| with conn.cursor() as cursor: | |
| # Lấy thông tin cơ bản | |
| cursor.execute(""" | |
| SELECT Number, Name, YearOfBirth, NoPhone, Major, No_checkIn_ed | |
| FROM PeopleData | |
| WHERE Number = %s | |
| """, (person_id,)) | |
| person_data = cursor.fetchone() | |
| if not person_data: | |
| return { | |
| "message": "Không tìm thấy người dùng với person_id này.", | |
| "person_id": person_id | |
| } | |
| # Lấy ảnh và vector khuôn mặt | |
| cursor.execute(""" | |
| SELECT FullImageBase64, FaceImageBase64, VectoFaceNet | |
| FROM PeopleImage | |
| WHERE Number = %s | |
| """, (person_id,)) | |
| image_data = cursor.fetchone() | |
| # Lấy mô tả chuyên ngành | |
| cursor.execute(""" | |
| SELECT Script, VideoLink | |
| FROM MajorData | |
| WHERE Major = %s | |
| """, (person_data[4],)) | |
| major_data = cursor.fetchone() | |
| return { | |
| "message": "Lấy thông tin đầy đủ thành công.", | |
| "person": { | |
| "Number": person_data[0], | |
| "Name": person_data[1], | |
| "YearOfBirth": person_data[2], | |
| "NoPhone": person_data[3], | |
| "Major": person_data[4], | |
| "No_checkIn_ed": person_data[5], | |
| "Image": { | |
| "FullImageBase64": image_data[0] if image_data else None, | |
| "FaceImageBase64": image_data[1] if image_data else None, | |
| "VectoFaceNet": image_data[2] if image_data else None | |
| }, | |
| "MajorInfo": { | |
| "Script": major_data[0] if major_data else None, | |
| "VideoLink": major_data[1] if major_data else None | |
| } | |
| } | |
| } | |
| except Exception as e: | |
| return { | |
| "message": "Lỗi khi truy vấn dữ liệu", | |
| "error": str(e) | |
| } | |
| # ==== API: LẤY THÔNG TIN PHẦN QUÀ ==== | |
| async def get_rewards(): | |
| try: | |
| with get_connection() as conn: | |
| with conn.cursor() as cursor: | |
| cursor.execute("SELECT Name FROM Rewards") | |
| rows = cursor.fetchall() | |
| rewards = [row[0] for row in rows] | |
| return {"rewards": rewards} | |
| except Exception as e: | |
| return {"message": "Lỗi khi truy vấn phần quà", "error": str(e)} | |
| # # ==== API: Lấy thông tin của ngành nghề quan tâm ==== | |
| async def get_majors(): | |
| try: | |
| with get_connection() as connection: | |
| with connection.cursor() as cursor: | |
| cursor.execute("SELECT Name FROM Majors;") | |
| rows = cursor.fetchall() | |
| majors = [{"label": row[0], "value": row[0]} for row in rows] | |
| return {"data_major": majors} | |
| except Exception as e: | |
| return {"message": "Lỗi khi truy vấn ngành học", "error": str(e)} | |
| # ==== API: LẤY DATA MAJOR TRÊN BẢNG TIN ==== | |
| def get_major_data(): | |
| try: | |
| with get_connection() as conn: | |
| with conn.cursor() as cursor: | |
| cursor.execute("SELECT ID, Major, Script, VideoLink FROM MajorData") | |
| rows = cursor.fetchall() | |
| return [ | |
| Major( | |
| ID=row[0], | |
| Major=row[1], | |
| Script=row[2], | |
| VideoLink=row[3] | |
| ) for row in rows | |
| ] | |
| except Exception as e: | |
| return [{"ID": -1, "Major": "Error", "Script": str(e), "VideoLink": ""}] | |
| # ==== API: ĐĂNG KÝ NHẬN TƯ VẤN ==== | |
| async def signup_advise(data: SignupData): | |
| try: | |
| with get_connection() as conn: | |
| with conn.cursor() as cursor: | |
| cursor.execute(""" | |
| INSERT INTO signup_advise (Name, Nophone, email, birthYear, province, school, major) | |
| VALUES (%s, %s, %s, %s, %s, %s, %s) | |
| """, (data.name_, data.phone, data.email, data.birthday, data.province, data.school, data.major)) | |
| conn.commit() | |
| return {"content": "Saved"} | |
| except Exception as e: | |
| return {"content": f"Error: {str(e)}"} | |
| # ==== API: Lấy toàn bộ bảng signup_advise ==== | |
| async def get_all_advise(): | |
| try: | |
| with get_connection() as conn: | |
| with conn.cursor() as cursor: | |
| cursor.execute("SELECT * FROM signup_advise") | |
| rows = cursor.fetchall() | |
| advise_list = [] | |
| for row in rows: | |
| advise_data = SignupData( | |
| name_=row[1], # chú ý: row[0] là id, còn name nằm ở row[1] | |
| phone=row[2], | |
| email=row[3], | |
| birthday=row[4], | |
| province=row[5], | |
| school=row[6], | |
| major=row[7] | |
| ) | |
| advise_list.append(advise_data) | |
| return advise_list | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=f"Error: {str(e)}") | |
| # ==== API: Xóa một bản ghi theo ID ==== | |
| async def delete_advise(advise_id: int): | |
| try: | |
| with get_connection() as conn: | |
| with conn.cursor() as cursor: | |
| cursor.execute("DELETE FROM signup_advise WHERE id = %s", (advise_id,)) | |
| conn.commit() | |
| if cursor.rowcount == 0: | |
| return {"content": f"No record found with ID {advise_id}"} | |
| return {"content": f"Record with ID {advise_id} deleted successfully"} | |
| except Exception as e: | |
| return {"content": f"Error: {str(e)}"} | |
| # ==== API: Lấy thông tin một bản ghi theo ID ==== | |
| async def get_advise_by_id(advise_id: int): | |
| try: | |
| with get_connection() as conn: | |
| with conn.cursor() as cursor: | |
| cursor.execute("SELECT * FROM signup_advise WHERE id = %s", (advise_id,)) | |
| row = cursor.fetchone() | |
| if row: | |
| advise_data = SignupData( | |
| name_=row[1], | |
| phone=row[2], | |
| email=row[3], | |
| birthday=row[4], | |
| province=row[5], | |
| school=row[6], | |
| major=row[7] | |
| ) | |
| return advise_data | |
| else: | |
| return {"content": f"No record found with ID {advise_id}"} | |
| except Exception as e: | |
| return {"content": f"Error: {str(e)}"} | |
| # ==== API: Đăng nhập với root (chỉ role=0) ==== | |
| async def login_root(data: UserLogin): | |
| try: | |
| with get_connection() as conn: | |
| with conn.cursor() as cursor: | |
| cursor.execute("SELECT role FROM UserAccount WHERE username=%s AND password=%s", (data.username, data.password)) | |
| row = cursor.fetchone() | |
| if row and row[0] == 0: | |
| return {"message": "Login successful (root)"} | |
| else: | |
| return {"message": "Unauthorized or wrong credentials"} | |
| except Exception as e: | |
| return {"error": str(e)} | |
| # ==== API: Đăng nhập (mọi role) ==== | |
| async def login(data: UserLogin): | |
| try: | |
| with get_connection() as conn: | |
| with conn.cursor() as cursor: | |
| cursor.execute("SELECT role FROM UserAccount WHERE username=%s AND password=%s", (data.username, data.password)) | |
| row = cursor.fetchone() | |
| if row: | |
| return {"message": "Login successful", "role": row[0]} | |
| else: | |
| return {"message": "Invalid credentials"} | |
| except Exception as e: | |
| return {"error": str(e)} | |
| # ==== API: Đăng ký ==== | |
| async def register(data: UserRegister): | |
| try: | |
| with get_connection() as conn: | |
| with conn.cursor() as cursor: | |
| cursor.execute("INSERT INTO UserAccount (username, password, role) VALUES (%s, %s, %s)", | |
| (data.username, data.password, data.role)) | |
| conn.commit() | |
| return {"message": "User registered successfully"} | |
| except Exception as e: | |
| return {"error": str(e)} | |
| # ==== API: Thêm Gmail vào bảng GmailAccount==== | |
| async def add_gmail(data: GmailAccountData): | |
| try: | |
| with get_connection() as conn: | |
| with conn.cursor() as cursor: | |
| cursor.execute("INSERT INTO GmailAccount (account, last_time, number) VALUES (%s, %s, %s)", | |
| (data.account, data.last_time, data.number)) | |
| conn.commit() | |
| return {"message": "Gmail account added successfully"} | |
| except Exception as e: | |
| return {"error": str(e)} | |
| # ==== API: Sửa Gmail theo id==== | |
| async def update_gmail(id: int, data: GmailAccountData): | |
| try: | |
| with get_connection() as conn: | |
| with conn.cursor() as cursor: | |
| cursor.execute(""" | |
| UPDATE GmailAccount | |
| SET account=%s, last_time=%s, number=%s | |
| WHERE id=%s | |
| """, (data.account, data.last_time, data.number, id)) | |
| conn.commit() | |
| return {"message": "Gmail account updated successfully"} | |
| except Exception as e: | |
| return {"error": str(e)} | |
| # ==== API: Xóa Gmail theo id ==== | |
| async def delete_gmail(id: int): | |
| try: | |
| with get_connection() as conn: | |
| with conn.cursor() as cursor: | |
| cursor.execute("DELETE FROM GmailAccount WHERE id=%s", (id,)) | |
| conn.commit() | |
| return {"message": f"Gmail account with id {id} deleted"} | |
| except Exception as e: | |
| return {"error": str(e)} | |
| # ==== API: Lấy tất cả Gmail ==== | |
| async def get_all_gmail(): | |
| try: | |
| with get_connection() as conn: | |
| with conn.cursor() as cursor: | |
| cursor.execute("SELECT * FROM GmailAccount") | |
| rows = cursor.fetchall() | |
| return [{"id": r[0], "account": r[1], "last_time": r[2], "number": r[3]} for r in rows] | |
| except Exception as e: | |
| return {"error": str(e)} | |
| # ==== API: Send report to Gmail ==== | |
| async def send_report(to: str = Form(...)): | |
| try: | |
| with get_connection() as conn: | |
| with conn.cursor() as cursor: | |
| # Lấy dữ liệu từ bảng signup_advise | |
| cursor.execute("SELECT * FROM signup_advise") | |
| advise_rows = cursor.fetchall() | |
| advise_headers = [desc[0] for desc in cursor.description] | |
| # Lấy dữ liệu từ bảng PeopleData | |
| cursor.execute("SELECT Number, Name, YearOfBirth, NoPhone, Major, No_checkIn_ed FROM PeopleData") | |
| people_rows = cursor.fetchall() | |
| people_headers = [desc[0] for desc in cursor.description] | |
| def generate_csv(rows, headers): | |
| output = io.StringIO() | |
| writer = csv.writer(output) | |
| writer.writerow(headers) | |
| writer.writerows(rows) | |
| return output.getvalue() | |
| advise_csv = generate_csv(advise_rows, advise_headers) | |
| people_csv = generate_csv(people_rows, people_headers) | |
| # Tạo email đẹp bằng HTML | |
| msg = MIMEMultipart() | |
| msg['Subject'] = "📊 Báo cáo hệ thống" | |
| msg['From'] = EMAILSENDER | |
| msg['To'] = to | |
| html_content = """ | |
| <html> | |
| <body> | |
| <h2>📋 Báo cáo hệ thống</h2> | |
| <p>Xin chào,</p> | |
| <p>Vui lòng xem báo cáo mới nhất từ hệ thống trong các tệp đính kèm bên dưới:</p> | |
| <ul> | |
| <li><strong>signupAdvise.csv</strong>: Danh sách tư vấn đăng ký.</li> | |
| <li><strong>checkin.csv</strong>: Dữ liệu điểm danh.</li> | |
| </ul> | |
| <p>Trân trọng,<br>Hệ thống FPT Check-in</p> | |
| </body> | |
| </html> | |
| """ | |
| msg.attach(MIMEText(html_content, "html")) | |
| # Đính kèm từng file CSV | |
| part1 = MIMEApplication(advise_csv.encode("utf-8"), _subtype="csv") | |
| part1.add_header('Content-Disposition', 'attachment', filename="signupAdvise.csv") | |
| msg.attach(part1) | |
| part2 = MIMEApplication(people_csv.encode("utf-8"), _subtype="csv") | |
| part2.add_header('Content-Disposition', 'attachment', filename="checkin.csv") | |
| msg.attach(part2) | |
| # Gửi email | |
| with smtplib.SMTP_SSL("smtp.gmail.com", 465) as smtp: | |
| smtp.login(EMAILSENDER, PASSWORDEMAILSENDER) | |
| smtp.send_message(msg) | |
| return {"message": f"Email đã được gửi thành công tới {to}"} | |
| except Exception as e: | |
| return JSONResponse(status_code=500, content={"error": str(e)}) |