Selfie Clock-In for Field Workers: Face Verification Time Clock in Python
Construction crews, cleaning teams, home care workers and security guards rarely start their day in front of a shared time clock. They start at a job site, and they clock in from a phone. A selfie clock-in solves the two
Construction crews, cleaning teams, home care workers and security guards rarely start their day in front of a shared time clock. They start at a job site, and they clock in from a phone. A selfie clock-in solves the two problems a plain mobile time clock cannot: was the employee really on site, and was it really them? This tutorial builds one in Python: each punch is accepted only if the selfie matches the employee's profile photo and the GPS position is inside the job site.
We tested the code on seven punches over two days for two employees. To keep everything public, the "employees" are NASA astronauts Jessica Meir and Christina Koch: their official portraits are the profile photos, and photos taken aboard the International Space Station play the selfies. ESA astronaut Sophie Adenot plays a coworker who tries to clock in for someone else. All photos are public domain.
Want to build it? Get a key for the Face Analyzer API.
How the selfie clock-in works
Every punch goes through three checks, from the cheapest to the most expensive:
- Geofence: the GPS position must be within the radius of the employee's job site. Pure math, no API call.
- Replay check: the photo must never have been used for an accepted punch. A hash of the file catches an old selfie sent again.
-
Face check: one call to
/compare-faceswith the profile photo as the source and the selfie as the target. The punch is accepted only if the selfie has exactly one face and it matches.
Because the employee is logged into the app, you already know who should be in the selfie, so a one to one comparison is enough: no face database, one API call per punch. Shared kiosks that must recognize anyone are covered in our face recognition attendance system tutorial.
Results on seven punches
- Clocked out from the parking lot: a punch from 2.3 km away was rejected without calling the API. Twelve minutes later, on site, it went through.
- Two people in the selfie: rejected, retake alone.
- Same photo sent twice: the clock-out reused the morning selfie, so the hash matched and it was rejected.
- Buddy punching: a coworker tried to clock Christina in with her own selfie. The face did not match, so the punch was rejected.
Build the clock-in check in Python
You need Python 3 with requests and a RapidAPI key in RAPIDAPI_KEY. Put each employee's profile photo in a profiles folder and save this as clock_in.py:
import csv
import hashlib
import math
import os
from datetime import datetime
import requests
HOST = "faceanalyzer-ai.p.rapidapi.com"
HEADERS = {"x-rapidapi-host": HOST, "x-rapidapi-key": os.environ["RAPIDAPI_KEY"]}
WORKERS = {
"W-101": {"name": "Jessica Meir", "photo": "profiles/meir.jpg", "site": "north-yard"},
"W-102": {"name": "Christina Koch", "photo": "profiles/koch.jpg", "site": "north-yard"},
}
SITES = { # latitude, longitude, radius in meters
"north-yard": (29.5593, -95.0900, 150),
}
LOG = "punches.csv"
FIELDS = ["time", "worker", "kind", "status", "reason", "distance_m", "photo_sha256"]
def distance_m(lat1, lon1, lat2, lon2):
"""Haversine distance between two GPS points, in meters."""
p1, p2 = math.radians(lat1), math.radians(lat2)
dp, dl = p2 - p1, math.radians(lon2 - lon1)
a = math.sin(dp / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2
return 6371000 * 2 * math.asin(math.sqrt(a))
def compare(profile_path, selfie_path):
with open(profile_path, "rb") as a, open(selfie_path, "rb") as b:
r = requests.post(f"https://{HOST}/compare-faces", headers=HEADERS,
files={"source_image": a, "target_image": b}, timeout=30)
r.raise_for_status()
return r.json()["body"]
def used_photos():
if not os.path.exists(LOG):
return set()
with open(LOG) as f:
return {row["photo_sha256"] for row in csv.DictReader(f) if row["status"] == "accepted"}
def decide(worker_id, selfie_path, lat, lon):
worker = WORKERS[worker_id]
site_lat, site_lon, radius = SITES[worker["site"]]
dist = round(distance_m(lat, lon, site_lat, site_lon))
if dist > radius:
return "rejected", f"{dist} m from {worker['site']}", dist, ""
with open(selfie_path, "rb") as f:
sha = hashlib.sha256(f.read()).hexdigest()
if sha in used_photos():
return "rejected", "photo already used for a punch", dist, sha
body = compare(worker["photo"], selfie_path)
faces = len(body["matchedFaces"]) + len(body["unmatchedFaces"])
if faces == 0:
return "rejected", "no face in the selfie", dist, sha
if faces > 1:
return "rejected", f"{faces} faces, retake alone", dist, sha
if not body["matchedFaces"]:
return "rejected", f"face does not match {worker['name']}", dist, sha
return "accepted", "face match, on site", dist, sha
def clock(worker_id, kind, selfie_path, lat, lon, when=None):
when = when or datetime.now().isoformat(timespec="minutes")
status, reason, dist, sha = decide(worker_id, selfie_path, lat, lon)
new_file = not os.path.exists(LOG)
with open(LOG, "a", newline="") as f:
writer = csv.DictWriter(f, fieldnames=FIELDS)
if new_file:
writer.writeheader()
writer.writerow({"time": when, "worker": worker_id, "kind": kind, "status": status,
"reason": reason, "distance_m": dist, "photo_sha256": sha})
return status, reason
- Every attempt is logged, accepted or not: rejected punches are the evidence a supervisor needs in a dispute.
- The geofence runs first, so a punch from the wrong place costs nothing.
-
One call gives two answers:
/compare-facessplits the selfie's faces intomatchedFacesandunmatchedFaces, which tells you how many people are in the photo and whether the employee is one of them.
Run a test week
This replays the seven punches. In a real app the time comes from the server clock, not from the phone:
import time
from clock_in import clock
SITE = (29.5594, -95.0899) # inside the north yard
PARKING = (29.5401, -95.0812) # about 2.3 km away
punches = [
("2026-11-16T07:58", "W-101", "in", "selfies/meir_mon_in.jpg", SITE),
("2026-11-16T08:03", "W-102", "in", "selfies/koch_mon_in.jpg", SITE),
("2026-11-16T16:20", "W-101", "out", "selfies/meir_mon_out.jpg", PARKING),
("2026-11-16T16:32", "W-101", "out", "selfies/meir_mon_out.jpg", SITE),
("2026-11-16T17:05", "W-102", "out", "selfies/two_people.jpg", SITE),
("2026-11-16T17:07", "W-102", "out", "selfies/koch_mon_in.jpg", SITE),
("2026-11-17T07:51", "W-102", "in", "selfies/adenot_as_koch.jpg", SITE),
]
for when, worker, kind, selfie, (lat, lon) in punches:
start = time.time()
status, reason = clock(worker, kind, selfie, lat, lon, when)
print(f"{when} {worker} {kind:<3} {status:<8} {reason} ({time.time() - start:.1f} s)")
2026-11-16T07:58 W-101 in accepted face match, on site (0.6 s)
2026-11-16T08:03 W-102 in accepted face match, on site (0.4 s)
2026-11-16T16:20 W-101 out rejected 2298 m from north-yard (0.0 s)
2026-11-16T16:32 W-101 out accepted face match, on site (0.6 s)
2026-11-16T17:05 W-102 out rejected 2 faces, retake alone (0.6 s)
2026-11-16T17:07 W-102 out rejected photo already used for a punch (0.0 s)
2026-11-17T07:51 W-102 in rejected face does not match Christina Koch (0.7 s)
Each face check took 0.4 to 0.7 seconds. The two rejections at 0.0 seconds never reached the API.
Receive punches from the mobile app
This Flask endpoint wraps clock() and returns 200 for an accepted punch and 422 for a rejected one:
import os
import tempfile
from flask import Flask, jsonify, request
from clock_in import WORKERS, clock
app = Flask(__name__)
@app.post("/punch")
def punch():
worker_id = request.form["worker_id"]
if worker_id not in WORKERS:
return jsonify(error="unknown worker"), 404
with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as tmp:
request.files["selfie"].save(tmp)
try:
status, reason = clock(worker_id, request.form["kind"], tmp.name,
float(request.form["lat"]), float(request.form["lon"]))
finally:
os.remove(tmp.name)
return jsonify(status=status, reason=reason), 200 if status == "accepted" else 422
if __name__ == "__main__":
app.run(port=5000)
curl -X POST http://127.0.0.1:5000/punch \
-F worker_id=W-101 -F kind=in \
-F lat=29.5594 -F lon=-95.0899 \
-F selfie=@selfies/meir_mon_in.jpg
{"reason":"face match, on site","status":"accepted"}
Turn punches into a timesheet
This pairs the accepted clock-in and clock-out of each employee per day, computes the hours and flags the days a supervisor must review:
import csv
from collections import defaultdict
from datetime import datetime
from clock_in import LOG, WORKERS
days = defaultdict(lambda: {"in": None, "out": None, "rejected": []})
with open(LOG) as f:
for row in csv.DictReader(f):
when = datetime.fromisoformat(row["time"])
day = days[(row["worker"], when.date())]
if row["status"] == "accepted":
day[row["kind"]] = when
else:
day["rejected"].append(f"{when:%H:%M} {row['reason']}")
rows = []
for (worker, date), day in sorted(days.items()):
hours, flag = "", ""
if day["in"] and day["out"]:
hours = f"{(day['out'] - day['in']).total_seconds() / 3600:.2f}"
elif day["in"]:
flag = "missing clock-out"
else:
flag = "no accepted clock-in"
if day["rejected"]:
flag = "; ".join(filter(None, [flag, f"{len(day['rejected'])} rejected"]))
rows.append({
"date": date, "worker": worker, "name": WORKERS[worker]["name"],
"in": f"{day['in']:%H:%M}" if day["in"] else "",
"out": f"{day['out']:%H:%M}" if day["out"] else "",
"hours": hours, "review": flag, "rejected_punches": " | ".join(day["rejected"]),
})
with open("timesheet.csv", "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=rows[0].keys())
writer.writeheader()
writer.writerows(rows)
for r in rows:
print(f"{r['date']} {r['name']:<15} {r['in']:>5} {r['out']:>5} {r['hours']:>5} {r['review']}")
2026-11-16 Jessica Meir 07:58 16:32 8.57 1 rejected
2026-11-16 Christina Koch 08:03 missing clock-out; 2 rejected
2026-11-17 Christina Koch no accepted clock-in; 1 rejected
Production tips
- Enroll a clear profile photo at hiring, facing the camera, in good light.
- Add a liveness step in the app: a blink or a head turn before the photo, so a printed picture cannot be used.
- Use the server clock and keep the log append only.
- Set the radius per site: 150 meters suits a yard; large sites need more, and GPS is less precise indoors.
- Tell employees what is checked, get consent where the law requires it, and define how long photos are kept.
- Route flags to people: a rejected punch is a question for a supervisor, not a sanction.
Full tutorial with images: Selfie Clock-In for Field Workers on ai-engine.net.
Try it with your own photos: grab a key from the Face Analyzer API page and run
clock_in.py.
Photos: NASA (public domain), from images.nasa.gov: NHQ202009150005, NHQ202009160004, iss074e0832627, iss074e0832632, iss061e068306, iss074e0437872.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.
