-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
223 lines (175 loc) · 7.5 KB
/
main.py
File metadata and controls
223 lines (175 loc) · 7.5 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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
import os
import sys
import time
import cv2 # type: ignore
import requests
from dotenv import load_dotenv
from pyzbar.pyzbar import decode # type: ignore
from dataclasses import dataclass
from typing import Optional
load_dotenv()
CHECKIN_LIST_SLUG: str = os.getenv("TITO_CHECKIN_LIST_SLUG", "")
if not CHECKIN_LIST_SLUG:
print("Error: Missing TITO_CHECKIN_LIST_SLUG environment variable.")
sys.exit(1)
BASE_URL: str = f"https://checkin.tito.io/checkin_lists/{CHECKIN_LIST_SLUG}"
HEADERS: dict[str, str] = {
"Accept": "application/json",
"Content-Type": "application/json",
"User-Agent": "BirmingHack Sign-in System (contact email css@guild.bham.ac.uk)",
}
@dataclass
class Ticket:
slug: str
reference: str
t_id: int
name: str
checkin_uuid: Optional[str] = None
@property
def is_checked_in(self) -> bool:
return self.checkin_uuid is not None
class AttendeeTracker:
def __init__(self) -> None:
self.tickets_by_slug: dict[str, Ticket] = {}
self.tickets_by_id: dict[int, Ticket] = {}
self.last_scan_time: float = 0
self.scan_cooldown: int = 4
def initialize_data(self) -> None:
"""Fetches tickets and existing check-ins to sync state."""
# 1. Fetch all tickets
try:
tickets_response = requests.get(f"{BASE_URL}/tickets", headers=HEADERS)
tickets_response.raise_for_status()
tickets_data = tickets_response.json()
tickets = (
tickets_data.get("tickets", tickets_data)
if isinstance(tickets_data, dict)
else tickets_data
)
for t in tickets:
ref = t.get("reference")
slug = t.get("slug")
t_id = t.get("id")
first = t.get("first_name") or ""
last = t.get("last_name") or ""
name = f"{first} {last}".strip() or "Unknown Guest"
if slug and ref and t_id:
# Create our single Ticket object
ticket = Ticket(slug=slug, reference=ref, t_id=t_id, name=name)
# Store a reference to it in both dictionaries
self.tickets_by_slug[slug] = ticket
self.tickets_by_id[t_id] = ticket
print(f"Loaded {len(self.tickets_by_slug)} valid tickets.")
except requests.RequestException as e:
print(f"Failed to fetch tickets: {e}")
sys.exit(1)
# 2. Fetch existing check-ins so we don't lose state if the app restarts
try:
checkins_response = requests.get(f"{BASE_URL}/checkins", headers=HEADERS)
checkins_response.raise_for_status()
checkins = checkins_response.json()
for checkin in checkins:
if not checkin.get("deleted_at"):
t_id = checkin.get("ticket_id")
c_uuid = checkin.get("uuid")
# If we find a valid check-in, update the Ticket object
if t_id and c_uuid and t_id in self.tickets_by_id:
self.tickets_by_id[t_id].checkin_uuid = c_uuid
checked_in_count = sum(1 for t in self.tickets_by_slug.values() if t.is_checked_in)
print(f"Synced {checked_in_count} existing check-ins.")
except requests.RequestException as e:
print(f"Failed to fetch existing check-ins: {e}")
sys.exit(1)
def process_qr_code(self, qr_data: str) -> str:
"""Logic to check user in or out using the Tito API."""
if qr_data not in self.tickets_by_slug:
return f"INVALID TICKET: {qr_data}"
ticket = self.tickets_by_slug[qr_data]
if ticket.is_checked_in:
# Attendee is inside, so we CHECK OUT (Delete Check-in)
url = f"{BASE_URL}/checkins/{ticket.checkin_uuid}"
try:
response = requests.delete(url, headers=HEADERS)
response.raise_for_status()
ticket.checkin_uuid = None # Clear the UUID locally
status = "CHECKED OUT"
except requests.RequestException as e:
print(f"API Error during Check-out: {e}")
return "API ERROR"
else:
# Attendee is outside, so we CHECK IN (Create Check-in)
url = f"{BASE_URL}/checkins"
payload = {"checkin": {"ticket_reference": ticket.reference}}
try:
response = requests.post(url, headers=HEADERS, json=payload)
response.raise_for_status()
# Save the new checkin UUID to the Ticket object
data = response.json()
ticket.checkin_uuid = data.get("uuid")
status = "CHECKED IN"
except requests.RequestException as e:
error_details = (
e.response.text if e.response is not None else "No response"
)
print(f"API Error during Check-in: {e}\nTito says: {error_details}")
return "API ERROR"
checked_in_count = sum(1 for t in self.tickets_by_slug.values() if t.is_checked_in)
print(f"[{status}] {ticket.name} ({ticket.reference}) - Total inside: {checked_in_count}")
return f"{status}: {ticket.name}"
def main() -> None:
tracker = AttendeeTracker()
tracker.initialize_data()
print("Starting Camera... Press 'q' to quit.")
cap = cv2.VideoCapture(0)
if not cap.isOpened():
print("Error: Could not open video device.")
return
freeze_until = 0.0
frozen_frame = None
freeze_duration = 3.0
while True:
# ALWAYS read the camera so the hardware buffer doesn't lag
ret, frame = cap.read()
if not ret:
break
if cv2.waitKey(1) & 0xFF == ord("q"):
break
current_time = time.time()
if current_time < freeze_until and frozen_frame is not None:
cv2.imshow("Tito Live Check-in Scanner", frozen_frame)
continue
decoded_objects = decode(frame)
for obj in decoded_objects:
qr_data = obj.data.decode("utf-8")
# If enough time has passed since the last scan
if current_time - tracker.last_scan_time < tracker.scan_cooldown:
continue
message = tracker.process_qr_code(qr_data)
tracker.last_scan_time = current_time
# 1. Draw the bounding box
points = obj.polygon
if len(points) == 4:
for i in range(4):
cv2.line(frame, points[i], points[(i + 1) % 4], (255, 0, 0), 3)
# 2. Draw the background and text
color = (
(0, 0, 255) if "OUT" in message or "ERROR" in message else (0, 255, 0)
)
(text_w, text_h), _ = cv2.getTextSize(
message, cv2.FONT_HERSHEY_SIMPLEX, 0.8, 2
)
cv2.rectangle(frame, (25, 25), (35 + text_w, 60), (0, 0, 0), -1)
cv2.putText(
frame, message, (30, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2
)
# 3. Take a snapshot and trigger the freeze
frozen_frame = frame.copy()
freeze_until = current_time + freeze_duration
break # Stop processing other QRs in this frame
# Show the live frame
if current_time >= freeze_until:
cv2.imshow("Tito Live Check-in Scanner", frame)
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
main()