$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 wantsJson(): bool { return str_contains( strtolower((string) ($_SERVER['HTTP_ACCEPT'] ?? '')), 'application/json', ); } 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 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 { ?> <?= 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.

done · left
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' || wantsJson()) { 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();