feat: add panel-validated CAPTCHA dataset collector

- validate labels through real panel login attempts
  - append confirmed samples safely to the OCR dataset
  - add dependency-free mobile-friendly collector UI
  - support Persian and Arabic digit normalization
  - fix PHP 8.5 captcha image corruption
  - add integration tests and documentation
This commit is contained in:
Meghdad committed 2026-07-28 03:52:28 +03:30
1 parent d5e974957e
commit 64b481bdb0
6 files changed
+1616 -1859

No files matched your search

+39 -49
View File
@@ -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.
+344 -224
View File
@@ -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 = (
'<form><input type="hidden" name="csrf_token" '
f'value="{csrf}"></form>'
).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"<script>(.*?)</script>", 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__":
+249
View File
@@ -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;
}
}
+117
View File
@@ -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();
})();
+681
View File
@@ -0,0 +1,681 @@
<?php
declare(strict_types=1);
const DATASET_COLUMNS = ['filename', 'label', 'batch_id', 'verified', 'hash'];
const MAX_PANEL_RESPONSE_BYTES = 2_000_000;
const CHALLENGE_MAX_AGE = 240;
final class CollectorError extends RuntimeException
{
public function __construct(
string $message,
public readonly int $status = 400,
) {
parent::__construct($message);
}
}
final class PanelResponse
{
/**
* @param array<string, list<string>> $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<string> */
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<string> $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 = [
'/<input\b[^>]*\bname=(["\'])csrf_token\1[^>]*\bvalue=(["\'])(.*?)\2[^>]*>/is',
'/<input\b[^>]*\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];
}
+186 -1586
View File
File diff suppressed because it is too large. Load diff