From 9bdea892786d8e610fb48615e1bd597a8c5cd8da Mon Sep 17 00:00:00 2001 From: Meghdad <61308304+MeghdadFadaee@users.noreply.github.com> Date: Sun, 26 Jul 2026 20:03:38 +0330 Subject: [PATCH] feat: optimize mobile OCR verification workflow --- .gitignore | 1 + README.md | 5 + tests/test_tools.py | 54 ++++++- web/index.php | 370 +++++++++++++++++++++++++++++++++++++++++--- 4 files changed, 398 insertions(+), 32 deletions(-) diff --git a/.gitignore b/.gitignore index 2ddffcd..cb787d9 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,4 @@ build/ *.egg-info/ captcha.jpg dataset/ +screenshots/ diff --git a/README.md b/README.md index 5d4c43f..b02314a 100644 --- a/README.md +++ b/README.md @@ -123,6 +123,11 @@ Arabic digits are accepted and normalized to ASCII. Enter saves and advances; an empty Enter or **Skip for now** leaves the row unverified and advances. Recent labels can be opened and corrected without moving the main queue. +On phones, focusing the number field switches to a compact entry layout that +keeps the captcha, input, and Next button above the software keyboard. Save and +skip requests update the next image in place, so the page does not reload and +the numeric keyboard stays open between labels. + The page deliberately does not rewrite the large CSV after every answer. The header shows how many rows have not yet been copied back. Click **Sync labels.csv** before training, copying the dataset, or using another Python tool. diff --git a/tests/test_tools.py b/tests/test_tools.py index 8d4d06c..add8e20 100644 --- a/tests/test_tools.py +++ b/tests/test_tools.py @@ -3,6 +3,7 @@ from __future__ import annotations import base64 import csv import hashlib +import json import os import re import shutil @@ -275,9 +276,15 @@ class ToolTests(unittest.TestCase): with urllib.request.urlopen(request, timeout=10) as response: return response.status, response.read(), dict(response.headers) - def post(values: dict[str, str]) -> tuple[int, bytes, dict[str, str]]: + def post( + values: dict[str, str], + *, + accept_json: bool = False, + ) -> tuple[int, bytes, dict[str, str]]: body = urllib.parse.urlencode(values).encode() request = urllib.request.Request(base_url, data=body, method="POST") + if accept_json: + request.add_header("Accept", "application/json") with urllib.request.urlopen(request, timeout=20) as response: return response.status, response.read(), dict(response.headers) @@ -301,6 +308,22 @@ class ToolTests(unittest.TestCase): self.assertIn(b'OCR verifier', page) self.assertRegex(page, rb'name="row_id" value="1"') self.assertRegex(page, rb'name="revision" value="0"') + self.assertIn(b'enterkeyhint="go"', page) + self.assertIn(b'id="mobile-counts"', page) + node = shutil.which("node") + if node is not None: + scripts = re.findall(rb"", page, re.DOTALL) + fast_entry_script = next( + script for script in scripts if b"submitFast" in script + ) + script_path = root / "fast-entry.js" + script_path.write_bytes(fast_entry_script) + syntax = subprocess.run( + [node, "--check", str(script_path)], + text=True, + capture_output=True, + ) + self.assertEqual(syntax.returncode, 0, syntax.stderr) status, image_body, headers = get("?action=image&id=1") self.assertEqual(status, 200) @@ -321,16 +344,26 @@ class ToolTests(unittest.TestCase): self.assertIn(b"Enter digits only", invalid.exception.read()) invalid.exception.close() - _, page, _ = post( + status, payload, headers = post( { "action": "save", "row_id": "1", "revision": "0", "mode": "queue", "label": "۱۲۳۴", - } + }, + accept_json=True, ) - self.assertIn(b"Label saved", page) + self.assertEqual(status, 200) + self.assertTrue(headers["Content-Type"].startswith("application/json")) + saved_payload = json.loads(payload) + self.assertEqual(saved_payload["status"], "saved") + self.assertEqual(saved_payload["revision"], 1) + self.assertEqual(saved_payload["row"]["id"], 2) + self.assertEqual(saved_payload["stats"]["verified"], 2) + self.assertEqual(saved_payload["stats"]["pending"], 1) + + _, page, _ = get() self.assertRegex(page, rb'name="row_id" value="2"') self.assertRegex(page, rb'name="revision" value="1"') @@ -353,14 +386,21 @@ class ToolTests(unittest.TestCase): self.assertEqual(escaped_image.exception.code, 404) escaped_image.exception.close() - _, page, _ = post( + status, payload, _ = post( { "action": "skip", "row_id": "2", "revision": "1", - } + }, + accept_json=True, ) - self.assertIn(b"Image skipped", page) + self.assertEqual(status, 200) + skipped_payload = json.loads(payload) + self.assertEqual(skipped_payload["status"], "skipped") + self.assertEqual(skipped_payload["revision"], 2) + self.assertEqual(skipped_payload["row"]["id"], 2) + + _, page, _ = get() self.assertRegex(page, rb'name="row_id" value="2"') _, edit_page, _ = get("?edit=1") diff --git a/web/index.php b/web/index.php index 13989ae..8eb24a7 100644 --- a/web/index.php +++ b/web/index.php @@ -60,6 +60,14 @@ function requestAction(): string return (string) ($_POST['action'] ?? $_GET['action'] ?? ''); } +function wantsJson(): bool +{ + return str_contains( + strtolower((string) ($_SERVER['HTTP_ACCEPT'] ?? '')), + 'application/json', + ); +} + function sourceStats(string $path): array { clearstatcache(true, $path); @@ -733,6 +741,41 @@ function recentRows(PDO $db): array )->fetchAll(); } +function verifierSnapshot(array $config, string $status): array +{ + $db = openDatabase($config); + requireReady($db); + verifySourceUnchanged($db, $config); + + $row = currentRow($db); + $total = (int) metadata($db, 'total_count', '0'); + $verified = (int) metadata($db, 'verified_count', '0'); + $pending = (int) metadata($db, 'pending_count', '0'); + $next = $row === null ? null : nextRowAfter($db, (int) $row['id']); + + return [ + 'status' => $status, + 'revision' => (int) metadata($db, 'revision', '0'), + 'row' => $row === null ? null : [ + 'id' => (int) $row['id'], + 'number' => (int) $row['id'] + 1, + 'filename' => $row['filename'], + 'label' => $row['label'], + 'image_url' => '?action=image&id=' . (int) $row['id'], + ], + 'stats' => [ + 'total' => $total, + 'verified' => $verified, + 'remaining' => max(0, $total - $verified), + 'pending' => $pending, + 'progress' => $total > 0 ? $verified * 100 / $total : 100, + ], + 'next_image_url' => $next === null + ? null + : '?action=image&id=' . (int) $next['id'], + ]; +} + function renderHeader(string $title): void { ?> @@ -763,6 +806,7 @@ function renderHeader(string $title): void html { min-height: 100%; background: #101114; } body { min-height: 100vh; + min-height: 100dvh; margin: 0; color: var(--ink); font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; @@ -831,6 +875,7 @@ function renderHeader(string $title): void .workspace { display: grid; grid-template-columns: minmax(0, 1fr) 270px; gap: .8rem; } .verify-card { min-height: 460px; padding: clamp(1.2rem, 4vw, 2.2rem); display: flex; flex-direction: column; } .card-meta { display: flex; align-items: center; justify-content: space-between; gap: 1rem; color: var(--muted); font-size: .82rem; } + .mobile-counts, .mobile-label { display: none; } .filename { max-width: 70%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-family: ui-monospace, monospace; } .image-stage { flex: 1; min-height: 190px; display: grid; place-items: center; margin: 1.25rem 0; @@ -869,21 +914,119 @@ function renderHeader(string $title): void .sync button { width: 100%; } .notice { margin-bottom: .8rem; padding: .85rem 1rem; border: 1px solid rgba(131,219,181,.25); border-radius: .85rem; color: var(--success); background: rgba(131,219,181,.07); } .notice.error { color: var(--danger); border-color: rgba(255,141,145,.25); background: rgba(255,141,145,.07); } + .fast-toast { + position: fixed; + z-index: 20; + top: max(.65rem, env(safe-area-inset-top)); + left: 50%; + max-width: min(92vw, 30rem); + padding: .65rem .9rem; + border: 1px solid rgba(131,219,181,.32); + border-radius: 999px; + color: var(--success); + background: rgba(20, 28, 25, .96); + box-shadow: 0 14px 38px rgba(0,0,0,.35); + font-size: .82rem; + font-weight: 750; + opacity: 0; + pointer-events: none; + transform: translate(-50%, -1rem); + transition: opacity .16s ease, transform .16s ease; + } + .fast-toast.visible { opacity: 1; transform: translate(-50%, 0); } + .fast-toast.error { + color: var(--danger); + border-color: rgba(255,141,145,.32); + background: rgba(35, 22, 24, .97); + } .complete { min-height: 460px; display: grid; place-items: center; padding: 2rem; text-align: center; } .complete-mark { margin: 0 auto 1rem; display: grid; place-items: center; width: 4rem; height: 4rem; border-radius: 50%; color: #102018; background: var(--success); font-size: 2rem; font-weight: 900; } .error-details { overflow-wrap: anywhere; color: var(--danger); } .visually-hidden { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0,0,0,0); white-space: nowrap; border: 0; } @media (max-width: 760px) { - .shell { width: min(100% - 1rem, 680px); padding-top: 1rem; } - .workspace { grid-template-columns: 1fr; } - .stats { gap: .45rem; } - .stat { padding: .8rem; } - .stat-value { font-size: 1.1rem; } - .label-form { grid-template-columns: 1fr; } - .label-form button { width: 100%; } - .sidebar { order: 2; } - .image-stage { min-height: 160px; } - .topbar { margin-bottom: 1rem; } + body { min-height: 100dvh; } + .shell { + width: min(100% - .7rem, 680px); + padding: .45rem 0 max(1rem, env(safe-area-inset-bottom)); + } + .topbar { + min-height: 2.35rem; + margin-bottom: .4rem; + padding: 0 .25rem; + } + .brand { gap: .5rem; font-size: .9rem; } + .brand-mark { width: .55rem; height: .55rem; } + .topbar .pill { padding: .3rem .55rem; font-size: .68rem; } + body.entry-focused .topbar { display: none; } + .stats, .progress-panel { display: none; } + .workspace { grid-template-columns: 1fr; gap: .45rem; } + .verify-card { + min-height: 0; + max-height: calc(var(--visual-height, 100dvh) - .7rem); + padding: .65rem; + border-radius: 1rem; + overflow-y: auto; + scroll-margin-top: .35rem; + } + .card-meta { min-height: 1.6rem; gap: .5rem; font-size: .76rem; } + .filename { display: none; } + .mobile-counts { display: inline; margin-left: auto; font-variant-numeric: tabular-nums; } + .image-stage { + flex: none; + min-height: 0; + height: clamp(88px, 22svh, 132px); + margin: .45rem 0; + border-radius: .75rem; + } + .image-stage img { width: min(96%, 612px); max-height: 100%; object-fit: contain; } + .label-form { + grid-template-columns: minmax(0, 1fr) auto; + gap: .4rem; + } + .label-input { + min-height: 3.2rem; + padding: .55rem .75rem; + border-radius: .75rem; + font-size: 1.35rem; + } + .label-form button { + min-width: 4.7rem; + min-height: 3.2rem; + width: auto; + padding: .55rem .7rem; + border-radius: .75rem; + } + .desktop-label { display: none; } + .mobile-label { display: inline; } + .secondary-actions { min-height: 2.5rem; margin-top: .4rem; } + .secondary-actions button, .secondary-actions .button { + min-height: 2.35rem; + padding: .4rem .75rem; + font-size: .78rem; + } + .secondary-actions .hint { display: none; } + .sidebar { + order: 2; + padding: .55rem; + border-radius: .9rem; + box-shadow: none; + } + .sidebar-head, .recent-list, .sidebar > .hint { display: none; } + .sync { margin: 0; padding: 0; border: 0; } + .sync button { min-height: 2.5rem; padding: .45rem .75rem; font-size: .78rem; } + .sync .hint { display: none; } + .notice { + position: fixed; + z-index: 19; + top: max(.55rem, env(safe-area-inset-top)); + left: .55rem; + right: .55rem; + margin: 0; + padding: .65rem .8rem; + box-shadow: 0 14px 38px rgba(0,0,0,.35); + } + body.entry-focused .sidebar { display: none; } + body.entry-focused .verify-card { border-color: rgba(255, 204, 102, .18); } } @media (prefers-reduced-motion: reduce) { *, *::before, *::after { scroll-behavior: auto !important; transition: none !important; } @@ -1058,36 +1201,37 @@ function renderVerifier(array $config, ?string $error = null): never
OCR verifier
- 0 ? number_format($pending) . ' unsynced' : 'CSV up to date' ?> + 0 ? number_format($pending) . ' unsynced' : 'CSV up to date' ?>
+
-
+
-
+
Verified
-
+
Remaining
-
+
Complete
-
%
+
%
- of - pending CSV sync + of + pending CSV sync
-
+
@@ -1103,11 +1247,13 @@ function renderVerifier(array $config, ?string $error = null): never
- - + + done · left +
Number image for row <?= (int) $row['id'] + 1 ?> - +
@@ -1173,7 +1327,7 @@ function renderVerifier(array $config, ?string $error = null): never
-
@@ -1190,10 +1344,133 @@ function renderVerifier(array $config, ?string $error = null): never const skip = document.querySelector('#skip-form'); if (!input || !form) return; + const card = document.querySelector('.verify-card'); + const image = document.querySelector('#captcha-image'); + const saveButton = document.querySelector('#save-button'); + const mobile = window.matchMedia('(max-width: 760px)'); + const queueMode = form.elements.mode?.value === 'queue'; + const formatter = new Intl.NumberFormat(); + const toast = document.querySelector('#fast-toast'); + let busy = false; + let toastTimer; + let viewportTimer; + const digitMap = { '۰':'0','۱':'1','۲':'2','۳':'3','۴':'4','۵':'5','۶':'6','۷':'7','۸':'8','۹':'9', '٠':'0','١':'1','٢':'2','٣':'3','٤':'4','٥':'5','٦':'6','٧':'7','٨':'8','٩':'9' }; + + const fastEntryEnabled = () => mobile.matches && queueMode && skip; + const setText = (selector, value) => { + const element = document.querySelector(selector); + if (element) element.textContent = value; + }; + const showToast = (message, isError = false) => { + if (!toast) return; + window.clearTimeout(toastTimer); + toast.textContent = message; + toast.classList.toggle('error', isError); + toast.classList.add('visible'); + toastTimer = window.setTimeout( + () => toast.classList.remove('visible'), + isError ? 2600 : 650 + ); + }; + const updateViewport = () => { + const viewport = window.visualViewport; + const height = viewport ? viewport.height : window.innerHeight; + document.documentElement.style.setProperty('--visual-height', `${height}px`); + if (mobile.matches && document.activeElement === input && card) { + window.clearTimeout(viewportTimer); + viewportTimer = window.setTimeout( + () => card.scrollIntoView({block: 'start', behavior: 'auto'}), + 40 + ); + } + }; + const focusEntry = () => { + if (!mobile.matches) return; + document.body.classList.add('entry-focused'); + updateViewport(); + window.setTimeout(updateViewport, 180); + }; + const updateSnapshot = payload => { + if (!payload.row) { + window.location.reload(); + return; + } + + const {row, stats, revision} = payload; + document.querySelectorAll('input[name="row_id"]').forEach( + element => element.value = row.id + ); + document.querySelectorAll('input[name="revision"]').forEach( + element => element.value = revision + ); + setText('#row-position', `Row ${formatter.format(row.number)}`); + setText('#mobile-counts', `${formatter.format(stats.verified)} done · ${formatter.format(stats.remaining)} left`); + setText('#current-filename', row.filename); + const filename = document.querySelector('#current-filename'); + if (filename) filename.title = row.filename; + + setText('#verified-count', formatter.format(stats.verified)); + setText('#remaining-count', formatter.format(stats.remaining)); + setText('#complete-count', `${stats.progress.toFixed(2)}%`); + setText('#progress-summary', `${formatter.format(stats.verified)} of ${formatter.format(stats.total)}`); + setText('#pending-summary', `${formatter.format(stats.pending)} pending CSV sync`); + setText('#sync-pill', stats.pending > 0 ? `${formatter.format(stats.pending)} unsynced` : 'CSV up to date'); + const progress = document.querySelector('#main-progress'); + if (progress) progress.style.width = `${Math.min(100, stats.progress)}%`; + const syncButton = document.querySelector('#sync-button'); + if (syncButton) syncButton.disabled = stats.pending === 0; + + image.src = row.image_url; + image.alt = `Number image for row ${row.number}`; + input.value = row.label || ''; + input.focus({preventScroll: true}); + input.select(); + focusEntry(); + + if (payload.next_image_url) { + const preload = new Image(); + preload.src = payload.next_image_url; + } + }; + const submitFast = async targetForm => { + if (busy) return; + busy = true; + saveButton.disabled = true; + try { + const response = await fetch('./', { + method: 'POST', + body: new FormData(targetForm), + headers: {'Accept': 'application/json'} + }); + let payload; + try { + payload = await response.json(); + } catch { + throw Object.assign(new Error('The server returned an invalid response.'), {status: response.status}); + } + if (!response.ok) { + throw Object.assign(new Error(payload.error || 'Could not save the label.'), {status: response.status}); + } + updateSnapshot(payload); + showToast(payload.status === 'skipped' ? 'Skipped' : 'Saved'); + } catch (problem) { + showToast(problem.message || 'Connection error. Reloading the queue…', true); + if (problem.status === 422) { + input.focus({preventScroll: true}); + input.select(); + } else { + window.setTimeout(() => window.location.reload(), 1200); + } + } finally { + busy = false; + saveButton.disabled = false; + } + }; + input.addEventListener('input', () => { input.value = Array.from(input.value, character => digitMap[character] ?? character) .join('') @@ -1203,10 +1480,47 @@ function renderVerifier(array $config, ?string $error = null): never if (input.value.trim() === '' && skip) { event.preventDefault(); skip.requestSubmit(); + return; + } + if (fastEntryEnabled()) { + event.preventDefault(); + submitFast(form); } }); + if (skip) { + skip.addEventListener('submit', event => { + if (!fastEntryEnabled()) return; + event.preventDefault(); + submitFast(skip); + }); + } + input.addEventListener('focus', focusEntry); + input.addEventListener('blur', () => { + window.setTimeout(() => { + if (!busy && document.activeElement !== input) { + document.body.classList.remove('entry-focused'); + } + }, 180); + }); + if (window.visualViewport) { + window.visualViewport.addEventListener('resize', updateViewport); + window.visualViewport.addEventListener('scroll', updateViewport); + } + mobile.addEventListener('change', () => { + if (!mobile.matches) { + document.body.classList.remove('entry-focused'); + document.documentElement.style.removeProperty('--visual-height'); + } + }); + + const pageNotice = document.querySelector('#page-notice:not(.error)'); + if (pageNotice && mobile.matches) { + window.setTimeout(() => pageNotice.hidden = true, 1400); + } + input.focus(); input.select(); + updateViewport(); $error->getMessage()], $error->status); } if ($action === 'image') { @@ -1289,7 +1609,7 @@ function handleRequest(): never renderSetup($config, $error->getMessage()); } catch (Throwable $error) { error_log((string) $error); - if ($action === 'initialize') { + if ($action === 'initialize' || wantsJson()) { jsonResponse(['error' => 'Unexpected initialization error. Check the PHP error log.'], 500); } http_response_code(500);