Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 49 additions & 1 deletion .github/workflows/build-windows.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,55 @@ jobs:

- name: Build Glance.exe with PyInstaller
working-directory: windows
shell: pwsh
run: |
python -m PyInstaller --noconfirm --clean --windowed --onefile --name Glance --collect-data cv2 --add-data "models/haarcascade_frontalface_default.xml;models" glance_windows.py

- name: Check packaged face detector
shell: pwsh
run: |
$process = Start-Process -FilePath "windows/dist/Glance.exe" -ArgumentList "--self-test" -PassThru
if (-not $process.WaitForExit(60000)) {
Stop-Process -Id $process.Id -Force -ErrorAction SilentlyContinue
throw "Packaged detector self-test timed out"
}
if ($process.ExitCode -ne 0) {
$log = Join-Path $env:APPDATA "Glance/camera-error.log"
if (Test-Path $log) { Get-Content $log }
throw "Packaged detector self-test failed: $($process.ExitCode)"
}

- name: Check packaged camera pipeline and overlay
shell: pwsh
run: |
$process = Start-Process -FilePath "windows/dist/Glance.exe" -ArgumentList "--self-test-camera" -PassThru
if (-not $process.WaitForExit(60000)) {
Stop-Process -Id $process.Id -Force -ErrorAction SilentlyContinue
throw "Packaged camera pipeline self-test timed out"
}
if ($process.ExitCode -ne 0) {
$log = Join-Path $env:APPDATA "Glance/camera-error.log"
if (Test-Path $log) { Get-Content $log }
throw "Packaged camera pipeline self-test failed: $($process.ExitCode)"
}

- name: Check packaged detector under a Vietnamese user path
shell: pwsh
run: |
python -m PyInstaller --noconfirm --clean --windowed --onefile --name Glance --collect-data cv2 glance_windows.py
$tempFolder = Join-Path $env:RUNNER_TEMP "Người-dùng-đặng"
New-Item -ItemType Directory -Force -Path $tempFolder | Out-Null
$env:TEMP = $tempFolder
$env:TMP = $tempFolder
$process = Start-Process -FilePath "windows/dist/Glance.exe" -ArgumentList "--self-test" -PassThru
if (-not $process.WaitForExit(60000)) {
Stop-Process -Id $process.Id -Force -ErrorAction SilentlyContinue
throw "Vietnamese path self-test timed out"
}
if ($process.ExitCode -ne 0) {
$log = Join-Path $env:APPDATA "Glance/camera-error.log"
if (Test-Path $log) { Get-Content $log }
throw "Vietnamese path self-test failed: $($process.ExitCode)"
}

- name: Assemble Glance-Windows.zip
shell: pwsh
Expand All @@ -42,6 +89,7 @@ jobs:
Copy-Item "windows/glance_windows.py" $stage
Copy-Item "windows/guard.py" $stage
Copy-Item "windows/posture.py" $stage
Copy-Item "windows/models" $stage -Recurse
Copy-Item "windows/requirements.txt" $stage
Copy-Item "windows/start_windows.bat" $stage
Copy-Item "windows/build_exe.bat" $stage
Expand Down
3 changes: 2 additions & 1 deletion windows/build_exe.bat
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@ if errorlevel 1 (
)

echo [Glance] Dang tien hanh dong goi Glance.exe bang PyInstaller...
!BUILD_PY! -m PyInstaller --noconfirm --clean --windowed --onefile --name Glance --collect-data cv2 glance_windows.py
if not exist "models\haarcascade_frontalface_default.xml" goto :failed
!BUILD_PY! -m PyInstaller --noconfirm --clean --windowed --onefile --name Glance --collect-data cv2 --add-data "models\haarcascade_frontalface_default.xml;models" glance_windows.py
if errorlevel 1 goto :failed

echo.
Expand Down
157 changes: 123 additions & 34 deletions windows/glance_windows.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import threading
import time
import tkinter as tk
import traceback
from tkinter import ttk

import cv2
Expand Down Expand Up @@ -50,6 +51,64 @@

CONFIG_DIR = os.path.join(os.environ.get("APPDATA", os.path.expanduser("~")), "Glance")
CONFIG_PATH = os.path.join(CONFIG_DIR, "config.json")
CAMERA_ERROR_PATH = os.path.join(CONFIG_DIR, "camera-error.log")


def record_camera_error():
"""Save diagnostic details locally without recording camera frames."""
try:
os.makedirs(CONFIG_DIR, exist_ok=True)
with open(CAMERA_ERROR_PATH, "w", encoding="utf-8") as log:
traceback.print_exc(file=log)
except OSError:
pass


def open_camera(index):
"""Try Windows camera backends independently when one cannot open a device."""
for backend in (cv2.CAP_DSHOW, cv2.CAP_MSMF, cv2.CAP_ANY):
capture = None
try:
capture = cv2.VideoCapture(index, backend)
if capture is not None and capture.isOpened():
return capture
except cv2.error:
pass
if capture is not None:
capture.release()
return None


