-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain_windows.py
More file actions
172 lines (145 loc) · 6.85 KB
/
main_windows.py
File metadata and controls
172 lines (145 loc) · 6.85 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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
from fastapi import FastAPI, File, UploadFile, Request, WebSocket, Response
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from PIL import Image
import io
import os
import uvicorn # Import Uvicorn
import cv2
import face_recognition
import os
import time
import sys
from pathlib import Path
import webbrowser
import zipfile
import shutil
import socket
import qrcode
from colorama import init, Fore, Back, Style
app = FastAPI()
templates = Jinja2Templates(directory="templates")
# Create a folder to store the uploaded and processed images
os.makedirs ("images", exist_ok=True)
os.makedirs ("images_tmp", exist_ok=True)
# Mount the folder as a static file directory
app.mount ("/images", StaticFiles (directory="images"), name="images")
app.mount ("/images_tmp", StaticFiles (directory="images_tmp"), name="images_tmp")
app.mount("/static", StaticFiles(directory="static"), name="static")
# Define a route to display the web UI
@app.get ("/", response_class=HTMLResponse)
async def index(request:Request):
# Return a simple HTML form to upload a file
return templates.TemplateResponse("index.html", {"request": request, "message": None})
# Define a route to handle the file upload
@app.post ("/uploadfile/")
async def create_upload_file(img: UploadFile = File (...), files: list[UploadFile] = File (...)):
# Save the uploaded file to the images folder
file_path = os.path.join ("images", img.filename)
image_path = file_path
print(file_path)
for file in files:
# Save the uploaded file to the images folder
pathdir = os.path.join ("images_tmp", file.filename).replace("/", "\\")
print(pathdir)
substring=pathdir.split("\\")
os.makedirs ("images_tmp\\"+substring[1], exist_ok=True)
folder_files = os.path.join ("images_tmp", file.filename).replace("/", "\\")
#os.makedirs (folder_files, exist_ok=True)
with open (folder_files, "wb") as f:
f.write (file.file.read())
with open (file_path, "wb") as f:
f.write (img.file.read ())
pictures_folder = os.path.join ("images_tmp\\"+substring[1]).replace("/", "\\")
total_files = len([name for name in os.listdir(pictures_folder) if os.path.isfile(os.path.join(pictures_folder, name))])
processed_files = 0
docs_img = cv2.imread(f"{image_path}")
docs_rgb_img = cv2.cvtColor(docs_img, cv2.COLOR_BGR2RGB)
docs_img_encoding = face_recognition.face_encodings(docs_rgb_img)[0]
start_time = time.time()
os.makedirs ("images_tmp\\"+substring[1]+"FaceDetected", exist_ok=True)
foldername = os.path.join(os.getcwd(), "images_tmp\\"+substring[1]+"FaceDetected")
os.startfile(foldername)
#os.system('xdg-open "%s"' % foldername) for linux
for root, dirs, files in os.walk(pictures_folder):
for file in files:
if file.endswith(".jpeg") or file.endswith(".jpg") or file.endswith(".png"):
img_path = os.path.join(root, file)
img = cv2.imread(img_path)
rgb_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
#img_encoding = face_recognition.face_encodings(rgb_img)[0]
encodings = face_recognition.face_encodings(rgb_img)
if len(encodings) > 0:
img_encoding = encodings[0]
# do something with img_encoding
else:
print("No faces found in the image")
result = face_recognition.compare_faces([docs_img_encoding], img_encoding)
processed_files += 1
elapsed_time = time.time() - start_time
estimated_time = (elapsed_time / processed_files) * (total_files - processed_files)
print(f"Processed {processed_files} out of {total_files} files. Estimated time left: {estimated_time:.2f} seconds.")
if result[0]:
cv2.imshow(" ",img)
#cv2.waitKey(0)
cv2.destroyAllWindows()
Face_folder = os.path.join ("images_tmp\\"+substring[1]+"FaceDetected")
print(f"File name: {file}, Location: {img_path}")
shutil.copy(img_path, Face_folder)
#return templates.TemplateResponse("gallery.html", {"request":None , "image_files": pictures_folder})
# Define a route for the download page that will allow the user to select and download images as a zip file
@app.post("/download", response_class=HTMLResponse)
async def download(request: Request):
# Get the form data from the request
form_data = await request.form()
# Get the list of selected image filenames from the form data
selected_images = form_data.getlist("images")
# Create a zip file in memory
zip_buffer = io.BytesIO()
with zipfile.ZipFile(zip_buffer, "w") as zip_file:
# Loop through the selected images and add them to the zip file
for image in selected_images:
zip_file.write(f"images_tmp/{image}", image)
# Return the zip file as a response with the appropriate headers
return Response(
zip_buffer.getvalue(),
media_type="application/zip",
headers={
"Content-Disposition": "attachment; filename=images.zip"
}
)
# Add a conditional statement to run Uvicorn if the file is the main script
if __name__ == "__main__":
set_port = 8005
host_address = "0.0.0.0"
# Get local IP address
hostname = socket.gethostname()
local_ip = socket.gethostbyname(hostname)
try:
init()
# Generate QR code for network access
network_url = f"http://{local_ip}:{set_port}"
qr = qrcode.QRCode(version=1,error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=1,
border=2)
qr.add_data(network_url)
qr.make(fit=True)
# Print QR code in terminal
# Print the QR code to the terminal
print("\nScan this QR code to access FaceFinder:")
print(Style.BRIGHT)
qr_string = qr.get_matrix()
for row in qr_string:
print(''.join('██' if cell else ' ' for cell in row))
print(Style.RESET_ALL)
print(f"\nStarting FaceFinder Server...")
print(f"Local Access URL: http://127.0.0.1:{set_port}")
print(f"Network Access URL: http://{local_ip}:{set_port}")
print("\nTo access from other devices in your network, use the Network Access URL")
print("Make sure your firewall allows incoming connections on port {set_port}")
web_address = f"http://127.0.0.1:{set_port}/"
webbrowser.open(web_address)
uvicorn.run("main_windows:app", host=host_address, port=set_port, reload=True)
except Exception as e:
print(f"Error starting server: {e}")