Noor-Khan's picture
Upload 8 files
93e5404 verified
Raw History Blame Contribute Delete
14 kB
"""Evaluate the touchless virtual keyboard — no webcam needed.
Runs three kinds of checks and writes metrics.json + sample renders:
1. Layout: every key inside the 1280x720 frame, no overlaps, all 35 keys
present with the sizes from main.py.
2. Typing simulation: KeyboardEngine driven with synthetic fingertip
positions at 30 fps — types "HI", then SPACE / BKSP / SHIFT / ENTER /
CLEAR, plus the negative controls (too-short hover, pinch too wide,
cooldown, no hand, fingertip off the keyboard).
3. Hand detection: MediaPipe HandLandmarker (the shipped
hand_landmarker.task) on two CC BY-SA 4.0 Wikimedia Commons palm
photos, with a blank-image and a random-noise control, and a missing
file control. Annotated copies of the photos are written to samples/.
Run: python3 evaluate.py
Needs: opencv-python, mediapipe, numpy (see requirements.txt). On Linux
MediaPipe's native library needs OpenGL ES (libGLESv2, e.g. libgles2).
"""
import hashlib
import json
import os
import sys
import time
import cv2
import numpy as np
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
def _resolve(*parts):
"""First existing candidate: <script-dir>/parts, then
<script-dir>/package/parts (work layout)."""
direct = os.path.join(HERE, *parts)
if os.path.exists(direct):
return direct
return os.path.join(HERE, "package", *parts)
def _samples_dir():
direct = os.path.join(HERE, "samples")
if os.path.isdir(direct):
return direct
return os.path.join(HERE, "package", "samples")
import virtual_keyboard as vk # noqa: E402
MODEL_PATH = _resolve("hand_landmarker.task")
SAMPLES = _samples_dir()
os.makedirs(SAMPLES, exist_ok=True)
FPS = 30
DT = 1.0 / FPS
HAND_CONNECTIONS = [
(0, 1), (1, 2), (2, 3), (3, 4),
(0, 5), (5, 6), (6, 7), (7, 8),
(5, 9), (9, 10), (10, 11), (11, 12),
(9, 13), (13, 14), (14, 15), (15, 16),
(13, 17), (17, 18), (18, 19), (19, 20),
(0, 17),
]
def check_layout():
buttons = vk.build_buttons()
expected = [k for row in vk.KEY_ROWS for k in row]
labels = [b.text for b in buttons]
inside = all(0 <= b.pos[0] and 0 <= b.pos[1]
and b.pos[0] + b.size[0] <= vk.FRAME_WIDTH
and b.pos[1] + b.size[1] <= vk.FRAME_HEIGHT for b in buttons)
overlaps = []
for i, a in enumerate(buttons):
for b in buttons[i + 1:]:
ax, ay = a.pos
aw, ah = a.size
bx, by = b.pos
bw, bh = b.size
if ax < bx + bw and bx < ax + aw and ay < by + bh and by < ay + ah:
overlaps.append((a.text, b.text))
sizes_ok = all(b.size == vk.KEY_SIZES.get(b.text, (85, 85)) for b in buttons)
result = {
"key_count": len(buttons),
"expected_key_count": len(expected),
"labels_match": labels == expected,
"all_inside_1280x720": inside,
"overlapping_pairs": overlaps,
"special_sizes_ok": sizes_ok,
}
assert len(buttons) == len(expected) and labels == expected
assert inside and not overlaps and sizes_ok
return result
def _press_key(engine, key, now, hover_frames=vk.HOVER_FRAMES_REQUIRED,
wait_for_cooldown=True):
"""Simulate: move index tip to key centre, hover, pinch, release.
Returns (now_after, pressed_key). ``now`` advances at 30 fps.
By default the simulated user waits out the click cooldown before
starting the next key; pass ``wait_for_cooldown=False`` to attempt
a press while the cooldown is still running.
"""
if wait_for_cooldown:
now = max(now, engine.last_press_time + engine.click_cooldown + DT)
centre = engine.key_center(key)
far = (centre[0] + 300, centre[1]) # thumb far away = no pinch
near = (centre[0] + 10, centre[1]) # thumb close = pinch (< 45 px)
last = None
for _ in range(hover_frames):
last = engine.step(centre, far, now)
now += DT
last = engine.step(centre, near, now) # pinch on the final hover frame
now += DT
engine.step(centre, far, now) # release the pinch
now += DT
return now, last["pressed_key"]
def check_typing():
engine = vk.KeyboardEngine()
now = 1000.0 # arbitrary start time; cooldown measured from here
engine.last_press_time = now - 10.0 # no cooldown pending at start
now, pressed = _press_key(engine, "H", now)
assert pressed == "H" and engine.final_text == "H", (pressed, engine.final_text)
now, pressed = _press_key(engine, "I", now)
assert pressed == "I" and engine.final_text == "HI", (pressed, engine.final_text)
now, pressed = _press_key(engine, "SPACE", now)
assert pressed == "SPACE" and engine.final_text == "HI "
now, pressed = _press_key(engine, "BKSP", now)
assert pressed == "BKSP" and engine.final_text == "HI"
now, pressed = _press_key(engine, "SHIFT", now)
assert pressed == "SHIFT" and engine.uppercase is False
now, pressed = _press_key(engine, "A", now)
assert pressed == "A" and engine.final_text == "HIa", engine.final_text
now, pressed = _press_key(engine, "ENTER", now)
assert pressed == "ENTER" and engine.final_text == "HIa\n"
now, pressed = _press_key(engine, "CLEAR", now)
assert pressed == "CLEAR" and engine.final_text == ""
# --- negative controls ------------------------------------------------
# (a) hover 5 frames (< 6 required) with a pinch on the 5th: no press.
e2 = vk.KeyboardEngine()
e2.last_press_time = now - 10.0
centre = e2.key_center("Q")
for _ in range(4):
e2.step(centre, (centre[0] + 300, centre[1]), now)
now += DT
r = e2.step(centre, (centre[0] + 10, centre[1]), now)
short_hover_pressed = r["pressed_key"]
assert short_hover_pressed is None and e2.final_text == ""
# (b) pinch distance 60 px (> 45) held for 8 frames: no press.
e3 = vk.KeyboardEngine()
e3.last_press_time = now - 10.0
centre = e3.key_center("Q")
r = None
for _ in range(8):
r = e3.step(centre, (centre[0] + 60, centre[1]), now)
now += DT
wide_pinch_pressed = r["pressed_key"]
assert wide_pinch_pressed is None and e3.final_text == ""
# (c) cooldown: press Q, then try again immediately: blocked; after
# 0.55 s the same key presses again.
e4 = vk.KeyboardEngine()
e4.last_press_time = now - 10.0
now, p1 = _press_key(e4, "Q", now)
assert p1 == "Q"
now2, p2 = _press_key(e4, "Q", now, wait_for_cooldown=False) # still inside the 0.55 s cooldown
cooldown_blocked = p2 is None and e4.final_text == "Q"
assert cooldown_blocked
now = now2 + 0.6 # wait past the cooldown
now, p3 = _press_key(e4, "Q", now)
assert p3 == "Q" and e4.final_text == "QQ"
# (d) fingertip off the keyboard: nothing selected, nothing pressed.
e5 = vk.KeyboardEngine()
r = e5.step((1250, 700), (1240, 700), now)
assert r["selected_key"] is None and r["pressed_key"] is None
# (e) no hand in frame: hover state resets.
e6 = vk.KeyboardEngine()
e6.step(e6.key_center("Q"), (999, 999), now)
e6.step(None, None, now)
assert e6.hover_key is None and e6.hover_frames == 0
# (f) apply_key caps text at MAX_TEXT_LENGTH.
text, _ = "", True
for _ in range(vk.MAX_TEXT_LENGTH + 5):
text, _ = vk.apply_key(text, "X", True)
assert len(text) == vk.MAX_TEXT_LENGTH
# (g) landmark_xy: normalised coords scale, pixel coords pass through.
lm = [[0.5, 0.5, 0.0]] * 21
assert vk.landmark_xy(lm, 0, (720, 1280, 3)) == (640, 360)
lm_px = [[640, 360, 0.0]] * 21
assert vk.landmark_xy(lm_px, 0, (720, 1280, 3)) == (640, 360)
return {
"typed_sequence": "H, I, SPACE, BKSP, SHIFT, A, ENTER, CLEAR -> ''",
"final_text_after_clear": engine.final_text,
"short_hover_5_frames_pressed": short_hover_pressed,
"wide_pinch_60px_pressed": wide_pinch_pressed,
"cooldown_second_press_blocked": cooldown_blocked,
"cooldown_press_after_wait": p3,
"off_keyboard_selected": None,
"no_hand_resets_hover": True,
"max_text_length_cap": len(text),
"landmark_xy_normalised_and_pixel_ok": True,
}
def annotate_hand(image_bgr, landmarks):
img = image_bgr.copy()
h, w = img.shape[:2]
pts = [(int(x * w), int(y * h)) for (x, y, _z) in landmarks]
for a, b in HAND_CONNECTIONS:
cv2.line(img, pts[a], pts[b], (0, 255, 0), 2)
for (x, y) in pts:
cv2.circle(img, (x, y), 4, (0, 0, 255), cv2.FILLED)
return img
def check_detection():
model_path = MODEL_PATH
with open(model_path, "rb") as fh:
model_sha256 = hashlib.sha256(fh.read()).hexdigest()
model_size = os.path.getsize(model_path)
photos = [
{"file": "palm_left.jpg",
"source": "Wikimedia Commons, File:Open Palm of the Left Hand, Fingers.jpg (CC BY-SA 4.0)",
"url": "https://commons.wikimedia.org/wiki/File:Open_Palm_of_the_Left_Hand,_Fingers.jpg"},
{"file": "palm_right.png",
"source": "Wikimedia Commons, File:Right Hand Palm.png (CC BY-SA 4.0)",
"url": "https://commons.wikimedia.org/wiki/File:Right_Hand_Palm.png"},
]
t0 = time.time()
detector = vk.HandDetector(model_path=model_path)
model_load_s = round(time.time() - t0, 2)
results = []
for photo in photos:
path = _resolve("samples", photo["file"])
image = cv2.imread(path)
assert image is not None, f"could not read {path}"
latencies = []
scores = []
hands = None
for _ in range(3):
t0 = time.time()
hands = detector.detect(image)
latencies.append(time.time() - t0)
scores.append(round(hands[0]["score"], 3) if hands else None)
assert len(hands) == 1, f"{photo['file']}: expected 1 hand, got {len(hands)}"
assert len(hands[0]["landmarks"]) == 21
annotated = annotate_hand(image, hands[0]["landmarks"])
out_name = photo["file"].rsplit(".", 1)[0] + "_annotated.jpg"
cv2.imwrite(os.path.join(SAMPLES, out_name), annotated)
# copy the original photo into samples/ too
cv2.imwrite(os.path.join(SAMPLES, photo["file"]), image)
results.append({
"file": photo["file"],
"image_shape": list(image.shape),
"hands_detected": len(hands),
"landmarks_per_hand": len(hands[0]["landmarks"]),
"handedness": hands[0]["handedness"],
"handedness_score": round(hands[0]["score"], 3),
"handedness_scores_over_3_runs": scores,
"detect_latency_s_mean_of_3": round(sum(latencies) / len(latencies), 3),
"source": photo["source"],
"source_url": photo["url"],
"annotated_sample": f"samples/{out_name}",
})
# controls: blank image -> 0 hands; random noise -> 0 hands
blank = np.zeros((720, 1280, 3), dtype=np.uint8)
blank_hands = detector.detect(blank)
rng = np.random.default_rng(42)
noise = rng.integers(0, 256, size=(720, 1280, 3), dtype=np.uint8)
noise_hands = detector.detect(noise)
detector.close()
# the one-shot convenience wrapper works too (fresh model load)
once = vk.detect_hands(cv2.imread(_resolve("samples", "palm_left.jpg")),
model_path=model_path)
assert len(once) == 1 and len(once[0]["landmarks"]) == 21
# missing model file -> FileNotFoundError
try:
vk.detect_hands(blank, model_path=os.path.join(
os.path.dirname(model_path), "no-such-model.task"))
missing_model_error = None
except FileNotFoundError as exc:
missing_model_error = str(exc)
return {
"model_file": "hand_landmarker.task",
"model_sha256": model_sha256,
"model_size_bytes": model_size,
"model_load_s": model_load_s,
"photos": results,
"blank_image_hands": len(blank_hands),
"random_noise_hands": len(noise_hands),
"one_shot_wrapper_hands": len(once),
"missing_model_file_error": missing_model_error,
}
def main():
import cv2 as _cv2 # noqa: F401 (versions recorded below)
import mediapipe
import numpy
metrics = {
"project": "touchless-virtual-keyboard",
"repo": "NoorullahZamindar-007/touchless-virtual-keyboard",
"evaluated": time.strftime("%Y-%m-%d"),
"environment": {
"python": sys.version.split()[0],
"opencv": cv2.__version__,
"mediapipe": mediapipe.__version__,
"numpy": numpy.__version__,
},
"layout": check_layout(),
"typing_simulation": check_typing(),
}
# keyboard render (no camera needed)
render_path = os.path.join(SAMPLES, "keyboard.png")
cv2.imwrite(render_path, vk.render_keyboard())
metrics["keyboard_render"] = "samples/keyboard.png"
metrics["hand_detection"] = check_detection()
# his original app at least imports (needs cvzone + a camera to run)
try:
import main as repo_main # noqa: F401 (work/ or script dir on path)
metrics["original_app_imports"] = True
except Exception as exc: # noqa: BLE001
metrics["original_app_imports"] = False
metrics["original_app_import_error"] = f"{type(exc).__name__}: {exc}"
with open(os.path.join(HERE, "metrics.json"), "w") as fh:
json.dump(metrics, fh, indent=2)
package_metrics = os.path.join(HERE, "package", "metrics.json")
if os.path.isdir(os.path.join(HERE, "package")):
with open(package_metrics, "w") as fh:
json.dump(metrics, fh, indent=2)
print(json.dumps(metrics, indent=2))
print("OK — metrics.json written (layout, typing simulation, hand detection)")
if __name__ == "__main__":
_work = os.path.join(HERE, "work") # dev layout: his original app lives here
if os.path.isdir(_work):
sys.path.insert(0, _work)
main()