def load_face_detector():
cascade_name = "haarcascade_frontalface_default.xml"
candidates = []
if getattr(sys, "_MEIPASS", None):
candidates.append(os.path.join(sys._MEIPASS, "models", cascade_name))
candidates.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "models", cascade_name))
if hasattr(cv2, "data") and getattr(cv2.data, "haarcascades", None):
candidates.append(os.path.join(cv2.data.haarcascades, cascade_name))
if getattr(sys, "_MEIPASS", None):
candidates.append(os.path.join(sys._MEIPASS, "cv2", "data", cascade_name))
candidates.append(os.path.join(sys._MEIPASS, cascade_name))
candidates.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), cascade_name))
path = next((candidate for candidate in candidates if os.path.exists(candidate)), None)
if path is None:
raise FileNotFoundError("Face detection model is missing")
# OpenCV's Windows filename handling can fail for paths with Vietnamese
# characters. Python opens the file with Unicode support; OpenCV parses
# the model from memory instead of opening the path itself.
with open(path, "r", encoding="utf-8") as model:
contents = model.read()
storage = cv2.FileStorage(contents, cv2.FILE_STORAGE_READ | cv2.FILE_STORAGE_MEMORY)
try:
if not storage.isOpened():
raise RuntimeError("Face detection model could not be opened")
detector = cv2.CascadeClassifier()
if not detector.read(storage.getFirstTopLevelNode()) or detector.empty():
raise RuntimeError("Face detection model could not be loaded")
finally:
storage.release()
return detector


def load_config():
Expand Down Expand Up @@ -572,38 +631,13 @@ def publish(self, generation, kind, value=None):
def camera_loop(self, generation, stop, index, delay):
cap = None
try:
cascade_name = "haarcascade_frontalface_default.xml"
cascade_candidates = []
if hasattr(cv2, "data") and getattr(cv2.data, "haarcascades", None):
cascade_candidates.append(os.path.join(cv2.data.haarcascades, cascade_name))
if getattr(sys, "_MEIPASS", None):
cascade_candidates.append(os.path.join(sys._MEIPASS, "cv2", "data", cascade_name))
cascade_candidates.append(os.path.join(sys._MEIPASS, cascade_name))
cascade_candidates.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), cascade_name))
cascade_path = next((p for p in cascade_candidates if os.path.exists(p)), cascade_candidates[0])
detector = cv2.CascadeClassifier(cascade_path)
if detector.empty():
self.publish(generation, "error", "Không tải được bộ nhận diện khuôn mặt.")
return
# Camera busy (Zoom/Teams holding it) is normal on Windows:
# wait and retry instead of dying — auto-resume when it frees.
def open_camera(cam_idx):
c = cv2.VideoCapture(cam_idx, cv2.CAP_DSHOW)
if c is not None and c.isOpened():
return c
if c is not None:
c.release()
c = cv2.VideoCapture(cam_idx)
return c

detector = load_face_detector()
cap = open_camera(index)
announced_busy = False
while not cap.isOpened() and not stop.is_set():
cap.release()
if not announced_busy:
self.publish(generation, "busy", None)
announced_busy = True
stop.wait(3)
while cap is None and not stop.is_set():
# Each retry refreshes the watchdog while waiting for a device.
self.publish(generation, "busy", index)
if stop.wait(3):
return
cap = open_camera(index)
if stop.is_set():
return
Expand Down Expand Up @@ -652,7 +686,9 @@ def open_camera(cam_idx):
last_state = state
stop.wait(wait_seconds)
except Exception:
self.publish(generation, "error", "Camera gặp lỗi. Tính năng tự động đã dừng; hãy thử bật lại.")
record_camera_error()
self.publish(generation, "error", "Camera gặp lỗi. Tính năng tự động đã dừng. "
"Thông tin lỗi được lưu tại %APPDATA%\\Glance\\camera-error.log.")
finally:
if cap is not None:
cap.release()
Expand All @@ -671,7 +707,8 @@ def poll(self):
self.start_button.configure(text="Bật camera")
elif kind == "busy":
self.last_frame_at = time.monotonic()
self.status.set("Camera đang bận (Zoom/Teams đang dùng?). Glance tự mở lại khi camera trống.")
self.status.set(f"Không mở được camera {value}. Kiểm tra quyền camera, "
"đóng ứng dụng đang dùng camera hoặc thử camera 0. Glance đang thử lại.")
elif kind == "blocked":
self.last_frame_at = time.monotonic()
self.automatic_cover = False
Expand Down Expand Up @@ -708,5 +745,57 @@ def close(self):
self.root.destroy()


def run_camera_pipeline_self_test():
"""Exercise the packaged camera pipeline and overlay with synthetic frames."""
import numpy as np

class TestCamera:
def read(self):
return True, np.full((240, 320, 3), 128, dtype=np.uint8)

def set(self, *args):
return True

def release(self):
pass

global open_camera, foreground_is_fullscreen, idle_seconds
open_camera = lambda index: TestCamera()
foreground_is_fullscreen = lambda: False
idle_seconds = lambda: 10
root = tk.Tk()
app = App(root)
try:
root.withdraw()
app.activity.set(False)
app.delay.set(0)
app.toggle_camera()
end = time.monotonic() + 15
while time.monotonic() < end:
root.update()
if app.automatic_cover and app.cover.visible:
break
time.sleep(0.05)
else:
raise RuntimeError("Camera pipeline or screen cover did not activate: " + app.status.get())
app.stop_camera()
root.update()
if app.cover.visible:
raise RuntimeError("Screen cover did not close after stopping the camera")
finally:
app.close()


if __name__ == "__main__":
App(tk.Tk()).root.mainloop()
if "--self-test" in sys.argv or "--self-test-camera" in sys.argv:
try:
import numpy as np
if "--self-test-camera" in sys.argv:
run_camera_pipeline_self_test()
else:
load_face_detector().detectMultiScale(np.zeros((64, 64), dtype=np.uint8))
except Exception:
record_camera_error()
sys.exit(1)
else:
App(tk.Tk()).root.mainloop()
Loading
Loading