diff --git a/README.md b/README.md index 3593e16..5d4c43f 100644 --- a/README.md +++ b/README.md @@ -100,3 +100,86 @@ Use `--reverify` to review them and `--start N` to begin after row `N`. The verifier builds a complete temporary CSV and atomically replaces the original when you quit, so the CSV cannot be left half-written. If it is interrupted while copying or displaying rather than at the prompt, the original CSV remains unchanged. + +## 5. Verify labels in a web browser + +The PHP verifier provides the same sequential labeling workflow without Kitty, +Python packages, Composer, or a framework. It requires PHP 8.1 or newer with +PDO SQLite and Fileinfo enabled. + +Start it locally from the repository root: + +```bash +php -S 127.0.0.1:8080 -t web +``` + +Then open `http://127.0.0.1:8080`. On the first visit, click **Initialize +verifier**. The browser incrementally imports `dataset/labels.csv` into +`dataset/verification.sqlite`; progress is resumable if the page or server is +stopped. + +Each accepted label is immediately committed to SQLite. ASCII, Persian, and +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. + +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. +Sync writes a complete neighboring temporary file and atomically replaces +`labels.csv`; a failed write leaves the existing CSV unchanged. + +Do not run `verify_labels.py`, the downloader, or another process that changes +`labels.csv` while the web verifier is active. The page detects an external CSV +change and stops rather than overwriting it. To move the dataset to another +machine, sync first and copy the dataset normally; the destination can rebuild +its SQLite state from the synced CSV. + +### Use another dataset directory + +The default dataset is the repository's `dataset/` directory. Set +`OCR_DATASET_DIR` to use another location: + +```bash +OCR_DATASET_DIR=/data/persian-ocr \ + php -S 127.0.0.1:8080 -t web +``` + +`OCR_STATE_PATH` can optionally place `verification.sqlite` elsewhere. The PHP +process must be able to read the CSV and images and write the SQLite database, +its lock/WAL files, and temporary CSV files. Grant the PHP-FPM user ownership or +a targeted ACL; do not make the directory world-writable. + +### Minimal Nginx configuration + +Use `web/` as the public document root so the CSV, SQLite state, images, and +Python source files are not directly downloadable. The page safely streams the +selected image itself. + +```nginx +server { + listen 80; + server_name verifier.example.internal; + root /srv/tci-ocr/web; + index index.php; + + location / { + try_files $uri /index.php?$query_string; + } + + location = /index.php { + include fastcgi_params; + fastcgi_param SCRIPT_FILENAME $document_root/index.php; + fastcgi_param OCR_DATASET_DIR /srv/tci-ocr/dataset; + fastcgi_pass unix:/run/php/php8.3-fpm.sock; + } + + location ~ \.php$ { + return 404; + } +} +``` + +Adjust the PHP-FPM socket and paths for the server. The application intentionally +contains no authentication; add Nginx basic authentication to the `server` or +`location /` block, or expose it only on a private network. diff --git a/tests/test_tools.py b/tests/test_tools.py index 6596a88..8d4d06c 100644 --- a/tests/test_tools.py +++ b/tests/test_tools.py @@ -1,12 +1,21 @@ from __future__ import annotations +import base64 import csv import hashlib import os +import re +import shutil +import socket +import sqlite3 import subprocess import sys import tempfile +import time import unittest +import urllib.error +import urllib.parse +import urllib.request from pathlib import Path @@ -194,6 +203,232 @@ class ToolTests(unittest.TestCase): self.assertTrue(original_one.is_file()) self.assertTrue(original_two.is_file()) + def test_php_web_verifier_initializes_saves_skips_edits_and_syncs(self): + php = shutil.which("php") + if php is None: + self.skipTest("PHP is not installed") + sqlite_support = subprocess.run( + [php, "-r", "exit(extension_loaded('pdo_sqlite') ? 0 : 1);"] + ) + if sqlite_support.returncode != 0: + self.skipTest("PHP PDO SQLite is not installed") + + with tempfile.TemporaryDirectory() as temp: + root = Path(temp) + dataset = root / "dataset" + image = dataset / "images" / "000000" / "000000000.png" + image.parent.mkdir(parents=True) + web_png = base64.b64decode( + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwC" + "AAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=" + ) + image.write_bytes(web_png) + outside_image = root / "outside.png" + outside_image.write_bytes(web_png) + csv_path = dataset / "labels.csv" + with csv_path.open("w", newline="", encoding="utf-8") as output: + writer = csv.DictWriter( + output, + fieldnames=["filename", "label", "batch_id", "verified", "hash"], + ) + writer.writeheader() + for index, (label, verified) in enumerate( + [("123", "1"), ("", "0"), ("", "0")] + ): + writer.writerow( + { + "filename": ( + "../outside.png" + if index == 2 + else image.relative_to(dataset).as_posix() + ), + "label": label, + "batch_id": "0", + "verified": verified, + "hash": hashlib.sha256(web_png + str(index).encode()).hexdigest(), + } + ) + + with socket.socket() as listener: + listener.bind(("127.0.0.1", 0)) + port = listener.getsockname()[1] + + environment = os.environ.copy() + environment["OCR_DATASET_DIR"] = str(dataset) + server = subprocess.Popen( + [ + php, + "-S", + f"127.0.0.1:{port}", + "-t", + str(PROJECT / "web"), + ], + stdout=subprocess.DEVNULL, + stderr=subprocess.PIPE, + text=True, + env=environment, + ) + base_url = f"http://127.0.0.1:{port}/" + + def get(path: str = "") -> tuple[int, bytes, dict[str, str]]: + request = urllib.request.Request(base_url + path) + 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]]: + body = urllib.parse.urlencode(values).encode() + request = urllib.request.Request(base_url, data=body, method="POST") + with urllib.request.urlopen(request, timeout=20) as response: + return response.status, response.read(), dict(response.headers) + + try: + for _ in range(50): + try: + status, page, _ = get() + if status == 200: + break + except urllib.error.URLError: + time.sleep(0.05) + else: + self.fail("PHP development server did not start") + + self.assertIn(b"Initialize verifier", page) + status, payload, _ = post({"action": "initialize"}) + self.assertEqual(status, 200) + self.assertIn(b'"done":true', payload) + + _, page, _ = get() + self.assertIn(b'OCR verifier', page) + self.assertRegex(page, rb'name="row_id" value="1"') + self.assertRegex(page, rb'name="revision" value="0"') + + status, image_body, headers = get("?action=image&id=1") + self.assertEqual(status, 200) + self.assertEqual(image_body, web_png) + self.assertEqual(headers["Content-Type"], "image/png") + + with self.assertRaises(urllib.error.HTTPError) as invalid: + post( + { + "action": "save", + "row_id": "1", + "revision": "0", + "mode": "queue", + "label": "12x", + } + ) + self.assertEqual(invalid.exception.code, 422) + self.assertIn(b"Enter digits only", invalid.exception.read()) + invalid.exception.close() + + _, page, _ = post( + { + "action": "save", + "row_id": "1", + "revision": "0", + "mode": "queue", + "label": "۱۲۳۴", + } + ) + self.assertIn(b"Label saved", page) + self.assertRegex(page, rb'name="row_id" value="2"') + self.assertRegex(page, rb'name="revision" value="1"') + + with self.assertRaises(urllib.error.HTTPError) as stale: + post( + { + "action": "save", + "row_id": "1", + "revision": "0", + "mode": "queue", + "label": "999", + } + ) + self.assertEqual(stale.exception.code, 409) + self.assertIn(b"stale", stale.exception.read()) + stale.exception.close() + + with self.assertRaises(urllib.error.HTTPError) as escaped_image: + get("?action=image&id=2") + self.assertEqual(escaped_image.exception.code, 404) + escaped_image.exception.close() + + _, page, _ = post( + { + "action": "skip", + "row_id": "2", + "revision": "1", + } + ) + self.assertIn(b"Image skipped", page) + self.assertRegex(page, rb'name="row_id" value="2"') + + _, edit_page, _ = get("?edit=1") + revision = re.search(rb'name="revision" value="(\d+)"', edit_page) + self.assertIsNotNone(revision) + _, corrected_page, _ = post( + { + "action": "save", + "row_id": "1", + "revision": revision.group(1).decode(), + "mode": "edit", + "label": "4567", + } + ) + self.assertIn(b"corrected", corrected_page) + + state = sqlite3.connect(dataset / "verification.sqlite") + try: + saved = state.execute( + "SELECT label, verified, dirty FROM labels WHERE id = 1" + ).fetchone() + pending = state.execute( + "SELECT value FROM metadata WHERE key = 'pending_count'" + ).fetchone() + finally: + state.close() + self.assertEqual(saved, ("4567", 1, 1)) + self.assertEqual(pending, ("1",)) + + _, synced_page, _ = post({"action": "sync"}) + self.assertIn(b"updated atomically", synced_page) + with csv_path.open(newline="", encoding="utf-8") as source: + rows = list(csv.DictReader(source)) + self.assertEqual(rows[1]["label"], "4567") + self.assertEqual(rows[1]["verified"], "1") + self.assertEqual(rows[2]["verified"], "0") + + state = sqlite3.connect(dataset / "verification.sqlite") + try: + pending = state.execute( + "SELECT value FROM metadata WHERE key = 'pending_count'" + ).fetchone() + finally: + state.close() + self.assertEqual(pending, ("0",)) + + with self.assertRaises(urllib.error.HTTPError) as missing: + get("?action=image&id=999") + self.assertEqual(missing.exception.code, 404) + missing.exception.close() + + with csv_path.open("a", encoding="utf-8") as output: + output.write("\n") + with self.assertRaises(urllib.error.HTTPError) as conflict: + get() + self.assertEqual(conflict.exception.code, 409) + self.assertIn(b"The source CSV changed", conflict.exception.read()) + conflict.exception.close() + finally: + server.terminate() + try: + server.wait(timeout=5) + except subprocess.TimeoutExpired: + server.kill() + server.wait(timeout=5) + if server.stderr is not None: + server.stderr.close() + if __name__ == "__main__": unittest.main() diff --git a/web/index.php b/web/index.php new file mode 100644 index 0000000..0ab76b5 --- /dev/null +++ b/web/index.php @@ -0,0 +1,1298 @@ + $dataset, + 'csv' => $dataset . DIRECTORY_SEPARATOR . 'labels.csv', + 'state' => $configuredState !== '' + ? $configuredState + : $dataset . DIRECTORY_SEPARATOR . 'verification.sqlite', + ]; +} + +function h(string|int|float|null $value): string +{ + return htmlspecialchars((string) $value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); +} + +function jsonResponse(array $payload, int $status = 200): never +{ + http_response_code($status); + header('Content-Type: application/json; charset=utf-8'); + header('Cache-Control: no-store'); + echo json_encode($payload, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES); + exit; +} + +function redirect(string $location): never +{ + header('Location: ' . $location, true, 303); + exit; +} + +function requestAction(): string +{ + return (string) ($_POST['action'] ?? $_GET['action'] ?? ''); +} + +function sourceStats(string $path): array +{ + clearstatcache(true, $path); + $stats = @stat($path); + if ($stats === false) { + throw new AppError("Dataset CSV is not readable: {$path}", 500); + } + + return [ + 'size' => (string) $stats['size'], + 'mtime' => (string) $stats['mtime'], + 'inode' => (string) $stats['ino'], + ]; +} + +function openDatabase(array $config, bool $create = false): PDO +{ + $state = $config['state']; + if (!$create && !is_file($state)) { + throw new AppError('The verifier has not been initialized.', 503); + } + + if ($create) { + $directory = dirname($state); + if (!is_dir($directory) && !@mkdir($directory, 0775, true) && !is_dir($directory)) { + throw new AppError("Cannot create the state directory: {$directory}", 500); + } + } + + try { + $db = new PDO('sqlite:' . $state, null, null, [ + PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, + PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, + ]); + $db->exec('PRAGMA journal_mode = WAL'); + $db->exec('PRAGMA synchronous = NORMAL'); + $db->exec('PRAGMA busy_timeout = 5000'); + return $db; + } catch (PDOException $error) { + throw new AppError('Cannot open SQLite state: ' . $error->getMessage(), 500); + } +} + +function createSchema(PDO $db): void +{ + $db->exec( + 'CREATE TABLE IF NOT EXISTS metadata ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL + )' + ); + $db->exec( + 'CREATE TABLE IF NOT EXISTS labels ( + id INTEGER PRIMARY KEY, + filename TEXT NOT NULL, + label TEXT NOT NULL, + batch_id TEXT NOT NULL, + verified INTEGER NOT NULL CHECK (verified IN (0, 1)), + hash TEXT NOT NULL, + dirty INTEGER NOT NULL DEFAULT 0 CHECK (dirty IN (0, 1)) + )' + ); + $db->exec( + 'CREATE INDEX IF NOT EXISTS labels_verified_id + ON labels (verified, id)' + ); + $db->exec( + 'CREATE INDEX IF NOT EXISTS labels_dirty + ON labels (dirty) WHERE dirty = 1' + ); + $db->exec( + 'CREATE TABLE IF NOT EXISTS events ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + row_id INTEGER NOT NULL, + old_label TEXT NOT NULL, + old_verified INTEGER NOT NULL, + new_label TEXT NOT NULL, + created_at TEXT NOT NULL, + FOREIGN KEY (row_id) REFERENCES labels (id) + )' + ); +} + +function metadata(PDO $db, string $key, ?string $default = null): ?string +{ + $statement = $db->prepare('SELECT value FROM metadata WHERE key = ?'); + $statement->execute([$key]); + $value = $statement->fetchColumn(); + return $value === false ? $default : (string) $value; +} + +function setMetadata(PDO $db, string $key, string|int $value): void +{ + $statement = $db->prepare( + 'INSERT INTO metadata (key, value) VALUES (?, ?) + ON CONFLICT(key) DO UPDATE SET value = excluded.value' + ); + $statement->execute([$key, (string) $value]); +} + +function acquireLock(array $config) +{ + $path = $config['state'] . '.lock'; + $directory = dirname($path); + if (!is_dir($directory) && !@mkdir($directory, 0775, true) && !is_dir($directory)) { + throw new AppError("Cannot create the state directory: {$directory}", 500); + } + $handle = @fopen($path, 'c'); + if ($handle === false || !flock($handle, LOCK_EX)) { + if (is_resource($handle)) { + fclose($handle); + } + throw new AppError('Could not lock the verifier state. Try again.', 503); + } + return $handle; +} + +function releaseLock($handle): void +{ + if (is_resource($handle)) { + flock($handle, LOCK_UN); + fclose($handle); + } +} + +function beginImmediate(PDO $db): void +{ + $db->exec('BEGIN IMMEDIATE'); +} + +function verifySourceUnchanged(PDO $db, array $config, bool $allowSyncRecovery = false): void +{ + $current = sourceStats($config['csv']); + $expectedSize = metadata($db, 'source_size'); + $expectedMtime = metadata($db, 'source_mtime'); + $expectedInode = metadata($db, 'source_inode'); + $recovering = metadata($db, 'sync_in_progress', '0') === '1'; + + if ( + ( + $current['size'] !== $expectedSize + || $current['mtime'] !== $expectedMtime + || $current['inode'] !== $expectedInode + ) + && !($allowSyncRecovery && $recovering) + ) { + throw new AppError( + 'labels.csv changed outside this verifier. Resolve the conflict before continuing.', + 409, + ); + } +} + +function initializeBatch(array $config): array +{ + if (!extension_loaded('pdo_sqlite')) { + throw new AppError('The PDO SQLite PHP extension is required.', 500); + } + if (!is_file($config['csv'])) { + throw new AppError("Dataset CSV was not found: {$config['csv']}", 500); + } + + $lock = acquireLock($config); + try { + $db = openDatabase($config, true); + createSchema($db); + $status = metadata($db, 'status'); + + if ($status === 'ready') { + return [ + 'done' => true, + 'rows' => (int) metadata($db, 'total_count', '0'), + 'percent' => 100, + ]; + } + + $source = @fopen($config['csv'], 'rb'); + if ($source === false) { + throw new AppError("Cannot open dataset CSV: {$config['csv']}", 500); + } + + try { + if ($status === null) { + $header = fgetcsv($source, null, ',', '"', ''); + if ($header !== CSV_COLUMNS) { + throw new AppError( + 'CSV columns are ' . json_encode($header) . + '; expected ' . json_encode(CSV_COLUMNS) . '.', + 422, + ); + } + + $stats = sourceStats($config['csv']); + beginImmediate($db); + setMetadata($db, 'schema_version', SCHEMA_VERSION); + setMetadata($db, 'status', 'importing'); + setMetadata($db, 'source_size', $stats['size']); + setMetadata($db, 'source_mtime', $stats['mtime']); + setMetadata($db, 'source_inode', $stats['inode']); + setMetadata($db, 'import_offset', (string) ftell($source)); + setMetadata($db, 'imported_count', '0'); + setMetadata($db, 'verified_count', '0'); + setMetadata($db, 'pending_count', '0'); + setMetadata($db, 'revision', '0'); + setMetadata($db, 'cursor_after_id', '-1'); + setMetadata($db, 'sync_in_progress', '0'); + $db->exec('COMMIT'); + } else { + verifySourceUnchanged($db, $config); + $offset = (int) metadata($db, 'import_offset', '0'); + if (fseek($source, $offset) !== 0) { + throw new AppError('Could not resume the CSV import.', 500); + } + } + + $insert = $db->prepare( + 'INSERT INTO labels + (id, filename, label, batch_id, verified, hash, dirty) + VALUES (?, ?, ?, ?, ?, ?, 0)' + ); + $imported = (int) metadata($db, 'imported_count', '0'); + $verified = (int) metadata($db, 'verified_count', '0'); + $processed = 0; + + beginImmediate($db); + while ($processed < IMPORT_BATCH_SIZE && ($row = fgetcsv($source, null, ',', '"', '')) !== false) { + if (count($row) !== count(CSV_COLUMNS)) { + throw new AppError('Malformed CSV row ' . ($imported + 2) . '.', 422); + } + [$filename, $label, $batchId, $isVerified, $hash] = $row; + if ($filename === '') { + throw new AppError('CSV row ' . ($imported + 2) . ' has an empty filename.', 422); + } + if ($isVerified !== '0' && $isVerified !== '1') { + throw new AppError( + 'CSV row ' . ($imported + 2) . ' has an invalid verified value.', + 422, + ); + } + + $insert->execute([ + $imported, + $filename, + $label, + $batchId, + (int) $isVerified, + $hash, + ]); + $verified += (int) $isVerified; + $imported++; + $processed++; + } + + $offset = (int) ftell($source); + setMetadata($db, 'import_offset', $offset); + setMetadata($db, 'imported_count', $imported); + setMetadata($db, 'verified_count', $verified); + + $done = feof($source); + if ($done) { + setMetadata($db, 'status', 'ready'); + setMetadata($db, 'total_count', $imported); + } + $db->exec('COMMIT'); + + $size = max(1, (int) metadata($db, 'source_size', '1')); + return [ + 'done' => $done, + 'rows' => $imported, + 'verified' => $verified, + 'percent' => $done ? 100 : min(99.9, round($offset * 100 / $size, 1)), + ]; + } catch (Throwable $error) { + if ($db->inTransaction()) { + $db->rollBack(); + } + throw $error; + } finally { + fclose($source); + } + } finally { + releaseLock($lock); + } +} + +function restartImport(array $config): void +{ + $lock = acquireLock($config); + try { + if (is_file($config['state'])) { + $db = openDatabase($config); + $status = metadata($db, 'status'); + $pending = (int) metadata($db, 'pending_count', '0'); + $db = null; + if ($status === 'ready') { + $reason = $pending > 0 + ? 'It also contains unsynced labels.' + : 'Restart is only available for an incomplete import.'; + throw new AppError('Cannot discard initialized state. ' . $reason, 409); + } + } + + foreach ([$config['state'], $config['state'] . '-wal', $config['state'] . '-shm'] as $path) { + if (is_file($path) && !@unlink($path)) { + throw new AppError("Cannot remove incomplete state: {$path}", 500); + } + } + } finally { + releaseLock($lock); + } +} + +function normalizeLabel(string $label): string +{ + $normalized = strtr(trim($label), [ + '۰' => '0', '۱' => '1', '۲' => '2', '۳' => '3', '۴' => '4', + '۵' => '5', '۶' => '6', '۷' => '7', '۸' => '8', '۹' => '9', + '٠' => '0', '١' => '1', '٢' => '2', '٣' => '3', '٤' => '4', + '٥' => '5', '٦' => '6', '٧' => '7', '٨' => '8', '٩' => '9', + ]); + if ($normalized === '' || strlen($normalized) > 64 || preg_match('/^[0-9]+$/D', $normalized) !== 1) { + throw new AppError('Enter digits only (ASCII, Persian, or Arabic).', 422); + } + return $normalized; +} + +function currentRow(PDO $db): ?array +{ + $after = (int) metadata($db, 'cursor_after_id', '-1'); + $statement = $db->prepare( + 'SELECT * FROM labels + WHERE verified = 0 AND id > ? + ORDER BY id LIMIT 1' + ); + $statement->execute([$after]); + $row = $statement->fetch(); + if ($row !== false) { + return $row; + } + + $row = $db->query( + 'SELECT * FROM labels WHERE verified = 0 ORDER BY id LIMIT 1' + )->fetch(); + return $row === false ? null : $row; +} + +function nextRowAfter(PDO $db, int $id): ?array +{ + $statement = $db->prepare( + 'SELECT * FROM labels + WHERE verified = 0 AND id > ? + ORDER BY id LIMIT 1' + ); + $statement->execute([$id]); + $row = $statement->fetch(); + if ($row !== false) { + return $row; + } + + $statement = $db->prepare( + 'SELECT * FROM labels + WHERE verified = 0 AND id <> ? + ORDER BY id LIMIT 1' + ); + $statement->execute([$id]); + $row = $statement->fetch(); + return $row === false ? null : $row; +} + +function rowById(PDO $db, int $id): array +{ + $statement = $db->prepare('SELECT * FROM labels WHERE id = ?'); + $statement->execute([$id]); + $row = $statement->fetch(); + if ($row === false) { + throw new AppError('Dataset row was not found.', 404); + } + return $row; +} + +function requireReady(PDO $db): void +{ + if (metadata($db, 'status') !== 'ready') { + throw new AppError('Dataset initialization is not complete.', 503); + } + if (metadata($db, 'schema_version') !== SCHEMA_VERSION) { + throw new AppError('The verifier state was created by an incompatible version.', 409); + } +} + +function requireRevision(PDO $db, int $submitted): int +{ + $current = (int) metadata($db, 'revision', '0'); + if ($submitted !== $current) { + throw new AppError('This page is stale; it has been refreshed without applying the old action.', 409); + } + return $current; +} + +function saveLabel(array $config): string +{ + $id = filter_input(INPUT_POST, 'row_id', FILTER_VALIDATE_INT); + $revision = filter_input(INPUT_POST, 'revision', FILTER_VALIDATE_INT); + $mode = ($_POST['mode'] ?? 'queue') === 'edit' ? 'edit' : 'queue'; + if ($id === false || $id === null || $revision === false || $revision === null) { + throw new AppError('Invalid row or revision.', 422); + } + $label = normalizeLabel((string) ($_POST['label'] ?? '')); + + $lock = acquireLock($config); + try { + $db = openDatabase($config); + requireReady($db); + verifySourceUnchanged($db, $config); + beginImmediate($db); + try { + $currentRevision = requireRevision($db, $revision); + $row = rowById($db, $id); + if ($mode === 'queue') { + $current = currentRow($db); + if ($current === null || (int) $current['id'] !== $id) { + throw new AppError('The verification queue has already advanced.', 409); + } + } + + $db->prepare( + 'UPDATE labels SET label = ?, verified = 1, dirty = 1 WHERE id = ?' + )->execute([$label, $id]); + $db->prepare( + 'INSERT INTO events + (row_id, old_label, old_verified, new_label, created_at) + VALUES (?, ?, ?, ?, ?)' + )->execute([ + $id, + $row['label'], + $row['verified'], + $label, + gmdate('c'), + ]); + + if ((int) $row['verified'] === 0) { + setMetadata( + $db, + 'verified_count', + (int) metadata($db, 'verified_count', '0') + 1, + ); + } + if ((int) $row['dirty'] === 0) { + setMetadata( + $db, + 'pending_count', + (int) metadata($db, 'pending_count', '0') + 1, + ); + } + if ($mode === 'queue') { + setMetadata($db, 'cursor_after_id', $id); + } + setMetadata($db, 'revision', $currentRevision + 1); + $db->exec('COMMIT'); + } catch (Throwable $error) { + if ($db->inTransaction()) { + $db->rollBack(); + } + throw $error; + } + } finally { + releaseLock($lock); + } + + return $mode === 'edit' ? 'corrected' : 'saved'; +} + +function skipRow(array $config): void +{ + $id = filter_input(INPUT_POST, 'row_id', FILTER_VALIDATE_INT); + $revision = filter_input(INPUT_POST, 'revision', FILTER_VALIDATE_INT); + if ($id === false || $id === null || $revision === false || $revision === null) { + throw new AppError('Invalid row or revision.', 422); + } + + $lock = acquireLock($config); + try { + $db = openDatabase($config); + requireReady($db); + verifySourceUnchanged($db, $config); + beginImmediate($db); + try { + $currentRevision = requireRevision($db, $revision); + $current = currentRow($db); + if ($current === null || (int) $current['id'] !== $id) { + throw new AppError('The verification queue has already advanced.', 409); + } + setMetadata($db, 'cursor_after_id', $id); + setMetadata($db, 'revision', $currentRevision + 1); + $db->exec('COMMIT'); + } catch (Throwable $error) { + if ($db->inTransaction()) { + $db->rollBack(); + } + throw $error; + } + } finally { + releaseLock($lock); + } +} + +function syncCsv(array $config): int +{ + $lock = acquireLock($config); + $temporary = null; + $replaced = false; + try { + $db = openDatabase($config); + requireReady($db); + verifySourceUnchanged($db, $config, true); + + beginImmediate($db); + setMetadata($db, 'sync_in_progress', '1'); + $db->exec('COMMIT'); + + $temporary = dirname($config['csv']) . DIRECTORY_SEPARATOR + . '.' . basename($config['csv']) . '.web-' . getmypid() . '.tmp'; + $output = @fopen($temporary, 'xb'); + if ($output === false) { + throw new AppError("Cannot create temporary CSV: {$temporary}", 500); + } + + try { + if (fputcsv($output, CSV_COLUMNS, ',', '"', '', "\n") === false) { + throw new AppError('Could not write the CSV header.', 500); + } + $rows = $db->query( + 'SELECT filename, label, batch_id, verified, hash + FROM labels ORDER BY id' + ); + $count = 0; + while ($row = $rows->fetch()) { + $values = [ + $row['filename'], + $row['label'], + $row['batch_id'], + (string) $row['verified'], + $row['hash'], + ]; + if (fputcsv($output, $values, ',', '"', '', "\n") === false) { + throw new AppError('Could not write labels.csv.', 500); + } + $count++; + } + if (!fflush($output)) { + throw new AppError('Could not flush labels.csv.', 500); + } + if (function_exists('fsync') && !fsync($output)) { + throw new AppError('Could not safely flush labels.csv to disk.', 500); + } + } finally { + fclose($output); + } + + $permissions = @fileperms($config['csv']); + if ($permissions !== false) { + @chmod($temporary, $permissions & 0777); + } + if (!@rename($temporary, $config['csv'])) { + throw new AppError('Could not atomically replace labels.csv.', 500); + } + $replaced = true; + $temporary = null; + + $stats = sourceStats($config['csv']); + beginImmediate($db); + $db->exec('UPDATE labels SET dirty = 0 WHERE dirty = 1'); + setMetadata($db, 'pending_count', '0'); + setMetadata($db, 'source_size', $stats['size']); + setMetadata($db, 'source_mtime', $stats['mtime']); + setMetadata($db, 'source_inode', $stats['inode']); + setMetadata($db, 'sync_in_progress', '0'); + setMetadata($db, 'revision', (int) metadata($db, 'revision', '0') + 1); + $db->exec('COMMIT'); + return $count; + } catch (Throwable $error) { + if (isset($db) && $db instanceof PDO && $db->inTransaction()) { + $db->rollBack(); + } + if (!$replaced && isset($db) && $db instanceof PDO) { + try { + beginImmediate($db); + setMetadata($db, 'sync_in_progress', '0'); + $db->exec('COMMIT'); + } catch (Throwable) { + if ($db->inTransaction()) { + $db->rollBack(); + } + } + } + throw $error; + } finally { + if ($temporary !== null && is_file($temporary)) { + @unlink($temporary); + } + releaseLock($lock); + } +} + +function serveImage(array $config): never +{ + $id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT); + if ($id === false || $id === null || $id < 0) { + throw new AppError('Invalid image id.', 404); + } + $db = openDatabase($config); + requireReady($db); + $row = rowById($db, $id); + + $root = realpath($config['dataset']); + $image = realpath($config['dataset'] . DIRECTORY_SEPARATOR . $row['filename']); + if ( + $root === false + || $image === false + || !is_file($image) + || !str_starts_with($image, $root . DIRECTORY_SEPARATOR) + ) { + throw new AppError('Image file is missing or outside the dataset.', 404); + } + + if (!class_exists(finfo::class)) { + throw new AppError('The PHP Fileinfo extension is required.', 500); + } + $mime = (new finfo(FILEINFO_MIME_TYPE))->file($image); + $allowed = [ + 'image/jpeg', + 'image/png', + 'image/gif', + 'image/bmp', + 'image/x-ms-bmp', + 'image/webp', + ]; + if ($mime === false || !in_array($mime, $allowed, true)) { + throw new AppError('Unsupported image type.', 415); + } + + $etagValue = preg_match('/^[a-f0-9]{64}$/i', $row['hash']) === 1 + ? strtolower($row['hash']) + : hash('sha256', $row['filename'] . '|' . filemtime($image) . '|' . filesize($image)); + $etag = '"' . $etagValue . '"'; + if (trim((string) ($_SERVER['HTTP_IF_NONE_MATCH'] ?? '')) === $etag) { + http_response_code(304); + exit; + } + + header('Content-Type: ' . $mime); + header('Content-Length: ' . (string) filesize($image)); + header('Cache-Control: private, max-age=31536000, immutable'); + header('ETag: ' . $etag); + header('X-Content-Type-Options: nosniff'); + readfile($image); + exit; +} + +function recentRows(PDO $db): array +{ + return $db->query( + 'SELECT labels.id, labels.filename, labels.label + FROM labels + JOIN ( + SELECT row_id, MAX(id) AS last_event + FROM events GROUP BY row_id + ) recent ON recent.row_id = labels.id + ORDER BY recent.last_event DESC + LIMIT 8' + )->fetchAll(); +} + +function renderHeader(string $title): void +{ + ?> + + + + + + + <?= h($title) ?> · OCR verifier + + + + + + + +
+
+
Browser verifier
+

