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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Train KYC Document Rotation Classifier - CPU Only
|
| 4 |
+
=================================================
|
| 5 |
+
|
| 6 |
+
This script trains a lightweight MobileNetV3-Small classifier
|
| 7 |
+
to detect document rotation: 0Β°, 90Β°, 180Β°, 270Β°.
|
| 8 |
+
|
| 9 |
+
Requirements:
|
| 10 |
+
pip install torch torchvision pillow numpy huggingface_hub tqdm
|
| 11 |
+
|
| 12 |
+
Usage:
|
| 13 |
+
python train_rotation_classifier.py
|
| 14 |
+
|
| 15 |
+
Dataset: Jwalit/moire-docs (will download automatically)
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
import os
|
| 19 |
+
import json
|
| 20 |
+
import random
|
| 21 |
+
import warnings
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
|
| 24 |
+
import numpy as np
|
| 25 |
+
from PIL import Image
|
| 26 |
+
|
| 27 |
+
import torch
|
| 28 |
+
import torch.nn as nn
|
| 29 |
+
from torch.utils.data import Dataset, DataLoader
|
| 30 |
+
from torchvision import transforms, models
|
| 31 |
+
from torchvision.transforms import functional as TF
|
| 32 |
+
|
| 33 |
+
from huggingface_hub import hf_hub_download, HfApi, create_repo
|
| 34 |
+
from tqdm import tqdm
|
| 35 |
+
|
| 36 |
+
warnings.filterwarnings("ignore")
|
| 37 |
+
|
| 38 |
+
# ββ Configuration βββββββββββββββββββββββββ
|
| 39 |
+
DATASET_REPO = "Jwalit/moire-docs"
|
| 40 |
+
LOCAL_DIR = Path("./moire-docs")
|
| 41 |
+
BATCH_SIZE = 16
|
| 42 |
+
EPOCHS = 15
|
| 43 |
+
LR = 1e-4
|
| 44 |
+
IMG_SIZE = 224
|
| 45 |
+
DEVICE = torch.device("cpu")
|
| 46 |
+
MAX_IMAGES = 1500
|
| 47 |
+
SEED = 42
|
| 48 |
+
|
| 49 |
+
random.seed(SEED)
|
| 50 |
+
np.random.seed(SEED)
|
| 51 |
+
torch.manual_seed(SEED)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
# ββ Download Dataset ββββββββββββββββββββββ
|
| 55 |
+
def download_dataset():
|
| 56 |
+
"""Download images from Jwalit/moire-docs."""
|
| 57 |
+
LOCAL_DIR.mkdir(parents=True, exist_ok=True)
|
| 58 |
+
api = HfApi()
|
| 59 |
+
files = api.list_repo_files(DATASET_REPO, repo_type="dataset")
|
| 60 |
+
image_files = [f for f in files if f.lower().endswith(('.jpg', '.jpeg', '.png'))]
|
| 61 |
+
image_files = [f for f in image_files if '.ipynb' not in f]
|
| 62 |
+
random.shuffle(image_files)
|
| 63 |
+
image_files = image_files[:MAX_IMAGES]
|
| 64 |
+
|
| 65 |
+
print(f"Downloading {len(image_files)} images...")
|
| 66 |
+
for rel_path in tqdm(image_files, desc="Download"):
|
| 67 |
+
try:
|
| 68 |
+
hf_hub_download(
|
| 69 |
+
repo_id=DATASET_REPO,
|
| 70 |
+
filename=rel_path,
|
| 71 |
+
repo_type="dataset",
|
| 72 |
+
local_dir=LOCAL_DIR,
|
| 73 |
+
)
|
| 74 |
+
except Exception:
|
| 75 |
+
pass
|
| 76 |
+
|
| 77 |
+
# Collect downloaded images
|
| 78 |
+
exts = ('.jpg', '.jpeg', '.png')
|
| 79 |
+
imgs = [p for e in exts for p in LOCAL_DIR.rglob(f'*{e}')]
|
| 80 |
+
return [p for p in imgs if '.ipynb' not in str(p)]
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
# ββ Dataset βββββββββββββββββββββββββββββββ
|
| 84 |
+
class RotationDataset(Dataset):
|
| 85 |
+
"""Self-supervised rotation dataset. Each image Γ 4 rotations."""
|
| 86 |
+
ANGLES = [0, 90, 180, 270]
|
| 87 |
+
|
| 88 |
+
def __init__(self, paths, img_size=IMG_SIZE):
|
| 89 |
+
self.paths = paths
|
| 90 |
+
self.transform = transforms.Compose([
|
| 91 |
+
transforms.Resize((img_size, img_size)),
|
| 92 |
+
transforms.ToTensor(),
|
| 93 |
+
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
|
| 94 |
+
])
|
| 95 |
+
|
| 96 |
+
def __len__(self):
|
| 97 |
+
return len(self.paths) * 4
|
| 98 |
+
|
| 99 |
+
def __getitem__(self, idx):
|
| 100 |
+
path = self.paths[idx // 4]
|
| 101 |
+
angle_idx = idx % 4
|
| 102 |
+
|
| 103 |
+
img = Image.open(path).convert('RGB')
|
| 104 |
+
img = TF.rotate(img, self.ANGLES[angle_idx])
|
| 105 |
+
|
| 106 |
+
return self.transform(img), angle_idx
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
# ββ Model βββββββββββββββββββββββββββββββββ
|
| 110 |
+
class RotationModel(nn.Module):
|
| 111 |
+
"""MobileNetV3-Small for 4-class rotation classification."""
|
| 112 |
+
|
| 113 |
+
def __init__(self):
|
| 114 |
+
super().__init__()
|
| 115 |
+
self.backbone = models.mobilenet_v3_small(
|
| 116 |
+
weights=models.MobileNet_V3_Small_Weights.IMAGENET1K_V1)
|
| 117 |
+
in_features = self.backbone.classifier[3].in_features
|
| 118 |
+
self.backbone.classifier[3] = nn.Linear(in_features, 4)
|
| 119 |
+
|
| 120 |
+
def forward(self, x):
|
| 121 |
+
return self.backbone(x)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
# ββ Training ββββββββββββββββββββββββββββββ
|
| 125 |
+
def train(model, train_loader, val_loader):
|
| 126 |
+
model.to(DEVICE)
|
| 127 |
+
optimizer = torch.optim.AdamW(model.parameters(), lr=LR, weight_decay=1e-4)
|
| 128 |
+
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=EPOCHS)
|
| 129 |
+
criterion = nn.CrossEntropyLoss()
|
| 130 |
+
|
| 131 |
+
best_acc = 0.0
|
| 132 |
+
best_state = None
|
| 133 |
+
|
| 134 |
+
for epoch in range(EPOCHS):
|
| 135 |
+
# Train
|
| 136 |
+
model.train()
|
| 137 |
+
train_loss = 0.0
|
| 138 |
+
for images, labels in tqdm(train_loader, desc=f"Epoch {epoch+1} train", leave=False):
|
| 139 |
+
images, labels = images.to(DEVICE), labels.to(DEVICE)
|
| 140 |
+
|
| 141 |
+
optimizer.zero_grad()
|
| 142 |
+
outputs = model(images)
|
| 143 |
+
loss = criterion(outputs, labels)
|
| 144 |
+
loss.backward()
|
| 145 |
+
optimizer.step()
|
| 146 |
+
|
| 147 |
+
train_loss += loss.item()
|
| 148 |
+
|
| 149 |
+
scheduler.step()
|
| 150 |
+
|
| 151 |
+
# Validate
|
| 152 |
+
model.eval()
|
| 153 |
+
val_loss = 0.0
|
| 154 |
+
correct = 0
|
| 155 |
+
total = 0
|
| 156 |
+
|
| 157 |
+
with torch.no_grad():
|
| 158 |
+
for images, labels in val_loader:
|
| 159 |
+
images, labels = images.to(DEVICE), labels.to(DEVICE)
|
| 160 |
+
outputs = model(images)
|
| 161 |
+
loss = criterion(outputs, labels)
|
| 162 |
+
val_loss += loss.item()
|
| 163 |
+
|
| 164 |
+
_, predicted = torch.max(outputs, 1)
|
| 165 |
+
correct += (predicted == labels).sum().item()
|
| 166 |
+
total += labels.size(0)
|
| 167 |
+
|
| 168 |
+
train_loss /= len(train_loader)
|
| 169 |
+
val_loss /= len(val_loader)
|
| 170 |
+
val_acc = correct / total if total > 0 else 0
|
| 171 |
+
|
| 172 |
+
print(f"Epoch {epoch+1}/{EPOCHS}: "
|
| 173 |
+
f"train_loss={train_loss:.4f} val_loss={val_loss:.4f} val_acc={val_acc:.4f}")
|
| 174 |
+
|
| 175 |
+
if val_acc > best_acc:
|
| 176 |
+
best_acc = val_acc
|
| 177 |
+
best_state = {k: v.clone() for k, v in model.state_dict().items()}
|
| 178 |
+
|
| 179 |
+
if best_state:
|
| 180 |
+
model.load_state_dict(best_state)
|
| 181 |
+
|
| 182 |
+
return model, best_acc
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
# ββ Push to Hub βββββββββββββββββββββββββββ
|
| 186 |
+
def push_model(model, accuracy):
|
| 187 |
+
output_dir = Path("./outputs")
|
| 188 |
+
output_dir.mkdir(exist_ok=True)
|
| 189 |
+
|
| 190 |
+
torch.save(model.state_dict(), output_dir / "rotation_model.bin")
|
| 191 |
+
|
| 192 |
+
with open(output_dir / "config.json", "w") as f:
|
| 193 |
+
json.dump({
|
| 194 |
+
"task": "rotation_classification",
|
| 195 |
+
"backbone": "mobilenet_v3_small",
|
| 196 |
+
"num_classes": 4,
|
| 197 |
+
"classes": ["0", "90", "180", "270"],
|
| 198 |
+
"epochs": EPOCHS,
|
| 199 |
+
"accuracy": accuracy,
|
| 200 |
+
}, f, indent=2)
|
| 201 |
+
|
| 202 |
+
repo_name = "Jwalit/kyc-document-rotation-classifier"
|
| 203 |
+
try:
|
| 204 |
+
create_repo(repo_name, repo_type="model", exist_ok=True)
|
| 205 |
+
api = HfApi()
|
| 206 |
+
api.upload_folder(folder_path=str(output_dir), repo_id=repo_name, repo_type="model")
|
| 207 |
+
print(f"\nPushed to https://huggingface.co/{repo_name}")
|
| 208 |
+
except Exception as e:
|
| 209 |
+
print(f"\nPush error: {e}")
|
| 210 |
+
print(f"Model saved locally to: {output_dir}/rotation_model.bin")
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
# ββ Main ββββββββββββββββββββββββββββββββββ
|
| 214 |
+
def main():
|
| 215 |
+
print("=" * 60)
|
| 216 |
+
print("KYC Document Rotation Classifier - CPU Training")
|
| 217 |
+
print("=" * 60)
|
| 218 |
+
|
| 219 |
+
# Download dataset
|
| 220 |
+
print("\n[1/4] Downloading dataset...")
|
| 221 |
+
images = download_dataset()
|
| 222 |
+
print(f"Total images: {len(images)}")
|
| 223 |
+
|
| 224 |
+
if len(images) < 20:
|
| 225 |
+
print("ERROR: Not enough images downloaded!")
|
| 226 |
+
return
|
| 227 |
+
|
| 228 |
+
# Split
|
| 229 |
+
random.shuffle(images)
|
| 230 |
+
n_train = int(0.85 * len(images))
|
| 231 |
+
train_images = images[:n_train]
|
| 232 |
+
val_images = images[n_train:]
|
| 233 |
+
print(f"Train: {len(train_images)}, Val: {len(val_images)}")
|
| 234 |
+
|
| 235 |
+
# DataLoaders
|
| 236 |
+
print("\n[2/4] Creating datasets...")
|
| 237 |
+
train_dataset = RotationDataset(train_images)
|
| 238 |
+
val_dataset = RotationDataset(val_images)
|
| 239 |
+
train_loader = DataLoader(train_dataset, batch_size=BATCH_SIZE, shuffle=True)
|
| 240 |
+
val_loader = DataLoader(val_dataset, batch_size=BATCH_SIZE)
|
| 241 |
+
print(f"Train samples: {len(train_dataset)}, Val samples: {len(val_dataset)}")
|
| 242 |
+
|
| 243 |
+
# Train
|
| 244 |
+
print("\n[3/4] Training model...")
|
| 245 |
+
model = RotationModel()
|
| 246 |
+
model, best_acc = train(model, train_loader, val_loader)
|
| 247 |
+
print(f"\nBest validation accuracy: {best_acc:.2%}")
|
| 248 |
+
|
| 249 |
+
# Push
|
| 250 |
+
print("\n[4/4] Pushing to Hugging Face Hub...")
|
| 251 |
+
push_model(model, best_acc)
|
| 252 |
+
|
| 253 |
+
print("\n" + "=" * 60)
|
| 254 |
+
print("Training complete!")
|
| 255 |
+
print("=" * 60)
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
if __name__ == "__main__":
|
| 259 |
+
main()
|