diff --git a/README.md b/README.md index b02314a..5348b93 100644 --- a/README.md +++ b/README.md @@ -101,70 +101,58 @@ The verifier builds a complete temporary CSV and atomically replaces the origina 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 +## 5. Collect panel-validated captchas -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. +The dependency-free PHP collector downloads a fresh captcha from the customer +panel and validates your transcription with a real login attempt. An image is +added to the dataset only when the panel responds with its successful login +redirect. Rejected, expired, or skipped captchas are discarded. -Start it locally from the repository root: +The collector requires PHP 8.1 or newer with sessions, OpenSSL, and the standard +HTTP stream wrapper enabled. Start it 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. +Open `http://127.0.0.1:8080`, enter the number, and press Enter. ASCII, Persian, +and Arabic digits are accepted and normalized to ASCII. The next challenge is +loaded without a page refresh so the numeric keyboard stays open on phones. -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. - -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. -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: +By default the collector connects to `https://panel.mvphub.ir` with the panel's +demo credentials (`username` / `password`) and appends to `dataset/labels.csv`. +Set real credentials through the process environment: ```bash -OCR_DATASET_DIR=/data/persian-ocr \ - php -S 127.0.0.1:8080 -t web +PANEL_LOGIN_USERNAME='your-user' \ +PANEL_LOGIN_PASSWORD='your-password' \ +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. +The supported settings are: + +- `PANEL_BASE_URL` — panel origin; defaults to `https://panel.mvphub.ir`. +- `PANEL_LOGIN_USERNAME` — login username; defaults to `username`. +- `PANEL_LOGIN_PASSWORD` — plaintext login password; defaults to `password`. +- `PANEL_REQUEST_TIMEOUT` — upstream timeout in seconds; defaults to `10`. +- `OCR_DATASET_DIR` — output dataset; defaults to the repository's `dataset/`. + +Validated images use content-addressed paths below `images/panel/`. The collector +appends rows with `batch_id=panel` and `verified=1`, while preserving all existing +CSV rows. Writes are locked, flushed, and exact-image duplicates are idempotent. +If the dataset directory or CSV has been removed, it is recreated automatically. +Legacy `verification.sqlite` files are ignored. + +Keep the collector private: it has no user authentication and holds the panel +credentials in the PHP process environment. The PHP user needs write permission +for the dataset directory. Do not expose `dataset/` as a public web directory. ### 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; + server_name collector.example.internal; root /srv/tci-ocr/web; index index.php; @@ -176,6 +164,9 @@ server { include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root/index.php; fastcgi_param OCR_DATASET_DIR /srv/tci-ocr/dataset; + fastcgi_param PANEL_BASE_URL https://panel.mvphub.ir; + fastcgi_param PANEL_LOGIN_USERNAME your-user; + fastcgi_param PANEL_LOGIN_PASSWORD your-password; fastcgi_pass unix:/run/php/php8.3-fpm.sock; } @@ -185,6 +176,5 @@ server { } ``` -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. +Prefer protected PHP-FPM environment configuration for real secrets instead of +putting them directly in a shared Nginx configuration. diff --git a/tests/test_tools.py b/tests/test_tools.py index add8e20..44df9eb 100644 --- a/tests/test_tools.py +++ b/tests/test_tools.py @@ -1,17 +1,18 @@ from __future__ import annotations -import base64 import csv import hashlib +import http.cookiejar +import http.server import json import os import re import shutil import socket -import sqlite3 import subprocess import sys import tempfile +import threading import time import unittest import urllib.error @@ -22,6 +23,7 @@ from pathlib import Path PROJECT = Path(__file__).resolve().parents[1] PNG = b"\x89PNG\r\n\x1a\n" + b"test-image-payload" +CSV_COLUMNS = ["filename", "label", "batch_id", "verified", "hash"] class ToolTests(unittest.TestCase): @@ -38,10 +40,7 @@ class ToolTests(unittest.TestCase): image.write_bytes(PNG) csv_path = root / "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 = csv.DictWriter(output, fieldnames=CSV_COLUMNS) writer.writeheader() writer.writerow( { @@ -64,11 +63,16 @@ class ToolTests(unittest.TestCase): [ sys.executable, str(PROJECT / "download_dataset.py"), - "--url", url, - "--output", str(dataset), - "--count", "3", - "--workers", "2", - "--flush-every", "1", + "--url", + url, + "--output", + str(dataset), + "--count", + "3", + "--workers", + "2", + "--flush-every", + "1", ], text=True, capture_output=True, @@ -78,20 +82,24 @@ class ToolTests(unittest.TestCase): [ sys.executable, str(PROJECT / "download_dataset.py"), - "--url", url, - "--output", str(dataset), - "--count", "5", - "--workers", "2", + "--url", + url, + "--output", + str(dataset), + "--count", + "5", + "--workers", + "2", ], text=True, capture_output=True, ) self.assertEqual(second.returncode, 0, second.stderr) - with (dataset / "labels.csv").open(newline="", encoding="utf-8") as f: - rows = list(csv.DictReader(f)) + with (dataset / "labels.csv").open(newline="", encoding="utf-8") as source: + rows = list(csv.DictReader(source)) self.assertEqual(len(rows), 5) - self.assertEqual(list(rows[0]), ["filename", "label", "batch_id", "verified", "hash"]) + self.assertEqual(list(rows[0]), CSV_COLUMNS) self.assertEqual(rows[0]["hash"], hashlib.sha256(PNG).hexdigest()) self.assertTrue(all((dataset / row["filename"]).is_file() for row in rows)) @@ -100,15 +108,17 @@ class ToolTests(unittest.TestCase): [ sys.executable, str(PROJECT / "find_duplicates.py"), - "--csv", str(dataset / "labels.csv"), - "--output", str(report), + "--csv", + str(dataset / "labels.csv"), + "--output", + str(report), ], text=True, capture_output=True, ) self.assertEqual(result.returncode, 0, result.stderr) - with report.open(newline="", encoding="utf-8") as f: - duplicates = list(csv.DictReader(f)) + with report.open(newline="", encoding="utf-8") as source: + duplicates = list(csv.DictReader(source)) self.assertEqual(len(duplicates), 4) def test_verifier_normalizes_persian_digits_and_saves_on_quit(self): @@ -119,10 +129,7 @@ class ToolTests(unittest.TestCase): image.write_bytes(PNG) csv_path = root / "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 = csv.DictWriter(output, fieldnames=CSV_COLUMNS) writer.writeheader() for suffix in ("0", "1"): writer.writerow( @@ -131,7 +138,9 @@ class ToolTests(unittest.TestCase): "label": "", "batch_id": "0", "verified": "0", - "hash": hashlib.sha256(PNG + suffix.encode()).hexdigest(), + "hash": hashlib.sha256( + PNG + suffix.encode() + ).hexdigest(), } ) @@ -141,12 +150,15 @@ class ToolTests(unittest.TestCase): fake_kitten.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8") fake_kitten.chmod(0o755) environment = os.environ.copy() - environment["PATH"] = f"{binary_dir}{os.pathsep}{environment.get('PATH', '')}" + environment["PATH"] = ( + f"{binary_dir}{os.pathsep}{environment.get('PATH', '')}" + ) result = subprocess.run( [ sys.executable, str(PROJECT / "verify_labels.py"), - "--csv", str(csv_path), + "--csv", + str(csv_path), ], input="۱۲۳\nq\n", text=True, @@ -180,8 +192,10 @@ class ToolTests(unittest.TestCase): str(PROJECT / "merge_datasets.py"), str(source_one), str(source_two / "labels.csv"), - "--output", str(destination), - "--batch-size", "1", + "--output", + str(destination), + "--batch-size", + "1", ], text=True, capture_output=True, @@ -204,63 +218,165 @@ 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): + def test_php_panel_collector_validates_and_appends_samples(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);"] + + class PanelHandler(http.server.BaseHTTPRequestHandler): + sessions: dict[str, dict[str, object]] = {} + sequence = 0 + latest_code = "" + reject_credentials = False + next_fixture: tuple[str, bytes] | None = None + + def log_message(self, *_args): + return + + def send_body( + self, + status: int, + body: bytes, + *, + content_type: str = "text/html; charset=UTF-8", + headers: dict[str, str] | None = None, + ) -> None: + self.send_response(status) + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(body))) + for name, value in (headers or {}).items(): + self.send_header(name, value) + self.end_headers() + self.wfile.write(body) + + def session_id(self) -> str: + cookie = self.headers.get("Cookie", "") + for part in cookie.split(";"): + name, separator, value = part.strip().partition("=") + if separator and name == "CUSTOMER_PORTAL_SESSION": + return value + return "" + + def do_GET(self): + path = urllib.parse.urlsplit(self.path).path + if path == "/panel": + type(self).sequence += 1 + session_id = f"session-{type(self).sequence}" + csrf = f"{type(self).sequence:064x}" + type(self).sessions[session_id] = {"csrf": csrf} + body = ( + '
' + ).encode() + self.send_body( + 200, + body, + headers={ + "Set-Cookie": ( + "CUSTOMER_PORTAL_SESSION=" + f"{session_id}; Path=/; HttpOnly; SameSite=Lax" + ) + }, + ) + return + + if path == "/captcha": + session = type(self).sessions.get(self.session_id()) + if session is None: + self.send_body(400, b"missing session") + return + type(self).sequence += 1 + fixture = type(self).next_fixture + type(self).next_fixture = None + if fixture is None: + code = str(10000 + type(self).sequence) + image = PNG + b"-" + code.encode() + else: + code, image = fixture + session["code"] = code + session["image"] = image + type(self).latest_code = code + self.send_body(200, image, content_type="image/png") + return + + self.send_body(404, b"not found") + + def do_POST(self): + if urllib.parse.urlsplit(self.path).path != "/login": + self.send_body(404, b"not found") + return + + length = int(self.headers.get("Content-Length", "0")) + values = urllib.parse.parse_qs( + self.rfile.read(length).decode(), + keep_blank_values=True, + ) + session = type(self).sessions.get(self.session_id()) + if session is None or values.get("csrf_token", [""])[0] != session["csrf"]: + self.send_body(400, "درخواست ورود معتبر نیست".encode()) + return + if values.get("captcha", [""])[0] != session.get("code"): + self.send_body( + 401, + "کد امنیتی اشتباه است یا اعتبار آن به پایان رسیده است".encode(), + ) + return + if ( + type(self).reject_credentials + or values.get("username", [""])[0] != "username" + or values.get("password", [""])[0] != "password" + ): + self.send_body( + 401, + "نام کاربری یا رمز عبور صحیح نیست".encode(), + ) + return + self.send_body(303, b"", headers={"Location": "/panel"}) + + panel_server = http.server.ThreadingHTTPServer( + ("127.0.0.1", 0), + PanelHandler, ) - if sqlite_support.returncode != 0: - self.skipTest("PHP PDO SQLite is not installed") + panel_thread = threading.Thread( + target=panel_server.serve_forever, + daemon=True, + ) + panel_thread.start() 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=" + old_hash = hashlib.sha256(PNG).hexdigest() + old_image = self.make_dataset( + dataset, + label="123", + verified="1", + digest=old_hash, ) - 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] + collector_port = listener.getsockname()[1] environment = os.environ.copy() + for name in ( + "PANEL_LOGIN_USERNAME", + "PANEL_LOGIN_PASSWORD", + "PANEL_USERNAME", + "PANEL_PASSWORD", + ): + environment.pop(name, None) environment["OCR_DATASET_DIR"] = str(dataset) - server = subprocess.Popen( + environment["PANEL_BASE_URL"] = ( + f"http://127.0.0.1:{panel_server.server_port}" + ) + environment["PANEL_REQUEST_TIMEOUT"] = "2" + collector = subprocess.Popen( [ php, "-S", - f"127.0.0.1:{port}", + f"127.0.0.1:{collector_port}", "-t", str(PROJECT / "web"), ], @@ -269,205 +385,209 @@ class ToolTests(unittest.TestCase): text=True, env=environment, ) - base_url = f"http://127.0.0.1:{port}/" + base_url = f"http://127.0.0.1:{collector_port}/" + opener = urllib.request.build_opener( + urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar()) + ) 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: + with opener.open(base_url + path, timeout=10) as response: return response.status, response.read(), dict(response.headers) 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: + request = urllib.request.Request( + base_url, + data=urllib.parse.urlencode(values).encode(), + method="POST", + headers={"Accept": "application/json"}, + ) + with opener.open(request, timeout=15) as response: return response.status, response.read(), dict(response.headers) try: - for _ in range(50): + for _ in range(60): try: - status, page, _ = get() + status, page, headers = get() if status == 200: break except urllib.error.URLError: time.sleep(0.05) else: - self.fail("PHP development server did not start") + self.fail("PHP collector 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"') + self.assertIn(b"Captcha collector", page) + self.assertIn(b'inputmode="numeric"', page) 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) + self.assertIn("no-store", headers["Cache-Control"]) + self.assertIn("default-src 'self'", headers["Content-Security-Policy"]) - 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() - - status, payload, headers = post( - { - "action": "save", - "row_id": "1", - "revision": "0", - "mode": "queue", - "label": "۱۲۳۴", - }, - accept_json=True, + csrf = re.search( + rb'name="csrf_token" value="([a-f0-9]{64})"', + 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) + challenge = re.search( + rb'name="challenge_id" value="([a-f0-9]{32})"', + page, + ) + self.assertIsNotNone(csrf) + self.assertIsNotNone(challenge) + csrf_token = csrf.group(1).decode() + first_challenge = challenge.group(1).decode() - _, page, _ = get() - self.assertRegex(page, rb'name="row_id" value="2"') - self.assertRegex(page, rb'name="revision" value="1"') + _, first_image, image_headers = get( + f"?action=captcha&id={first_challenge}" + ) + self.assertEqual(image_headers["Content-Type"], "image/png") + + _, rejected_body, _ = post( + { + "action": "submit", + "csrf_token": csrf_token, + "challenge_id": first_challenge, + "label": "99999", + } + ) + rejected = json.loads(rejected_body) + self.assertEqual(rejected["outcome"], "rejected") + self.assertNotEqual(rejected["challenge"]["id"], first_challenge) + with csv_path.open(newline="", encoding="utf-8") as source: + self.assertEqual(len(list(csv.DictReader(source))), 1) with self.assertRaises(urllib.error.HTTPError) as stale: post( { - "action": "save", - "row_id": "1", - "revision": "0", - "mode": "queue", - "label": "999", + "action": "submit", + "csrf_token": csrf_token, + "challenge_id": first_challenge, + "label": "99999", } ) 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() - - status, payload, _ = post( - { - "action": "skip", - "row_id": "2", - "revision": "1", - }, - accept_json=True, + accepted_challenge = rejected["challenge"]["id"] + _, accepted_image, _ = get( + f"?action=captcha&id={accepted_challenge}" ) - 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") - revision = re.search(rb'name="revision" value="(\d+)"', edit_page) - self.assertIsNotNone(revision) - _, corrected_page, _ = post( + ascii_code = PanelHandler.latest_code + persian_code = ascii_code.translate( + str.maketrans("0123456789", "۰۱۲۳۴۵۶۷۸۹") + ) + PanelHandler.next_fixture = (ascii_code, accepted_image) + _, saved_body, _ = post( { - "action": "save", - "row_id": "1", - "revision": revision.group(1).decode(), - "mode": "edit", - "label": "4567", + "action": "submit", + "csrf_token": csrf_token, + "challenge_id": accepted_challenge, + "label": persian_code, } ) - self.assertIn(b"corrected", corrected_page) + saved = json.loads(saved_body) + self.assertEqual(saved["outcome"], "saved") + self.assertEqual(saved["saved_this_session"], 1) - 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(len(rows), 2) + self.assertEqual(rows[0]["filename"], old_image.relative_to(dataset).as_posix()) + self.assertEqual(rows[1]["label"], ascii_code) + self.assertEqual(rows[1]["batch_id"], "panel") self.assertEqual(rows[1]["verified"], "1") - self.assertEqual(rows[2]["verified"], "0") + self.assertEqual( + rows[1]["hash"], + hashlib.sha256(accepted_image).hexdigest(), + ) + self.assertEqual( + (dataset / rows[1]["filename"]).read_bytes(), + accepted_image, + ) - 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",)) + duplicate_challenge = saved["challenge"]["id"] + _, duplicate_image, _ = get( + f"?action=captcha&id={duplicate_challenge}" + ) + self.assertEqual(duplicate_image, accepted_image) + _, duplicate_body, _ = post( + { + "action": "submit", + "csrf_token": csrf_token, + "challenge_id": duplicate_challenge, + "label": ascii_code, + } + ) + duplicate = json.loads(duplicate_body) + self.assertEqual(duplicate["outcome"], "duplicate") + self.assertEqual(duplicate["saved_this_session"], 1) + with csv_path.open(newline="", encoding="utf-8") as source: + self.assertEqual(len(list(csv.DictReader(source))), 2) - with self.assertRaises(urllib.error.HTTPError) as missing: - get("?action=image&id=999") - self.assertEqual(missing.exception.code, 404) - missing.exception.close() + # Removing the old dataset must not require resetting collector state. + next_challenge = duplicate["challenge"]["id"] + _, recreated_image, _ = get( + f"?action=captcha&id={next_challenge}" + ) + recreate_code = PanelHandler.latest_code + shutil.rmtree(dataset) + _, recreated_body, _ = post( + { + "action": "submit", + "csrf_token": csrf_token, + "challenge_id": next_challenge, + "label": recreate_code, + } + ) + recreated = json.loads(recreated_body) + self.assertEqual(recreated["outcome"], "saved") + with csv_path.open(newline="", encoding="utf-8") as source: + recreated_rows = list(csv.DictReader(source)) + self.assertEqual(len(recreated_rows), 1) + self.assertEqual( + (dataset / recreated_rows[0]["filename"]).read_bytes(), + recreated_image, + ) - 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() + PanelHandler.reject_credentials = True + credential_challenge = recreated["challenge"]["id"] + credential_code = PanelHandler.latest_code + with self.assertRaises(urllib.error.HTTPError) as credentials: + post( + { + "action": "submit", + "csrf_token": csrf_token, + "challenge_id": credential_challenge, + "label": credential_code, + } + ) + self.assertEqual(credentials.exception.code, 502) + credential_payload = json.loads(credentials.exception.read()) + self.assertIn("username or password", credential_payload["error"]) + self.assertIsNone(credential_payload["challenge"]) + credentials.exception.close() + with csv_path.open(newline="", encoding="utf-8") as source: + self.assertEqual(len(list(csv.DictReader(source))), 1) + + node = shutil.which("node") + if node is not None: + syntax = subprocess.run( + [node, "--check", str(PROJECT / "web" / "app.js")], + text=True, + capture_output=True, + ) + self.assertEqual(syntax.returncode, 0, syntax.stderr) finally: - server.terminate() + collector.terminate() try: - server.wait(timeout=5) + collector.wait(timeout=5) except subprocess.TimeoutExpired: - server.kill() - server.wait(timeout=5) - if server.stderr is not None: - server.stderr.close() + collector.kill() + collector.wait(timeout=5) + if collector.stderr is not None: + collector.stderr.close() + panel_server.shutdown() + panel_server.server_close() + panel_thread.join(timeout=5) if __name__ == "__main__": diff --git a/web/app.css b/web/app.css new file mode 100644 index 0000000..1f4d4c1 --- /dev/null +++ b/web/app.css @@ -0,0 +1,249 @@ +:root { + color-scheme: dark; + font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; + background: #09111d; + color: #eaf1fb; + --panel: #111d2d; + --line: #26364b; + --muted: #91a2b8; + --accent: #67e8b8; + --accent-dark: #073c31; + --danger: #ff9a9a; +} + +* { + box-sizing: border-box; +} + +body { + min-height: 100dvh; + margin: 0; + background: + radial-gradient(circle at top, rgba(46, 91, 126, .28), transparent 36rem), + #09111d; +} + +button, +input { + font: inherit; +} + +.shell { + width: min(100% - 2rem, 42rem); + margin: 0 auto; + padding: max(1.25rem, env(safe-area-inset-top)) 0 max(2rem, env(safe-area-inset-bottom)); +} + +.topbar { + display: flex; + align-items: flex-end; + justify-content: space-between; + gap: 1rem; + margin-bottom: 1.2rem; +} + +.eyebrow { + margin: 0 0 .2rem; + color: var(--accent); + font-size: .75rem; + font-weight: 800; + letter-spacing: .12em; + text-transform: uppercase; +} + +h1, +h2, +p { + margin-top: 0; +} + +h1 { + margin-bottom: 0; + font-size: clamp(1.55rem, 6vw, 2.2rem); +} + +.counter { + flex: 0 0 auto; + text-align: right; +} + +.counter strong { + display: block; + color: var(--accent); + font-size: 1.5rem; + line-height: 1; +} + +.counter span, +.privacy { + color: var(--muted); + font-size: .78rem; +} + +.status { + min-height: 2.8rem; + margin-bottom: .9rem; + padding: .75rem .9rem; + border: 1px solid rgba(103, 232, 184, .24); + border-radius: .8rem; + background: rgba(103, 232, 184, .08); + color: #c7f9e8; +} + +.status.error { + border-color: rgba(255, 154, 154, .3); + background: rgba(255, 99, 99, .09); + color: var(--danger); +} + +.card { + padding: clamp(1rem, 4vw, 1.6rem); + border: 1px solid var(--line); + border-radius: 1.15rem; + background: rgba(17, 29, 45, .96); + box-shadow: 0 1.5rem 4rem rgba(0, 0, 0, .28); +} + +.image-stage { + display: grid; + min-height: 9.5rem; + place-items: center; + margin-bottom: 1.2rem; + border: 1px solid var(--line); + border-radius: .9rem; + background: #f3f6fa; + overflow: hidden; +} + +.image-stage img { + width: min(100%, 27.5rem); + height: auto; + image-rendering: auto; +} + +label { + display: block; + margin-bottom: .45rem; + color: var(--muted); + font-size: .86rem; + font-weight: 700; +} + +.entry-row { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + gap: .7rem; +} + +input { + min-width: 0; + height: 3.35rem; + padding: 0 .95rem; + border: 1px solid #39506c; + border-radius: .75rem; + outline: 0; + background: #09131f; + color: #fff; + font-size: 1.25rem; + font-variant-numeric: tabular-nums; + letter-spacing: .08em; +} + +input:focus { + border-color: var(--accent); + box-shadow: 0 0 0 .2rem rgba(103, 232, 184, .12); +} + +button, +.button-link { + min-height: 3.35rem; + padding: 0 1rem; + border: 0; + border-radius: .75rem; + cursor: pointer; + font-weight: 800; + text-decoration: none; +} + +button:disabled { + cursor: wait; + opacity: .55; +} + +.primary { + background: var(--accent); + color: var(--accent-dark); +} + +.secondary { + width: 100%; + min-height: 2.8rem; + margin-top: .7rem; + border: 1px solid var(--line); + background: transparent; + color: var(--muted); +} + +.button-link { + display: inline-flex; + align-items: center; +} + +.unavailable { + padding: 2rem 1rem; + text-align: center; +} + +.unavailable p { + color: var(--muted); +} + +.privacy { + margin: .9rem 0 0; + text-align: center; +} + +[hidden] { + display: none !important; +} + +@media (max-width: 560px) { + .shell { + width: min(100% - 1rem, 42rem); + padding-top: max(.7rem, env(safe-area-inset-top)); + } + + .topbar { + align-items: center; + margin-bottom: .7rem; + } + + .counter span { + display: none; + } + + .card { + padding: .8rem; + border-radius: .9rem; + } + + .image-stage { + min-height: 7.7rem; + margin-bottom: .8rem; + } + + .entry-row { + grid-template-columns: minmax(0, 1fr) 7.3rem; + gap: .45rem; + } + + input, + button { + height: 3.2rem; + } + + .primary { + padding: 0 .65rem; + font-size: .88rem; + } +} diff --git a/web/app.js b/web/app.js new file mode 100644 index 0000000..92a207c --- /dev/null +++ b/web/app.js @@ -0,0 +1,117 @@ +(() => { + const answerForm = document.querySelector('#answer-form'); + const nextForm = document.querySelector('#next-form'); + const input = document.querySelector('#label'); + const image = document.querySelector('#captcha-image'); + const status = document.querySelector('#status'); + const savedCount = document.querySelector('#saved-count'); + const submitButton = document.querySelector('#submit-button'); + let busy = false; + + if (!answerForm || !nextForm || !input || !image || !status || !submitButton) { + return; + } + + const digitMap = { + '۰': '0', '۱': '1', '۲': '2', '۳': '3', '۴': '4', + '۵': '5', '۶': '6', '۷': '7', '۸': '8', '۹': '9', + '٠': '0', '١': '1', '٢': '2', '٣': '3', '٤': '4', + '٥': '5', '٦': '6', '٧': '7', '٨': '8', '٩': '9', + }; + + const showStatus = (message, isError = false) => { + status.hidden = false; + status.textContent = message; + status.classList.toggle('error', isError); + }; + + const setBusy = value => { + busy = value; + submitButton.disabled = value; + nextForm.querySelector('button').disabled = value; + }; + + const applyChallenge = challenge => { + if (!challenge) { + answerForm.hidden = true; + image.closest('.image-stage').hidden = true; + nextForm.querySelector('button').textContent = 'Try another captcha'; + return; + } + answerForm.hidden = false; + image.closest('.image-stage').hidden = false; + nextForm.querySelector('button').textContent = 'New captcha'; + answerForm.elements.challenge_id.value = challenge.id; + image.src = `${challenge.image_url}&nonce=${Date.now()}`; + input.value = ''; + input.focus({preventScroll: true}); + }; + + const submit = async form => { + if (busy) return; + setBusy(true); + try { + const response = await fetch(form.action, { + method: 'POST', + body: new FormData(form), + headers: {'Accept': 'application/json'}, + }); + let payload; + try { + payload = await response.json(); + } catch { + throw new Error('The server returned an invalid response.'); + } + if (!response.ok) { + const problem = new Error(payload.error || 'The request failed.'); + problem.payload = payload; + throw problem; + } + + if (savedCount) { + savedCount.textContent = new Intl.NumberFormat().format( + payload.saved_this_session + ); + } + applyChallenge(payload.challenge); + showStatus( + payload.warning + ? `${payload.message} ${payload.warning}` + : payload.message, + Boolean(payload.warning), + ); + } catch (problem) { + if ( + problem.payload + && Object.prototype.hasOwnProperty.call(problem.payload, 'challenge') + ) { + applyChallenge(problem.payload.challenge); + } + showStatus(problem.message || 'Connection error. Refresh and try again.', true); + if (!answerForm.hidden) { + input.focus({preventScroll: true}); + input.select(); + } + } finally { + setBusy(false); + } + }; + + input.addEventListener('input', () => { + input.value = Array.from( + input.value, + character => digitMap[character] ?? character, + ).join('').replace(/[^0-9]/g, ''); + }); + + answerForm.addEventListener('submit', event => { + event.preventDefault(); + submit(answerForm); + }); + nextForm.addEventListener('submit', event => { + event.preventDefault(); + submit(nextForm); + }); + + input.focus(); +})(); diff --git a/web/collector.php b/web/collector.php new file mode 100644 index 0000000..9784a4d --- /dev/null +++ b/web/collector.php @@ -0,0 +1,681 @@ +> $headers + */ + public function __construct( + public readonly int $status, + public readonly array $headers, + public readonly string $body, + ) { + } + + public function header(string $name): ?string + { + $values = $this->headers[strtolower($name)] ?? []; + return $values[0] ?? null; + } + + /** @return list */ + public function headers(string $name): array + { + return $this->headers[strtolower($name)] ?? []; + } +} + +function collectorConfig(): array +{ + $configuredDataset = $_SERVER['OCR_DATASET_DIR'] ?? getenv('OCR_DATASET_DIR') ?: ''; + $timeoutValue = $_SERVER['PANEL_REQUEST_TIMEOUT'] + ?? getenv('PANEL_REQUEST_TIMEOUT') + ?: '10'; + $timeout = filter_var($timeoutValue, FILTER_VALIDATE_INT); + + return [ + 'dataset' => rtrim( + $configuredDataset !== '' ? $configuredDataset : dirname(__DIR__) . '/dataset', + DIRECTORY_SEPARATOR, + ), + 'panel_base_url' => rtrim( + $_SERVER['PANEL_BASE_URL'] + ?? getenv('PANEL_BASE_URL') + ?: 'https://panel.mvphub.ir', + '/', + ), + 'panel_username' => (string) ( + $_SERVER['PANEL_LOGIN_USERNAME'] + ?? getenv('PANEL_LOGIN_USERNAME') + ?: 'username' + ), + 'panel_password' => (string) ( + $_SERVER['PANEL_LOGIN_PASSWORD'] + ?? getenv('PANEL_LOGIN_PASSWORD') + ?: 'password' + ), + 'timeout' => $timeout === false ? 10 : max(1, min(60, $timeout)), + ]; +} + +function sendSecurityHeaders(): void +{ + header_remove('X-Powered-By'); + header('Cache-Control: no-store, max-age=0'); + header('Pragma: no-cache'); + header('X-Content-Type-Options: nosniff'); + header('X-Frame-Options: DENY'); + header("Content-Security-Policy: default-src 'self'; img-src 'self'; style-src 'self'; script-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'"); + header('Referrer-Policy: no-referrer'); + header('Permissions-Policy: camera=(), microphone=(), geolocation=()'); +} + +function h(string|int|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'); + echo json_encode($payload, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES); + exit; +} + +function redirect(string $location): never +{ + header('Location: ' . $location, true, 303); + exit; +} + +function wantsJson(): bool +{ + return str_contains( + strtolower((string) ($_SERVER['HTTP_ACCEPT'] ?? '')), + 'application/json', + ); +} + +function scalarRequestValue(string $key, int $maxLength): ?string +{ + $value = $_POST[$key] ?? $_GET[$key] ?? null; + return is_string($value) && strlen($value) <= $maxLength ? $value : null; +} + +function scalarPostValue(string $key, int $maxLength): ?string +{ + $value = $_POST[$key] ?? null; + return is_string($value) && strlen($value) <= $maxLength ? $value : null; +} + +function localCsrfToken(): string +{ + if (!isset($_SESSION['local_csrf']) || !is_string($_SESSION['local_csrf'])) { + $_SESSION['local_csrf'] = bin2hex(random_bytes(32)); + } + return $_SESSION['local_csrf']; +} + +function requireLocalCsrf(): void +{ + $submitted = scalarPostValue('csrf_token', 64); + if ($submitted === null || !hash_equals(localCsrfToken(), $submitted)) { + throw new CollectorError('This page has expired. Refresh it and try again.', 403); + } +} + +function normalizeAnswer(string $answer): string +{ + $answer = strtr(trim($answer), [ + '۰' => '0', '۱' => '1', '۲' => '2', '۳' => '3', '۴' => '4', + '۵' => '5', '۶' => '6', '۷' => '7', '۸' => '8', '۹' => '9', + '٠' => '0', '١' => '1', '٢' => '2', '٣' => '3', '٤' => '4', + '٥' => '5', '٦' => '6', '٧' => '7', '٨' => '8', '٩' => '9', + ]); + if ($answer === '' || strlen($answer) > 16 || preg_match('/^[0-9]+$/D', $answer) !== 1) { + throw new CollectorError('Enter digits only.', 422); + } + return $answer; +} + +function panelUrl(array $config, string $path): string +{ + $base = $config['panel_base_url']; + $parts = parse_url($base); + if ( + $parts === false + || !isset($parts['scheme'], $parts['host']) + || !in_array(strtolower((string) $parts['scheme']), ['http', 'https'], true) + || isset($parts['user']) + || isset($parts['pass']) + || isset($parts['query']) + || isset($parts['fragment']) + ) { + throw new CollectorError('PANEL_BASE_URL must be a valid HTTP or HTTPS origin.', 500); + } + return $base . '/' . ltrim($path, '/'); +} + +/** + * @param list $headers + */ +function panelRequest( + array $config, + string $method, + string $path, + array $headers = [], + string $body = '', +): PanelResponse { + foreach ($headers as $header) { + if (str_contains($header, "\r") || str_contains($header, "\n")) { + throw new CollectorError('Unsafe outbound panel header.', 500); + } + } + + $headers[] = 'Accept: text/html, image/*;q=0.9, */*;q=0.5'; + $headers[] = 'User-Agent: tci-ocr-panel-collector/1.0'; + $options = [ + 'http' => [ + 'method' => strtoupper($method), + 'header' => implode("\r\n", $headers), + 'content' => $body, + 'ignore_errors' => true, + 'follow_location' => 0, + 'timeout' => $config['timeout'], + 'protocol_version' => 1.1, + ], + 'ssl' => [ + 'verify_peer' => true, + 'verify_peer_name' => true, + ], + ]; + + $stream = @fopen(panelUrl($config, $path), 'rb', false, stream_context_create($options)); + if ($stream === false) { + $details = error_get_last(); + $message = is_array($details) ? (string) ($details['message'] ?? '') : ''; + error_log('Panel request failed: ' . $message); + throw new CollectorError('Could not connect to the panel.', 502); + } + + try { + $responseBody = stream_get_contents($stream, MAX_PANEL_RESPONSE_BYTES + 1); + $metadata = stream_get_meta_data($stream); + } finally { + fclose($stream); + } + + if ($responseBody === false || ($metadata['timed_out'] ?? false) === true) { + throw new CollectorError('The panel request timed out.', 504); + } + if (strlen($responseBody) > MAX_PANEL_RESPONSE_BYTES) { + throw new CollectorError('The panel returned an unexpectedly large response.', 502); + } + + $rawHeaders = $metadata['wrapper_data'] ?? []; + if (!is_array($rawHeaders)) { + throw new CollectorError('The panel returned malformed HTTP headers.', 502); + } + + $status = 0; + $parsedHeaders = []; + foreach ($rawHeaders as $line) { + if (!is_string($line)) { + continue; + } + if (preg_match('#^HTTP/\S+\s+(\d{3})#i', $line, $matches) === 1) { + $status = (int) $matches[1]; + $parsedHeaders = []; + continue; + } + $separator = strpos($line, ':'); + if ($separator === false) { + continue; + } + $name = substr($line, 0, $separator); + $value = substr($line, $separator + 1); + if (trim($name) === '') { + continue; + } + $parsedHeaders[strtolower(trim($name))][] = trim($value); + } + + if ($status === 0) { + throw new CollectorError('The panel returned a response without an HTTP status.', 502); + } + return new PanelResponse($status, $parsedHeaders, $responseBody); +} + +function extractPanelCookies(PanelResponse $response): string +{ + $cookies = []; + foreach ($response->headers('set-cookie') as $header) { + $pair = trim(explode(';', $header, 2)[0]); + $separator = strpos($pair, '='); + if ($separator === false) { + continue; + } + $name = substr($pair, 0, $separator); + $value = substr($pair, $separator + 1); + if ( + preg_match('/^[A-Za-z0-9_.-]+$/D', $name) !== 1 + || preg_match('/[\x00-\x20\x7f;]/', $value) === 1 + ) { + continue; + } + $cookies[$name] = $value; + } + if ($cookies === []) { + throw new CollectorError('The panel did not create a login session.', 502); + } + + $parts = []; + foreach ($cookies as $name => $value) { + $parts[] = $name . '=' . $value; + } + return implode('; ', $parts); +} + +function extractPanelCsrf(string $html): string +{ + $patterns = [ + '/]*\bname=(["\'])csrf_token\1[^>]*\bvalue=(["\'])(.*?)\2[^>]*>/is', + '/]*\bvalue=(["\'])(.*?)\1[^>]*\bname=(["\'])csrf_token\3[^>]*>/is', + ]; + foreach ($patterns as $index => $pattern) { + if (preg_match($pattern, $html, $matches) === 1) { + $value = $index === 0 ? $matches[3] : $matches[2]; + $token = html_entity_decode($value, ENT_QUOTES | ENT_HTML5, 'UTF-8'); + if (preg_match('/^[a-f0-9]{64}$/D', $token) === 1) { + return $token; + } + } + } + throw new CollectorError('Could not find the panel login token.', 502); +} + +function imageType(string $bytes, ?string $contentType): array +{ + $mediaType = strtolower(trim(explode(';', (string) $contentType, 2)[0])); + $types = [ + 'image/jpeg' => ['extension' => '.jpg', 'magic' => str_starts_with($bytes, "\xff\xd8\xff")], + 'image/png' => ['extension' => '.png', 'magic' => str_starts_with($bytes, "\x89PNG\r\n\x1a\n")], + 'image/gif' => ['extension' => '.gif', 'magic' => str_starts_with($bytes, 'GIF87a') || str_starts_with($bytes, 'GIF89a')], + 'image/bmp' => ['extension' => '.bmp', 'magic' => str_starts_with($bytes, 'BM')], + 'image/webp' => [ + 'extension' => '.webp', + 'magic' => strlen($bytes) >= 12 + && substr($bytes, 0, 4) === 'RIFF' + && substr($bytes, 8, 4) === 'WEBP', + ], + ]; + $type = $types[$mediaType] ?? null; + if ($type === null || $type['magic'] !== true) { + throw new CollectorError('The panel returned an unsupported captcha image.', 502); + } + return ['mime' => $mediaType, 'extension' => $type['extension']]; +} + +function fetchPanelChallenge(array $config): array +{ + $login = panelRequest($config, 'GET', '/panel'); + if ($login->status !== 200) { + throw new CollectorError('The panel login page is unavailable.', 502); + } + $cookie = extractPanelCookies($login); + $upstreamCsrf = extractPanelCsrf($login->body); + + $captcha = panelRequest( + $config, + 'GET', + '/captcha?nonce=' . rawurlencode(bin2hex(random_bytes(8))), + ['Cookie: ' . $cookie], + ); + if ($captcha->status !== 200 || $captcha->body === '') { + throw new CollectorError('The panel captcha is unavailable.', 502); + } + $type = imageType($captcha->body, $captcha->header('content-type')); + + return [ + 'id' => bin2hex(random_bytes(16)), + 'cookie' => $cookie, + 'upstream_csrf' => $upstreamCsrf, + 'image' => $captcha->body, + 'mime' => $type['mime'], + 'extension' => $type['extension'], + 'issued_at' => time(), + ]; +} + +function challengeIsUsable(mixed $challenge): bool +{ + return is_array($challenge) + && isset( + $challenge['id'], + $challenge['cookie'], + $challenge['upstream_csrf'], + $challenge['image'], + $challenge['mime'], + $challenge['extension'], + $challenge['issued_at'], + ) + && is_string($challenge['id']) + && is_string($challenge['cookie']) + && is_string($challenge['upstream_csrf']) + && is_string($challenge['image']) + && is_string($challenge['mime']) + && is_string($challenge['extension']) + && is_int($challenge['issued_at']) + && (time() - $challenge['issued_at']) <= CHALLENGE_MAX_AGE; +} + +function ensurePanelChallenge(array $config, bool $force = false): array +{ + $current = $_SESSION['panel_challenge'] ?? null; + if (!$force && challengeIsUsable($current)) { + return $current; + } + + unset($_SESSION['panel_challenge']); + $challenge = fetchPanelChallenge($config); + $_SESSION['panel_challenge'] = $challenge; + return $challenge; +} + +function challengeImageUrl(array $challenge): string +{ + return '?action=captcha&id=' . rawurlencode($challenge['id']); +} + +function challengePayload(array $challenge): array +{ + return [ + 'id' => $challenge['id'], + 'image_url' => challengeImageUrl($challenge), + ]; +} + +function servePendingCaptcha(): never +{ + $id = scalarRequestValue('id', 64) ?? ''; + $challenge = $_SESSION['panel_challenge'] ?? null; + if ( + !challengeIsUsable($challenge) + || $id === '' + || !hash_equals($challenge['id'], $id) + ) { + throw new CollectorError('Captcha not found or expired.', 404); + } + + header('Content-Type: ' . $challenge['mime']); + header('Content-Length: ' . strlen($challenge['image'])); + echo $challenge['image']; + exit; +} + +function validatePendingChallenge(array $config, string $challengeId, string $answer): array +{ + $challenge = $_SESSION['panel_challenge'] ?? null; + if ( + !challengeIsUsable($challenge) + || $challengeId === '' + || !hash_equals($challenge['id'], $challengeId) + ) { + throw new CollectorError('This captcha has expired. Load a new one.', 409); + } + + // A panel captcha can be used only once. Discard it before the network request + // so an ambiguous timeout can never cause a guessed label to be submitted twice. + unset($_SESSION['panel_challenge']); + + $body = http_build_query([ + 'username' => $config['panel_username'], + 'password' => $config['panel_password'], + 'captcha' => $answer, + 'csrf_token' => $challenge['upstream_csrf'], + ], '', '&', PHP_QUERY_RFC3986); + + $response = panelRequest( + $config, + 'POST', + '/login', + [ + 'Content-Type: application/x-www-form-urlencoded', + 'Content-Length: ' . strlen($body), + 'Cookie: ' . $challenge['cookie'], + ], + $body, + ); + + $location = $response->header('location'); + $locationPath = $location === null ? null : parse_url($location, PHP_URL_PATH); + if ($response->status === 303 && $locationPath === '/panel') { + return storeValidatedSample($config, $challenge, $answer); + } + + if ( + $response->status === 401 + && str_contains($response->body, 'کد امنیتی اشتباه است یا اعتبار آن به پایان رسیده است') + ) { + return ['stored' => false, 'rejected' => true]; + } + + if ( + $response->status === 401 + && str_contains($response->body, 'نام کاربری یا رمز عبور صحیح نیست') + ) { + throw new CollectorError( + 'The panel rejected the configured username or password.', + 502, + ); + } + + throw new CollectorError( + 'The panel returned an unexpected login response; nothing was saved.', + 502, + ); +} + +function outcomeMessage(string $outcome): string +{ + return match ($outcome) { + 'saved' => 'Correct — saved.', + 'duplicate' => 'Correct — already saved.', + 'rejected' => 'Rejected — showing the next captcha.', + 'skipped' => 'New captcha loaded.', + default => 'Ready.', + }; +} + +function ensureDirectory(string $path): void +{ + if (!is_dir($path) && !@mkdir($path, 0775, true) && !is_dir($path)) { + throw new CollectorError("Cannot create dataset directory: {$path}", 500); + } +} + +function writeAtomic(string $path, string $bytes): void +{ + ensureDirectory(dirname($path)); + $temporary = dirname($path) . DIRECTORY_SEPARATOR + . '.' . basename($path) . '.' . bin2hex(random_bytes(6)) . '.tmp'; + $handle = @fopen($temporary, 'xb'); + if ($handle === false) { + throw new CollectorError('Cannot create a temporary dataset file.', 500); + } + + $completed = false; + try { + try { + $written = 0; + $length = strlen($bytes); + while ($written < $length) { + $count = fwrite($handle, substr($bytes, $written)); + if ($count === false || $count === 0) { + throw new CollectorError('Could not write the captcha image.', 500); + } + $written += $count; + } + if (!fflush($handle) || (function_exists('fsync') && !fsync($handle))) { + throw new CollectorError('Could not safely flush the captcha image.', 500); + } + } finally { + fclose($handle); + } + + if (!@rename($temporary, $path)) { + throw new CollectorError('Could not finalize the captcha image.', 500); + } + $completed = true; + } finally { + if (!$completed && is_file($temporary)) { + @unlink($temporary); + } + } +} + +function csvContainsFilename($handle, string $filename): bool +{ + rewind($handle); + fgetcsv($handle, null, ',', '"', ''); + while (($row = fgetcsv($handle, null, ',', '"', '')) !== false) { + if (($row[0] ?? null) === $filename) { + return true; + } + } + return false; +} + +function validateOrCreateCsvHeader($handle): void +{ + $stats = fstat($handle); + if ($stats === false) { + throw new CollectorError('Could not inspect labels.csv.', 500); + } + if ((int) $stats['size'] === 0) { + if (fputcsv($handle, DATASET_COLUMNS, ',', '"', '', "\n") === false) { + throw new CollectorError('Could not initialize labels.csv.', 500); + } + return; + } + + rewind($handle); + $header = fgetcsv($handle, null, ',', '"', ''); + if ($header !== DATASET_COLUMNS) { + throw new CollectorError('labels.csv has an incompatible header.', 409); + } +} + +function appendCsvRow($handle, array $row): void +{ + if (fseek($handle, 0, SEEK_END) !== 0) { + throw new CollectorError('Could not seek to the end of labels.csv.', 500); + } + $position = ftell($handle); + if ($position === false) { + throw new CollectorError('Could not inspect labels.csv.', 500); + } + if ($position > 0) { + if (fseek($handle, -1, SEEK_END) !== 0) { + throw new CollectorError('Could not inspect the end of labels.csv.', 500); + } + $last = fread($handle, 1); + if (fseek($handle, 0, SEEK_END) !== 0) { + throw new CollectorError('Could not seek to the end of labels.csv.', 500); + } + if ($last !== "\n" && fwrite($handle, "\n") !== 1) { + throw new CollectorError('Could not repair the labels.csv line ending.', 500); + } + } + if (fputcsv($handle, $row, ',', '"', '', "\n") === false) { + throw new CollectorError('Could not append to labels.csv.', 500); + } + if (!fflush($handle) || (function_exists('fsync') && !fsync($handle))) { + throw new CollectorError('Could not safely flush labels.csv.', 500); + } +} + +function storeValidatedSample(array $config, array $challenge, string $label): array +{ + $dataset = $config['dataset']; + ensureDirectory($dataset); + $hash = hash('sha256', $challenge['image']); + $relative = 'images/panel/' . substr($hash, 0, 2) . '/' + . $hash . $challenge['extension']; + $imagePath = $dataset . DIRECTORY_SEPARATOR + . str_replace('/', DIRECTORY_SEPARATOR, $relative); + $marker = $dataset . DIRECTORY_SEPARATOR . '.panel-samples' + . DIRECTORY_SEPARATOR . substr($hash, 0, 2) + . DIRECTORY_SEPARATOR . $hash . '.done'; + $csvPath = $dataset . DIRECTORY_SEPARATOR . 'labels.csv'; + $lockPath = $dataset . DIRECTORY_SEPARATOR . '.panel-collector.lock'; + + $lock = @fopen($lockPath, 'c'); + if ($lock === false || !flock($lock, LOCK_EX)) { + if (is_resource($lock)) { + fclose($lock); + } + throw new CollectorError('Could not lock the dataset for writing.', 503); + } + + try { + $csv = @fopen($csvPath, 'c+b'); + if ($csv === false) { + throw new CollectorError('Could not open labels.csv for writing.', 500); + } + try { + validateOrCreateCsvHeader($csv); + + $csvChecked = false; + if (is_file($marker)) { + $csvChecked = true; + if (csvContainsFilename($csv, $relative)) { + return ['stored' => false, 'hash' => $hash, 'filename' => $relative]; + } + if (!@unlink($marker)) { + throw new CollectorError('Could not repair stale panel sample state.', 500); + } + } + + if (is_file($imagePath)) { + $existingHash = @hash_file('sha256', $imagePath); + if (!is_string($existingHash) || !hash_equals($hash, $existingHash)) { + throw new CollectorError('An existing captcha file failed its hash check.', 500); + } + if (!$csvChecked && csvContainsFilename($csv, $relative)) { + writeAtomic($marker, "saved\n"); + return ['stored' => false, 'hash' => $hash, 'filename' => $relative]; + } + } else { + writeAtomic($imagePath, $challenge['image']); + } + + appendCsvRow($csv, [$relative, $label, 'panel', '1', $hash]); + writeAtomic($marker, "saved\n"); + } finally { + fclose($csv); + } + } finally { + flock($lock, LOCK_UN); + fclose($lock); + } + + return ['stored' => true, 'hash' => $hash, 'filename' => $relative]; +} diff --git a/web/index.php b/web/index.php index 8eb24a7..0fe9ee0 100644 --- a/web/index.php +++ b/web/index.php @@ -2,1619 +2,219 @@ declare(strict_types=1); -const CSV_COLUMNS = ['filename', 'label', 'batch_id', 'verified', 'hash']; -const SCHEMA_VERSION = '1'; -const IMPORT_BATCH_SIZE = 20000; +require_once __DIR__ . '/collector.php'; -final class AppError extends RuntimeException -{ - public function __construct( - string $message, - public readonly int $status = 400, - ) { - parent::__construct($message); - } -} +ini_set('session.use_strict_mode', '1'); +ini_set('session.use_only_cookies', '1'); +ini_set('session.cookie_httponly', '1'); +ini_set('session.cookie_samesite', 'Lax'); +ini_set( + 'session.cookie_secure', + (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? '1' : '0', +); +session_name('OCR_PANEL_COLLECTOR'); +session_start(); -function config(): array -{ - $configuredDataset = $_SERVER['OCR_DATASET_DIR'] ?? getenv('OCR_DATASET_DIR') ?: ''; - $dataset = $configuredDataset !== '' - ? $configuredDataset - : dirname(__DIR__) . DIRECTORY_SEPARATOR . 'dataset'; - $dataset = rtrim($dataset, DIRECTORY_SEPARATOR); +sendSecurityHeaders(); - $configuredState = $_SERVER['OCR_STATE_PATH'] ?? getenv('OCR_STATE_PATH') ?: ''; +$config = collectorConfig(); +$method = strtoupper((string) ($_SERVER['REQUEST_METHOD'] ?? 'GET')); +$action = scalarRequestValue('action', 32) ?? ''; - return [ - 'dataset' => $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); +try { + if ($method === 'GET' && $action === 'captcha') { + servePendingCaptcha(); } - return [ - 'size' => (string) $stats['size'], - 'mtime' => (string) $stats['mtime'], - 'inode' => (string) $stats['ino'], - ]; -} + if ($method === 'POST') { + requireLocalCsrf(); -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); + if ($action === 'submit') { + $answer = normalizeAnswer(scalarPostValue('label', 16) ?? ''); + $challengeId = scalarPostValue('challenge_id', 64) ?? ''; + $result = validatePendingChallenge($config, $challengeId, $answer); + $outcome = ($result['rejected'] ?? false) + ? 'rejected' + : ($result['stored'] ? 'saved' : 'duplicate'); + $_SESSION['saved_this_session'] = (int) ($_SESSION['saved_this_session'] ?? 0) + + ($result['stored'] ? 1 : 0); + respondWithNextChallenge($config, $outcome); } + + if ($action === 'next') { + unset($_SESSION['panel_challenge']); + respondWithNextChallenge($config, 'skipped'); + } + + throw new CollectorError('Unknown action.', 404); } + if ($method !== 'GET') { + header('Allow: GET, POST'); + throw new CollectorError('Method not allowed.', 405); + } + + $challenge = null; + $error = null; try { - $db = new PDO('sqlite:' . $state, null, null, [ - PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, - PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, + $challenge = ensurePanelChallenge($config); + } catch (CollectorError $problem) { + $error = $problem->getMessage(); + } + renderCollectorPage( + $challenge, + $error, + scalarRequestValue('status', 24) ?? '', + ); +} catch (CollectorError $problem) { + if (wantsJson()) { + $payload = ['error' => $problem->getMessage()]; + if (!challengeIsUsable($_SESSION['panel_challenge'] ?? null)) { + $payload['challenge'] = null; + } + jsonResponse($payload, $problem->status); + } + + http_response_code($problem->status); + $fallbackChallenge = challengeIsUsable($_SESSION['panel_challenge'] ?? null) + ? $_SESSION['panel_challenge'] + : null; + renderCollectorPage($fallbackChallenge, $problem->getMessage(), ''); +} catch (Throwable $problem) { + error_log((string) $problem); + if (wantsJson()) { + jsonResponse(['error' => 'Unexpected server error. Check the PHP error log.'], 500); + } + + http_response_code(500); + renderCollectorPage(null, 'Unexpected server error. Check the PHP error log.', ''); +} + +function respondWithNextChallenge(array $config, string $outcome): never +{ + $challenge = null; + $warning = null; + try { + $challenge = ensurePanelChallenge($config, true); + } catch (CollectorError $problem) { + $warning = $problem->getMessage(); + } + + if (wantsJson()) { + jsonResponse([ + 'outcome' => $outcome, + 'message' => outcomeMessage($outcome), + 'saved_this_session' => (int) ($_SESSION['saved_this_session'] ?? 0), + 'challenge' => $challenge === null ? null : challengePayload($challenge), + 'warning' => $warning, ]); - $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); } + + redirect('./?status=' . rawurlencode($outcome)); } -function createSchema(PDO $db): void +function renderCollectorPage(?array $challenge, ?string $error, string $status): never { - $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', + $notices = [ + 'saved' => 'Correct — the captcha was saved.', + 'duplicate' => 'Correct — this exact image was already saved.', + 'rejected' => 'That answer was rejected. Here is a new captcha.', + 'skipped' => 'A new captcha is ready.', ]; - 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 -{ + $notice = $error ?? ($notices[$status] ?? ''); + $noticeClass = $error === null ? '' : ' error'; + $saved = (int) ($_SESSION['saved_this_session'] ?? 0); + $csrf = localCsrfToken(); ?> - - - - - <?= h($title) ?> · OCR verifier - + + + Panel captcha collector + + - +
+
+

OCR dataset

+

Captcha collector

+
+
+ + saved this session +
+
-function renderFooter(): void -{ - ?> +

+ >

+ +
+ +
+

No captcha is available

+

The panel could not provide a usable challenge. Check the message above and try again.

+ Try again +
+ +
+ Security code to transcribe +
+ +
+ + + + +
+ + +
+
+ +
+ + + +
+ +
+ +

+ Answers are stored only after the panel confirms a successful login. +

+ + -
-
-
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();