feat: add PHP web interface for OCR label verification
This commit is contained in:
3 files changed
+1616
No files matched your search
@@ -100,3 +100,86 @@ Use `--reverify` to review them and `--start N` to begin after row `N`.
|
|||||||
The verifier builds a complete temporary CSV and atomically replaces the original
|
The verifier builds a complete temporary CSV and atomically replaces the original
|
||||||
when you quit, so the CSV cannot be left half-written. If it is interrupted while
|
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.
|
copying or displaying rather than at the prompt, the original CSV remains unchanged.
|
||||||
|
|
||||||
|
## 5. Verify labels in a web browser
|
||||||
|
|
||||||
|
The PHP verifier provides the same sequential labeling workflow without Kitty,
|
||||||
|
Python packages, Composer, or a framework. It requires PHP 8.1 or newer with
|
||||||
|
PDO SQLite and Fileinfo enabled.
|
||||||
|
|
||||||
|
Start it locally from the repository root:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
php -S 127.0.0.1:8080 -t web
|
||||||
|
```
|
||||||
|
|
||||||
|
Then open `http://127.0.0.1:8080`. On the first visit, click **Initialize
|
||||||
|
verifier**. The browser incrementally imports `dataset/labels.csv` into
|
||||||
|
`dataset/verification.sqlite`; progress is resumable if the page or server is
|
||||||
|
stopped.
|
||||||
|
|
||||||
|
Each accepted label is immediately committed to SQLite. ASCII, Persian, and
|
||||||
|
Arabic digits are accepted and normalized to ASCII. Enter saves and advances;
|
||||||
|
an empty Enter or **Skip for now** leaves the row unverified and advances. Recent
|
||||||
|
labels can be opened and corrected without moving the main queue.
|
||||||
|
|
||||||
|
The page deliberately does not rewrite the large CSV after every answer. The
|
||||||
|
header shows how many rows have not yet been copied back. Click **Sync
|
||||||
|
labels.csv** before training, copying the dataset, or using another Python tool.
|
||||||
|
Sync writes a complete neighboring temporary file and atomically replaces
|
||||||
|
`labels.csv`; a failed write leaves the existing CSV unchanged.
|
||||||
|
|
||||||
|
Do not run `verify_labels.py`, the downloader, or another process that changes
|
||||||
|
`labels.csv` while the web verifier is active. The page detects an external CSV
|
||||||
|
change and stops rather than overwriting it. To move the dataset to another
|
||||||
|
machine, sync first and copy the dataset normally; the destination can rebuild
|
||||||
|
its SQLite state from the synced CSV.
|
||||||
|
|
||||||
|
### Use another dataset directory
|
||||||
|
|
||||||
|
The default dataset is the repository's `dataset/` directory. Set
|
||||||
|
`OCR_DATASET_DIR` to use another location:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
OCR_DATASET_DIR=/data/persian-ocr \
|
||||||
|
php -S 127.0.0.1:8080 -t web
|
||||||
|
```
|
||||||
|
|
||||||
|
`OCR_STATE_PATH` can optionally place `verification.sqlite` elsewhere. The PHP
|
||||||
|
process must be able to read the CSV and images and write the SQLite database,
|
||||||
|
its lock/WAL files, and temporary CSV files. Grant the PHP-FPM user ownership or
|
||||||
|
a targeted ACL; do not make the directory world-writable.
|
||||||
|
|
||||||
|
### Minimal Nginx configuration
|
||||||
|
|
||||||
|
Use `web/` as the public document root so the CSV, SQLite state, images, and
|
||||||
|
Python source files are not directly downloadable. The page safely streams the
|
||||||
|
selected image itself.
|
||||||
|
|
||||||
|
```nginx
|
||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name verifier.example.internal;
|
||||||
|
root /srv/tci-ocr/web;
|
||||||
|
index index.php;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
try_files $uri /index.php?$query_string;
|
||||||
|
}
|
||||||
|
|
||||||
|
location = /index.php {
|
||||||
|
include fastcgi_params;
|
||||||
|
fastcgi_param SCRIPT_FILENAME $document_root/index.php;
|
||||||
|
fastcgi_param OCR_DATASET_DIR /srv/tci-ocr/dataset;
|
||||||
|
fastcgi_pass unix:/run/php/php8.3-fpm.sock;
|
||||||
|
}
|
||||||
|
|
||||||
|
location ~ \.php$ {
|
||||||
|
return 404;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Adjust the PHP-FPM socket and paths for the server. The application intentionally
|
||||||
|
contains no authentication; add Nginx basic authentication to the `server` or
|
||||||
|
`location /` block, or expose it only on a private network.
|
||||||
@@ -1,12 +1,21 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
import csv
|
import csv
|
||||||
import hashlib
|
import hashlib
|
||||||
import os
|
import os
|
||||||
|
import re
|
||||||
|
import shutil
|
||||||
|
import socket
|
||||||
|
import sqlite3
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
import tempfile
|
import tempfile
|
||||||
|
import time
|
||||||
import unittest
|
import unittest
|
||||||
|
import urllib.error
|
||||||
|
import urllib.parse
|
||||||
|
import urllib.request
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
@@ -194,6 +203,232 @@ class ToolTests(unittest.TestCase):
|
|||||||
self.assertTrue(original_one.is_file())
|
self.assertTrue(original_one.is_file())
|
||||||
self.assertTrue(original_two.is_file())
|
self.assertTrue(original_two.is_file())
|
||||||
|
|
||||||
|
def test_php_web_verifier_initializes_saves_skips_edits_and_syncs(self):
|
||||||
|
php = shutil.which("php")
|
||||||
|
if php is None:
|
||||||
|
self.skipTest("PHP is not installed")
|
||||||
|
sqlite_support = subprocess.run(
|
||||||
|
[php, "-r", "exit(extension_loaded('pdo_sqlite') ? 0 : 1);"]
|
||||||
|
)
|
||||||
|
if sqlite_support.returncode != 0:
|
||||||
|
self.skipTest("PHP PDO SQLite is not installed")
|
||||||
|
|
||||||
|
with tempfile.TemporaryDirectory() as temp:
|
||||||
|
root = Path(temp)
|
||||||
|
dataset = root / "dataset"
|
||||||
|
image = dataset / "images" / "000000" / "000000000.png"
|
||||||
|
image.parent.mkdir(parents=True)
|
||||||
|
web_png = base64.b64decode(
|
||||||
|
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwC"
|
||||||
|
"AAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="
|
||||||
|
)
|
||||||
|
image.write_bytes(web_png)
|
||||||
|
outside_image = root / "outside.png"
|
||||||
|
outside_image.write_bytes(web_png)
|
||||||
|
csv_path = dataset / "labels.csv"
|
||||||
|
with csv_path.open("w", newline="", encoding="utf-8") as output:
|
||||||
|
writer = csv.DictWriter(
|
||||||
|
output,
|
||||||
|
fieldnames=["filename", "label", "batch_id", "verified", "hash"],
|
||||||
|
)
|
||||||
|
writer.writeheader()
|
||||||
|
for index, (label, verified) in enumerate(
|
||||||
|
[("123", "1"), ("", "0"), ("", "0")]
|
||||||
|
):
|
||||||
|
writer.writerow(
|
||||||
|
{
|
||||||
|
"filename": (
|
||||||
|
"../outside.png"
|
||||||
|
if index == 2
|
||||||
|
else image.relative_to(dataset).as_posix()
|
||||||
|
),
|
||||||
|
"label": label,
|
||||||
|
"batch_id": "0",
|
||||||
|
"verified": verified,
|
||||||
|
"hash": hashlib.sha256(web_png + str(index).encode()).hexdigest(),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
with socket.socket() as listener:
|
||||||
|
listener.bind(("127.0.0.1", 0))
|
||||||
|
port = listener.getsockname()[1]
|
||||||
|
|
||||||
|
environment = os.environ.copy()
|
||||||
|
environment["OCR_DATASET_DIR"] = str(dataset)
|
||||||
|
server = subprocess.Popen(
|
||||||
|
[
|
||||||
|
php,
|
||||||
|
"-S",
|
||||||
|
f"127.0.0.1:{port}",
|
||||||
|
"-t",
|
||||||
|
str(PROJECT / "web"),
|
||||||
|
],
|
||||||
|
stdout=subprocess.DEVNULL,
|
||||||
|
stderr=subprocess.PIPE,
|
||||||
|
text=True,
|
||||||
|
env=environment,
|
||||||
|
)
|
||||||
|
base_url = f"http://127.0.0.1:{port}/"
|
||||||
|
|
||||||
|
def get(path: str = "") -> tuple[int, bytes, dict[str, str]]:
|
||||||
|
request = urllib.request.Request(base_url + path)
|
||||||
|
with urllib.request.urlopen(request, timeout=10) as response:
|
||||||
|
return response.status, response.read(), dict(response.headers)
|
||||||
|
|
||||||
|
def post(values: dict[str, str]) -> tuple[int, bytes, dict[str, str]]:
|
||||||
|
body = urllib.parse.urlencode(values).encode()
|
||||||
|
request = urllib.request.Request(base_url, data=body, method="POST")
|
||||||
|
with urllib.request.urlopen(request, timeout=20) as response:
|
||||||
|
return response.status, response.read(), dict(response.headers)
|
||||||
|
|
||||||
|
try:
|
||||||
|
for _ in range(50):
|
||||||
|
try:
|
||||||
|
status, page, _ = get()
|
||||||
|
if status == 200:
|
||||||
|
break
|
||||||
|
except urllib.error.URLError:
|
||||||
|
time.sleep(0.05)
|
||||||
|
else:
|
||||||
|
self.fail("PHP development server did not start")
|
||||||
|
|
||||||
|
self.assertIn(b"Initialize verifier", page)
|
||||||
|
status, payload, _ = post({"action": "initialize"})
|
||||||
|
self.assertEqual(status, 200)
|
||||||
|
self.assertIn(b'"done":true', payload)
|
||||||
|
|
||||||
|
_, page, _ = get()
|
||||||
|
self.assertIn(b'OCR verifier', page)
|
||||||
|
self.assertRegex(page, rb'name="row_id" value="1"')
|
||||||
|
self.assertRegex(page, rb'name="revision" value="0"')
|
||||||
|
|
||||||
|
status, image_body, headers = get("?action=image&id=1")
|
||||||
|
self.assertEqual(status, 200)
|
||||||
|
self.assertEqual(image_body, web_png)
|
||||||
|
self.assertEqual(headers["Content-Type"], "image/png")
|
||||||
|
|
||||||
|
with self.assertRaises(urllib.error.HTTPError) as invalid:
|
||||||
|
post(
|
||||||
|
{
|
||||||
|
"action": "save",
|
||||||
|
"row_id": "1",
|
||||||
|
"revision": "0",
|
||||||
|
"mode": "queue",
|
||||||
|
"label": "12x",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
self.assertEqual(invalid.exception.code, 422)
|
||||||
|
self.assertIn(b"Enter digits only", invalid.exception.read())
|
||||||
|
invalid.exception.close()
|
||||||
|
|
||||||
|
_, page, _ = post(
|
||||||
|
{
|
||||||
|
"action": "save",
|
||||||
|
"row_id": "1",
|
||||||
|
"revision": "0",
|
||||||
|
"mode": "queue",
|
||||||
|
"label": "۱۲۳۴",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
self.assertIn(b"Label saved", page)
|
||||||
|
self.assertRegex(page, rb'name="row_id" value="2"')
|
||||||
|
self.assertRegex(page, rb'name="revision" value="1"')
|
||||||
|
|
||||||
|
with self.assertRaises(urllib.error.HTTPError) as stale:
|
||||||
|
post(
|
||||||
|
{
|
||||||
|
"action": "save",
|
||||||
|
"row_id": "1",
|
||||||
|
"revision": "0",
|
||||||
|
"mode": "queue",
|
||||||
|
"label": "999",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
self.assertEqual(stale.exception.code, 409)
|
||||||
|
self.assertIn(b"stale", stale.exception.read())
|
||||||
|
stale.exception.close()
|
||||||
|
|
||||||
|
with self.assertRaises(urllib.error.HTTPError) as escaped_image:
|
||||||
|
get("?action=image&id=2")
|
||||||
|
self.assertEqual(escaped_image.exception.code, 404)
|
||||||
|
escaped_image.exception.close()
|
||||||
|
|
||||||
|
_, page, _ = post(
|
||||||
|
{
|
||||||
|
"action": "skip",
|
||||||
|
"row_id": "2",
|
||||||
|
"revision": "1",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
self.assertIn(b"Image skipped", page)
|
||||||
|
self.assertRegex(page, rb'name="row_id" value="2"')
|
||||||
|
|
||||||
|
_, edit_page, _ = get("?edit=1")
|
||||||
|
revision = re.search(rb'name="revision" value="(\d+)"', edit_page)
|
||||||
|
self.assertIsNotNone(revision)
|
||||||
|
_, corrected_page, _ = post(
|
||||||
|
{
|
||||||
|
"action": "save",
|
||||||
|
"row_id": "1",
|
||||||
|
"revision": revision.group(1).decode(),
|
||||||
|
"mode": "edit",
|
||||||
|
"label": "4567",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
self.assertIn(b"corrected", corrected_page)
|
||||||
|
|
||||||
|
state = sqlite3.connect(dataset / "verification.sqlite")
|
||||||
|
try:
|
||||||
|
saved = state.execute(
|
||||||
|
"SELECT label, verified, dirty FROM labels WHERE id = 1"
|
||||||
|
).fetchone()
|
||||||
|
pending = state.execute(
|
||||||
|
"SELECT value FROM metadata WHERE key = 'pending_count'"
|
||||||
|
).fetchone()
|
||||||
|
finally:
|
||||||
|
state.close()
|
||||||
|
self.assertEqual(saved, ("4567", 1, 1))
|
||||||
|
self.assertEqual(pending, ("1",))
|
||||||
|
|
||||||
|
_, synced_page, _ = post({"action": "sync"})
|
||||||
|
self.assertIn(b"updated atomically", synced_page)
|
||||||
|
with csv_path.open(newline="", encoding="utf-8") as source:
|
||||||
|
rows = list(csv.DictReader(source))
|
||||||
|
self.assertEqual(rows[1]["label"], "4567")
|
||||||
|
self.assertEqual(rows[1]["verified"], "1")
|
||||||
|
self.assertEqual(rows[2]["verified"], "0")
|
||||||
|
|
||||||
|
state = sqlite3.connect(dataset / "verification.sqlite")
|
||||||
|
try:
|
||||||
|
pending = state.execute(
|
||||||
|
"SELECT value FROM metadata WHERE key = 'pending_count'"
|
||||||
|
).fetchone()
|
||||||
|
finally:
|
||||||
|
state.close()
|
||||||
|
self.assertEqual(pending, ("0",))
|
||||||
|
|
||||||
|
with self.assertRaises(urllib.error.HTTPError) as missing:
|
||||||
|
get("?action=image&id=999")
|
||||||
|
self.assertEqual(missing.exception.code, 404)
|
||||||
|
missing.exception.close()
|
||||||
|
|
||||||
|
with csv_path.open("a", encoding="utf-8") as output:
|
||||||
|
output.write("\n")
|
||||||
|
with self.assertRaises(urllib.error.HTTPError) as conflict:
|
||||||
|
get()
|
||||||
|
self.assertEqual(conflict.exception.code, 409)
|
||||||
|
self.assertIn(b"The source CSV changed", conflict.exception.read())
|
||||||
|
conflict.exception.close()
|
||||||
|
finally:
|
||||||
|
server.terminate()
|
||||||
|
try:
|
||||||
|
server.wait(timeout=5)
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
server.kill()
|
||||||
|
server.wait(timeout=5)
|
||||||
|
if server.stderr is not None:
|
||||||
|
server.stderr.close()
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
+1298
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user