Make the dataset ready.

+

+ The first run builds a fast local SQLite index from + . The CSV and all images stay in place. + Importing can be paused and safely resumed. +

+ +
+ + + + +
+ + +
+ + +
+ +
+

Requires PHP 8.1+, PDO SQLite, and write access to the dataset directory.

+
+
+ + +
+
+
Attention required
+

The source CSV changed.

+

+

+ SQLite currently has + unsynced row. The verifier stopped to avoid replacing + changes made by another process. +

+ +
+ + +
+ +

Do not run verify_labels.py or modify labels.csv while the web verifier is active.

+
+
+getMessage()); + } + + $editId = filter_input(INPUT_GET, 'edit', FILTER_VALIDATE_INT); + $editing = $editId !== false && $editId !== null && $editId >= 0; + $row = $editing ? rowById($db, $editId) : currentRow($db); + $total = (int) metadata($db, 'total_count', '0'); + $verified = (int) metadata($db, 'verified_count', '0'); + $remaining = max(0, $total - $verified); + $pending = (int) metadata($db, 'pending_count', '0'); + $revision = (int) metadata($db, 'revision', '0'); + $progress = $total > 0 ? $verified * 100 / $total : 100; + $recent = recentRows($db); + $status = (string) ($_GET['status'] ?? ''); + $notices = [ + 'saved' => 'Label saved. Progress is autosaved in SQLite.', + 'corrected' => 'The previous label was corrected.', + 'skipped' => 'Image skipped for now. It will return after the queue wraps.', + 'synced' => 'labels.csv was updated atomically.', + ]; + + renderHeader($editing ? 'Correct label' : 'Verify labels'); + ?> +
+
+
OCR verifier
+ 0 ? number_format($pending) . ' unsynced' : 'CSV up to date' ?> +
+ + +
+ +
+ + +
+
+
Verified
+
+
+
+
Remaining
+
+
+
+
Complete
+
%
+
+
+
+
+ of + pending CSV sync +
+
+
+
+
+ +
+ +
+
+
✓
+

Everything is verified.

+

All labels are complete. Sync the CSV if any changes are pending.

+
+
+ +
+
+ + +
+
+ Number image for row <?= (int) $row['id'] + 1 ?> +
+
+ + + + + +
+ + +
+
+
+ + Back to queue + +
+ + + + +
+ + Enter save · empty Enter skip +
+
+ + + +
+
+ + + + $error->getMessage()], $error->status); + } + if ($action === 'image') { + http_response_code($error->status); + header('Content-Type: text/plain; charset=utf-8'); + header('Cache-Control: no-store'); + echo $error->getMessage(); + exit; + } + http_response_code($error->status); + if (is_file($config['state'])) { + try { + $db = openDatabase($config); + if (metadata($db, 'status') === 'ready') { + renderVerifier($config, $error->getMessage()); + } + } catch (Throwable) { + // Fall through to the setup/error page. + } + } + renderSetup($config, $error->getMessage()); + } catch (Throwable $error) { + error_log((string) $error); + if ($action === 'initialize') { + jsonResponse(['error' => 'Unexpected initialization error. Check the PHP error log.'], 500); + } + http_response_code(500); + renderSetup($config, 'Unexpected server error. Check the PHP error log.'); + } +} + +handleRequest();