Spaces:
Sleeping
Sleeping
Aaron commited on
Commit ·
c8de355
1
Parent(s): d9106f7
Add ONNX-exported local_trained enhancer (onnxruntime, no torch needed)
Browse filesFiles changed (4)
123version https://git-lfs.github.com/spec/v1oid sha256:2e9c30372ee86e869d9e150f4c50d8a2e2b0217a8acec4453097201047fa9c87size 42901812345677 unmodified lines151617181920212223242 unmodified lines272829303132334 unmodified lines38394041424346 unmodified lines909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281298 unmodified lines1381391401411421431441 unmodified line146147148149150"""Locally-trained drawing restoration provider.=============================================A small residual CNN (~250k parameters) trained IN THIS REPO on syntheticdegradations of the project's own clean drawing renders — yellowing, stains,uneven lighting, stroke fading, blur, noise (seetraining/synthetic_degradation.py, modelled on the real 1970s samples).7 unmodified lineslocal_enhancer.pth, <1 MB), so it works on a fresh clone with zero network:it is the designated learned-model fallback when downloads are impossible.Train / retrain with:./venv/Scripts/python.exe training/train_local_enhancer.pyHonest scope: a 250k-parameter patch model is not Real-ESRGAN. It learns the*global* degradations well (de-yellowing, stain suppression, contrastrecovery, preserving coloured pencil marks) but does not hallucinate loststroke detail the way a 17M-parameter GAN can. Measure before preferring it.2 unmodified linesfrom __future__ import annotationsimport loggingimport osfrom pathlib import Pathfrom typing import Optional4 unmodified lineslogger = logging.getLogger(__name__)WEIGHTS_PATH = Path(__file__).resolve().parent.parent.parent / "models" / "local_enhancer.pth"_TORCH_AVAILABLE = False_TORCH_ERROR: Optional[str] = None46 unmodified lines"learned fallback for machines whose proxy blocks model downloads.")_shared_net = None@propertydef is_available(self) -> bool:return _TORCH_AVAILABLE and WEIGHTS_PATH.exists()@propertydef unavailable_reason(self) -> Optional[str]:if not _TORCH_AVAILABLE:return _TORCH_ERRORif not WEIGHTS_PATH.exists():return (f"weights not found at {WEIGHTS_PATH} — run ""training/train_local_enhancer.py to train them")return Nonedef enhance(self, image: np.ndarray) -> np.ndarray:import cv2try:net = self._get_net()if len(image.shape) == 2:bgr = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)else:bgr = imagex = torch.from_numpy(bgr.astype(np.float32) / 255.0).permute(2, 0, 1).unsqueeze(0)with torch.no_grad():y = net(x)restored = (y.squeeze(0).permute(1, 2, 0).numpy() * 255.0).clip(0, 255).astype(np.uint8)# Light classical finish: the CNN handles colour/stain/fade# correction; a mild sharpen crisps line edges for downstream8 unmodified linesfrom processors.image_enhancer import ImageEnhancerreturn ImageEnhancer().enhance(image)def _get_net(self):if LocalTrainedProvider._shared_net is None:net = LocalEnhancerNet()state = torch.load(WEIGHTS_PATH, map_location="cpu", weights_only=True)1 unmodified linenet.eval()LocalTrainedProvider._shared_net = netn = sum(p.numel() for p in net.parameters())logger.info("local_trained model loaded (%d params)", n)return LocalTrainedProvider._shared_net12345677 unmodified lines15161718192021222324252627282930313233343536373839402 unmodified lines4344454647484 unmodified lines53545556575859606162636465666746 unmodified lines1141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551568 unmodified lines1651661671681691701711721731741751761771781791 unmodified line181182183184185186"""Locally-trained drawing restoration provider.=============================================A small residual CNN (107k parameters) trained IN THIS REPO on syntheticdegradations of the project's own clean drawing renders — yellowing, stains,uneven lighting, stroke fading, blur, noise (seetraining/synthetic_degradation.py, modelled on the real 1970s samples).7 unmodified lineslocal_enhancer.pth, <1 MB), so it works on a fresh clone with zero network:it is the designated learned-model fallback when downloads are impossible.Inference vs. training dependencies — read this before changing imports-------------------------------------------------------------------------Training needs the full PyTorch stack (torch/basicsr/realesrgan) — far tooheavy for the free HF Space tier, which is why local_trained was previouslycloud-unavailable despite being the smallest model in the registry. But*inference* of a 107k-parameter conv net needs nothing but the forward pass,so this provider runs on **onnxruntime** (~15 MB, no torch) viabackend/models/local_enhancer.onnx — exported with training/export_onnx.py,parity-checked against the PyTorch model there (max abs diff 3e-6). This iswhat makes local_trained deployable on the Space; onnxruntime is listed inrequirements.cloud.txt, torch is not.torch remains an optional fallback below (dev machines that retrained buthaven't re-exported yet) — never the cloud path.Train / export with:./venv/Scripts/python.exe training/train_local_enhancer.py./venv/Scripts/python.exe training/export_onnx.py --verifyHonest scope: a 107k-parameter patch model is not Real-ESRGAN. It learns the*global* degradations well (de-yellowing, stain suppression, contrastrecovery, preserving coloured pencil marks) but does not hallucinate loststroke detail the way a 17M-parameter GAN can. Measure before preferring it.2 unmodified linesfrom __future__ import annotationsimport loggingfrom pathlib import Pathfrom typing import Optional4 unmodified lineslogger = logging.getLogger(__name__)WEIGHTS_PATH = Path(__file__).resolve().parent.parent.parent / "models" / "local_enhancer.pth"ONNX_PATH = WEIGHTS_PATH.with_suffix(".onnx")_ONNX_AVAILABLE = False_ONNX_ERROR: Optional[str] = Nonetry:import onnxruntime as ort_ONNX_AVAILABLE = Trueexcept ImportError as _e: # pragma: no cover_ONNX_ERROR = f"onnxruntime not installed: {_e}"_TORCH_AVAILABLE = False_TORCH_ERROR: Optional[str] = None46 unmodified lines"learned fallback for machines whose proxy blocks model downloads.")_shared_session = None # onnxruntime.InferenceSession_shared_net = None # torch fallback@propertydef is_available(self) -> bool:if _ONNX_AVAILABLE and ONNX_PATH.exists():return Truereturn _TORCH_AVAILABLE and WEIGHTS_PATH.exists()@propertydef unavailable_reason(self) -> Optional[str]:if self.is_available:return Noneif not _ONNX_AVAILABLE and not _TORCH_AVAILABLE:return f"{_ONNX_ERROR}; {_TORCH_ERROR}"if not WEIGHTS_PATH.exists() and not ONNX_PATH.exists():return (f"weights not found at {WEIGHTS_PATH} or {ONNX_PATH} — run ""training/train_local_enhancer.py then training/export_onnx.py")return _ONNX_ERROR or _TORCH_ERRORdef enhance(self, image: np.ndarray) -> np.ndarray:import cv2try:if len(image.shape) == 2:bgr = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)else:bgr = imagex = (bgr.astype(np.float32) / 255.0).transpose(2, 0, 1)[None]if _ONNX_AVAILABLE and ONNX_PATH.exists():y = self._get_onnx_session().run(None, {"image": x})[0]else:y = self._run_torch(x)restored = (y[0].transpose(1, 2, 0) * 255.0).clip(0, 255).astype(np.uint8)# Light classical finish: the CNN handles colour/stain/fade# correction; a mild sharpen crisps line edges for downstream8 unmodified linesfrom processors.image_enhancer import ImageEnhancerreturn ImageEnhancer().enhance(image)def _get_onnx_session(self):if LocalTrainedProvider._shared_session is None:LocalTrainedProvider._shared_session = ort.InferenceSession(str(ONNX_PATH), providers=["CPUExecutionProvider"],)logger.info("local_trained loaded via onnxruntime (%s)", ONNX_PATH.name)return LocalTrainedProvider._shared_sessiondef _run_torch(self, x: np.ndarray) -> np.ndarray:if LocalTrainedProvider._shared_net is None:net = LocalEnhancerNet()state = torch.load(WEIGHTS_PATH, map_location="cpu", weights_only=True)1 unmodified linenet.eval()LocalTrainedProvider._shared_net = netn = sum(p.numel() for p in net.parameters())logger.info("local_trained loaded via torch fallback (%d params)", n)with torch.no_grad():return LocalTrainedProvider._shared_net(torch.from_numpy(x)).numpy()
1234567891011# Cloud deployment — excludes torch/Real-ESRGAN/PaddleOCR (too large for the# free cpu-basic Space tier). Real-ESRGAN, local_trained, and ocr_ensemble# are local-only providers; the cloud deployment falls back gracefully# (registry reports them unavailable) exactly as it already does for the# `huggingface` provider — see processors/enhancement/registry.py.fastapi==0.115.0uvicorn[standard]==0.30.6python-multipart==0.0.9# contrib (not headless-only opencv) adds cv2.ximgproc — needed for the# line_model="fld" FastLineDetector option. Same version, still headless# (no GUI deps), negligible size difference over plain opencv-python-headless.1234567891011121314151617# Cloud deployment — excludes torch/basicsr/realesrgan/PaddleOCR (too large# for the free cpu-basic Space tier). Real-ESRGAN and ocr_ensemble remain# local-only providers; the cloud deployment falls back gracefully (registry# reports them unavailable) exactly as it already does for the `huggingface`# provider — see processors/enhancement/registry.py.fastapi==0.115.0uvicorn[standard]==0.30.6python-multipart==0.0.9# local_trained (107k-param trained-in-repo CNN) runs via onnxruntime at# inference time instead of torch — ~15 MB vs. torch's several-hundred-MB# footprint, so it's the one learned enhancement provider that DOES reach# the cloud Space. See processors/enhancement/local_trained.py and# training/export_onnx.py for the torch-training / onnx-inference split.onnxruntime>=1.20.0# contrib (not headless-only opencv) adds cv2.ximgproc — needed for the# line_model="fld" FastLineDetector option. Same version, still headless# (no GUI deps), negligible size difference over plain opencv-python-headless.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106"""Export the trained local enhancer to ONNX.===========================================Decouples inference from training: LocalEnhancerNet is trained withPyTorch (training/train_local_enhancer.py, needs torch/basicsr/realesrgan —too heavy for the free HF Space tier), but at only 107k parameters, inferencealone needs nothing but onnxruntime (~15 MB, no torch). Exporting to ONNX iswhat makes local_trained deployable on the cloud Space instead of dev-only.
processors/enhancement/local_trained.py loads the .onnx file viaonnxruntime.InferenceSession — see that module for the inference side.
Usage----- cd backend ./venv/Scripts/python.exe training/export_onnx.py ./venv/Scripts/python.exe training/export_onnx.py --verify # also checks # torch vs onnx # output parity"""
from __future__ import annotations
import argparseimport sysfrom pathlib import Path
ROOT = Path(__file__).resolve().parent.parentsys.path.insert(0, str(ROOT))
import numpy as npimport torch
from processors.enhancement.local_trained import LocalEnhancerNet, WEIGHTS_PATH
ONNX_PATH = WEIGHTS_PATH.with_suffix(".onnx")
def export(pth_path: Path = WEIGHTS_PATH, onnx_path: Path = ONNX_PATH) -> None: net = LocalEnhancerNet() state = torch.load(pth_path, map_location="cpu", weights_only=True) net.load_state_dict(state) net.eval()
# Dynamic H/W: the network is fully convolutional, so export with dynamic # axes rather than baking in one input resolution — real drawings vary. dummy = torch.zeros(1, 3, 64, 64) torch.onnx.export( net, dummy, str(onnx_path), input_names=["image"], output_names=["restored"], dynamic_axes={ "image": {0: "batch", 2: "height", 3: "width"}, "restored": {0: "batch", 2: "height", 3: "width"}, }, opset_version=17, # Force the legacy TorchScript-based exporter: torch 2.x's newer # "dynamo" exporter splits weights into a companion .onnx.data file # by default, which is fine for large models but just adds a second # file to ship/find at this model's size (425 KB) — the legacy path # embeds weights directly in the single .onnx file. dynamo=False, ) size_kb = onnx_path.stat().st_size / 1024 print(f"exported {onnx_path} ({size_kb:.0f} KB)")
def verify(pth_path: Path = WEIGHTS_PATH, onnx_path: Path = ONNX_PATH) -> None: """Confirm the ONNX graph produces the same output as the PyTorch model (within floating-point tolerance) on a real image, not just random noise — a graph bug can hide in dynamic-shape handling that random data won't exercise the same way as a real photograph's statistics.""" import cv2 import onnxruntime as ort
net = LocalEnhancerNet() net.load_state_dict(torch.load(pth_path, map_location="cpu", weights_only=True)) net.eval()
img = cv2.imread(str(ROOT / "benchmark/real_samples/real_faded_1.jpg"), cv2.IMREAD_COLOR) img = cv2.resize(img, (512, 384)) # non-square, catches H/W axis swaps x_np = (img.astype(np.float32) / 255.0).transpose(2, 0, 1)[None]
with torch.no_grad(): torch_out = net(torch.from_numpy(x_np)).numpy()
session = ort.InferenceSession(str(onnx_path), providers=["CPUExecutionProvider"]) onnx_out = session.run(None, {"image": x_np})[0]
max_diff = float(np.abs(torch_out - onnx_out).max()) mean_diff = float(np.abs(torch_out - onnx_out).mean()) print(f"max abs diff: {max_diff:.6f} | mean abs diff: {mean_diff:.6f}") if max_diff > 1e-3: raise SystemExit(f"PARITY CHECK FAILED — max diff {max_diff} exceeds 1e-3 tolerance") print("PARITY OK — torch and onnxruntime outputs match")
if __name__ == "__main__": ap = argparse.ArgumentParser(description=__doc__) ap.add_argument("--verify", action="store_true", help="also check torch/onnx output parity") args = ap.parse_args() export() if args.verify: verify()models/local_enhancer.onnxAdded+3
processors/enhancement/local_trained.py+59-23
requirements.cloud.txt+11-5
training/export_onnx.pyAdded+106