diff --git a/comic-translate-ai/main/comic_translator_pipeline.py b/comic-translate-ai/main/comic_translator_pipeline.py index 6307fab..576ac34 100644 --- a/comic-translate-ai/main/comic_translator_pipeline.py +++ b/comic-translate-ai/main/comic_translator_pipeline.py @@ -101,7 +101,8 @@ def __init__(self, target_language="zh-Hans", vertical_alignment="center", text_color=None, - text_mask_generator=None): + text_mask_generator=None, + cuda_detector_model_path=None): self._translation_capabilities = ResponseFormatCapabilities() self.device = 'cuda' if use_gpu else 'cpu' self.translation_model = translation_model @@ -144,7 +145,8 @@ def __init__(self, print("初始化管线") print("[INFO] 加载 Comic Text Detector...") - self.detector = create_text_detector(det_model_path, self.device, self.source_language) + self.detector = create_text_detector(det_model_path, self.device, self.source_language, + cuda_model_path=cuda_detector_model_path) self.ocr_engine = create_ocr(self.ocr_config, self.device) self.ocr_backend_active = self.ocr_engine.name diff --git a/comic-translate-ai/main/onnx_text_detector.py b/comic-translate-ai/main/onnx_text_detector.py index a822104..ff5b646 100644 --- a/comic-translate-ai/main/onnx_text_detector.py +++ b/comic-translate-ai/main/onnx_text_detector.py @@ -103,10 +103,17 @@ def _postprocess_mask_np(img: np.ndarray) -> np.ndarray: return img.astype(np.uint8) -def create_text_detector(model_path, device="cpu", language="ja"): +def create_text_detector(model_path, device="cpu", language="ja", *, cuda_model_path=None): from pathlib import Path from comic_translate_core.detector_paths import REGION_FILE + if cuda_model_path and str(device).startswith('cuda'): + try: + return OnnxTextDetector(cuda_model_path, device=device, require_cuda=True) + except Exception as exc: + # The optional fast graph must never pin an installation to the + # heavier CPU detector when the CUDA runtime cannot load it. + print(f'[WARNING] CUDA 快速检测器不可用,改用默认检测器: {exc}') if Path(model_path).name == REGION_FILE: from onnx_split_detector import SplitTextDetector return SplitTextDetector(model_path, device, language) @@ -114,8 +121,8 @@ def create_text_detector(model_path, device="cpu", language="ja"): class OnnxTextDetector: - def __init__(self, model_path: str, input_size: int = 1024, device: str = "cpu", conf_thresh: float = 0.4, nms_thresh: float = 0.35, mask_thresh: float = 0.3): - self.session = create_onnx_session(model_path, device) + def __init__(self, model_path: str, input_size: int = 1024, device: str = "cpu", conf_thresh: float = 0.4, nms_thresh: float = 0.35, mask_thresh: float = 0.3, *, require_cuda=False): + self.session = create_onnx_session(model_path, device, require_cuda=True) if require_cuda else create_onnx_session(model_path, device) self.input_size = input_size if isinstance(input_size, tuple) else (input_size, input_size) self.conf_thresh = conf_thresh self.nms_thresh = nms_thresh diff --git a/comic_translate_core/onnx_session.py b/comic_translate_core/onnx_session.py index 7b5b142..d6e6cb2 100644 --- a/comic_translate_core/onnx_session.py +++ b/comic_translate_core/onnx_session.py @@ -39,7 +39,7 @@ def _preload_cuda(ort): _cuda_preloaded = True -def create_onnx_session(model_path, device='cpu', *, sess_options=None): +def create_onnx_session(model_path, device='cpu', *, sess_options=None, require_cuda=False): import onnxruntime as ort requested_cuda = str(device).startswith('cuda') @@ -50,13 +50,15 @@ def create_onnx_session(model_path, device='cpu', *, sess_options=None): except (OSError, RuntimeError) as exc: print(f'[WARNING] CUDA 运行库加载失败: {exc}') providers.insert(0, 'CUDAExecutionProvider') + if require_cuda and len(providers) == 1: + raise RuntimeError('CUDAExecutionProvider is unavailable') kwargs = {'providers': providers} if sess_options is not None: kwargs['sess_options'] = sess_options try: session = ort.InferenceSession(str(model_path), **kwargs) except Exception as exc: - if len(providers) == 1: + if require_cuda or len(providers) == 1: raise print(f'[WARNING] {Path(model_path).name}: GPU 会话创建失败: {exc}') kwargs['providers'] = ['CPUExecutionProvider'] @@ -64,6 +66,8 @@ def create_onnx_session(model_path, device='cpu', *, sess_options=None): actual = session.get_providers() gpu_active = 'CUDAExecutionProvider' in actual + if require_cuda and not gpu_active: + raise RuntimeError('ONNX Runtime did not activate CUDAExecutionProvider') if requested_cuda and not gpu_active: print(f'[WARNING] {Path(model_path).name}: GPU 未能启用,实际使用 CPU,处理速度会降低;请打开“设置 → 运行与输出 → GPU 安装说明与下载”。安装指南: {GPU_SETUP_URL}') else: diff --git a/comic_translate_core/text_mask.py b/comic_translate_core/text_mask.py index 06804a2..6e11f03 100644 --- a/comic_translate_core/text_mask.py +++ b/comic_translate_core/text_mask.py @@ -62,7 +62,7 @@ def _dilate(mask, radius): def _white_box_fallback(image, inside, seeds, erase, size): - """Repaint a plain balloon interior, including marks the detector missed. + """Repair missed glyphs near detected text on plain balloon paper. The decision must be local to this box: the detector domain is dilated by up to 8px, so `np.any(seeds)` can be satisfied by a neighbouring balloon while @@ -167,11 +167,27 @@ def _white_box_fallback(image, inside, seeds, erase, size): # safe to repaint, so the plain verdict overrides this veto. if protect_pixels > area * .30 and not plain: return None - mask = box & ~protect # Leave visibly coloured artwork to the colour-aware normal path. chroma = np.ptp(image.astype(np.int16),axis=2) if np.mean(chroma[box] > 20) > .005: return None + # A white box is not evidence that all its pixels belong to text. Extend + # the original mask only around glyph-sized ink components near its seeds. + nearby_text = _dilate(local_seeds, max(4, round(size * 2))) & box + nearby_labels = set(np.unique(labels[nearby_text])) + extra_components = np.zeros(count, bool) + for i in (relevant & nearby_labels) - supported: + x, y, w, h, component_area = stats[i] + if protected[i] or not max(4, round(size * .15)) <= component_area <= size * size * 4: + continue + local_labels = labels[y:y+h, x:x+w] == i + if np.all(box[y:y+h, x:x+w][local_labels]): + extra_components[i] = True + extra = extra_components[labels] + # Leave separate ink and low-contrast artwork outside the small collar + # untouched, even when the paper passes every uniformity check. + collar = cv2.dilate(extra.astype(np.uint8), np.ones((3, 3), np.uint8)) > 0 + mask = box & ~protect & (erase | (collar & (~ink | extra))) return mask,tuple(map(int,paper)),protect_pixels,('loose' if loose else 'strict'),plain diff --git a/comic_translate_desktop/config.py b/comic_translate_desktop/config.py index de47abc..961f147 100644 --- a/comic_translate_desktop/config.py +++ b/comic_translate_desktop/config.py @@ -121,6 +121,12 @@ def load_ai_config() -> dict[str, Any]: ocr_backend = str(raw.get("ocr_backend") or "auto").strip().lower() ocr_config = {key: raw.get(key, default) for key, default in OCR_DEFAULTS.items()} ocr_config["source_language"] = str(raw.get("source_language") or "ja").strip().lower() + use_gpu = bool(raw.get("use_gpu", True)) + detector_setting = detector_model_setting(raw.get("detector_model")) + detector_path = _detector_path(detector_setting) + legacy = MODELS_ROOT / LEGACY_PATH + cuda_detector = (legacy if use_gpu and detector_setting == "auto" + and detector_path != legacy and _model_file_exists(legacy) else None) return { **ocr_config, @@ -146,13 +152,15 @@ def load_ai_config() -> dict[str, Any]: "pdf_dpi": int(raw.get("pdf_dpi") or 200), "resume_enabled": bool(raw.get("resume_enabled", True)), "issue_url": str(raw.get("issue_url") or ""), - "use_gpu": bool(raw.get("use_gpu", True)), + "use_gpu": use_gpu, "font_map": font_map, "style_font_map": style_font_map, "font_fallbacks": font_fallbacks, "translation_font": translation_font, "translation_font_active": translation_font_active, - "detector_model": str(_detector_path(raw.get("detector_model"))), + "detector_model": str(detector_path), + "detector_model_setting": detector_setting, + "cuda_detector_model": str(cuda_detector) if cuda_detector else None, "lama_model": str(_resolve_path(raw.get("lama_model"), "manga-lama/lama-manga-dynamic.onnx", base=MODELS_ROOT)), "ocr_backend": ocr_backend, "charspot_ocr_model": str(_resolve_path(raw.get("charspot_ocr_model"), "charspot-small", base=MODELS_ROOT)), @@ -190,6 +198,7 @@ def config_fingerprint(config: dict[str, Any]) -> tuple: return ( config["use_gpu"], config["detector_model"], + config.get("cuda_detector_model"), config["lama_model"], config["ocr_backend"], config["ocr_model"], @@ -220,20 +229,34 @@ def _baberu_ocr_complete(path: Path) -> bool: ) -def _detector_path(value): +def detector_model_setting(value): # Older installations saved this relative default even without a user choice. # Absolute paths and other custom paths stay explicit. setting = _clean_text(value) - if setting and setting != "auto" and Path(setting) != Path("models") / LEGACY_PATH: + if (not setting or setting.lower() in ("auto", "none") + or Path(setting) == Path("models") / LEGACY_PATH): + return "auto" + return setting + + +def _model_file_exists(path): + try: + return path.is_file() + except OSError: + # Leave diagnostics to missing_models; an unavailable candidate must + # not prevent the workbench from starting or using another detector. + return False + + +def _detector_path(value): + setting = detector_model_setting(value) + if setting != "auto": return _resolve_path(setting, str(SPLIT_PATH), base=MODELS_ROOT) new = MODELS_ROOT / SPLIT_PATH old = MODELS_ROOT / LEGACY_PATH - try: - if not new.parent.exists() and old.is_file(): + if not (_model_file_exists(new) and _model_file_exists(new.with_name(LINE_FILE))): + if _model_file_exists(old): return old - except PermissionError: - # Report access failures through the UI's model check. - pass return new diff --git a/comic_translate_desktop/smoke_test.py b/comic_translate_desktop/smoke_test.py index feb7ee0..92e09e0 100644 --- a/comic_translate_desktop/smoke_test.py +++ b/comic_translate_desktop/smoke_test.py @@ -205,19 +205,23 @@ def finish(): paper = cv2.imdecode(cv2.imencode('.jpg', paper, [cv2.IMWRITE_JPEG_QUALITY, 82])[1], 1) mask = AdaptiveTextMask().generate(MaskRequest(paper, (20, 20, 109, 79), strokes, 28)) result['jpeg_paper_fill'] = mask.fill_color is not None and not mask.erase_mask[16, 16:113].any() - # The whole-box fallback has to ship as well: a mark the detector - # seed never covers must be repainted inside a plain white balloon. + # A glyph-sized mark near text should be covered without repainting + # the whole balloon or swallowing isolated artwork. balloon = np.full((120, 150, 3), 255, np.uint8) cv2.putText(balloon, 'Hi', (30, 78), cv2.FONT_HERSHEY_SIMPLEX, 1.4, (10, 10, 10), 3) seeded = np.zeros(balloon.shape[:2], np.uint8) cv2.putText(seeded, 'Hi', (30, 78), cv2.FONT_HERSHEY_SIMPLEX, 1.4, 255, 3) seeded = cv2.erode(seeded, np.ones((3, 3), np.uint8)) - cv2.circle(balloon, (120, 92), 3, (10, 10, 10), -1) # missed punctuation + dot = np.zeros_like(seeded) + cv2.circle(dot, (108, 87), 3, 255, -1) # missed punctuation + balloon[dot > 0] = 10 + balloon[45, 100:127:3] = 20 # isolated screen dots fallback = AdaptiveTextMask().generate(MaskRequest(balloon, (20, 30, 130, 100), seeded, 28)) covered = getattr(fallback, 'box_fill_mask', None) result['white_box_fallback'] = bool( covered is not None and fallback.box_fill_color is not None - and int(covered[89:96, 117:124].min()) == 255) + and np.all(covered[dot > 0] == 255) + and not covered[45, 100:127:3].any()) import httpx with httpx.Client(timeout=90.0): result["translation_https_client"] = True diff --git a/comic_translate_desktop/worker.py b/comic_translate_desktop/worker.py index ea371b5..9dcfc57 100644 --- a/comic_translate_desktop/worker.py +++ b/comic_translate_desktop/worker.py @@ -201,6 +201,7 @@ def _build_pipeline(self): with self._capture_pipeline_output(): pipeline = ComicTranslatorPipeline( det_model_path=self._config["detector_model"], + cuda_detector_model_path=self._config.get("cuda_detector_model"), font_map=self._config["font_map"], font_size=self._config["font_size"], fallback_fonts=self._config.get('font_fallbacks'), diff --git a/docs/ERASE_FIX_VALIDATION.md b/docs/ERASE_FIX_VALIDATION.md index 3d3cdec..5e6d031 100644 --- a/docs/ERASE_FIX_VALIDATION.md +++ b/docs/ERASE_FIX_VALIDATION.md @@ -1,5 +1,7 @@ # 白气泡擦字修复实测 +下列数据记录的是首次纸色平涂实验。当前构建另有受限补擦:只在文字种子附近补涂合适的连通块,保留稀疏装饰网点。下列数据未用于评估这次补擦变更。 + 原图中浅色且均匀的气泡常带 JPEG 噪声,气泡边线也会进入框外采样环。以整圈像素的最大色差判定可否平涂,使 12 页日漫上全部 106 个框都进入 LaMa。修复在生成最终掩膜后检查框内剩余纸面,要求有足量样本、九成纸色像素在中位色的 3 级内、99% 在 10 级内,同时核对笔画附近及框外背景估色。通过时只向已有擦除掩膜填入测得的纸色。旧的纯色识别仍可处理黑底和彩底。 在同一批原尺寸页面上,对每版分别固定其检测框、字号、种子、LaMa 权重与设备,调用生产代码 inpaint_bubbles 比较修复前后。12 页主样本及 2 张额外页面仅供本地评测。每张页图的新旧掩膜逐像素一致,掩膜外灰度逐像素等于输入。没有修改模型权重,未调用翻译 API。 diff --git a/docs/RELEASE-v2.5.1.md b/docs/RELEASE-v2.5.1.md index a9a21e8..3f543cd 100644 --- a/docs/RELEASE-v2.5.1.md +++ b/docs/RELEASE-v2.5.1.md @@ -6,6 +6,10 @@ ## 更新内容 +本分支新构建的模型包同时提供两套检测器(379,381,876 字节,约为 v2.5.0 的 64.9%)。自动模式下,开启 GPU 且 CUDA 会话成功启用时优先使用旧版 Comic Text Detector;关闭 GPU 时优先使用轻量双图检测器。快速模型缺失或 CUDA 无法启动时,仍可使用轻量方案;只有完整旧模型时仍可使用旧检测器。手动填写的检测器路径始终优先。源码用户可运行 `python scripts/download_cuda_detector.py` 按固定提交和 SHA-256 安装快速模型。 + +白气泡补擦仅在检测文字附近补上符合形状条件的遗漏笔画和标点。已存在的稀疏网点和其他无关画面不会被整框涂掉。 + 修复白色漫画气泡擦字后出现灰斑的问题:先检查框内纸色和笔画周围的像素,纸面足够均匀时,在已有擦除掩膜内按原纸色填充。 在「设置 → 运行与输出 → GPU 安装说明与下载」点击「下载安装便携 GPU 运行库」,完成后重启。首次下载约 1.53 GB,需要兼容的 NVIDIA 驱动。DLL 保存在程序旁的 gpu-runtime 目录,无需另外安装 Python 或配置 PATH。 @@ -14,7 +18,7 @@ Windows 源码安装的模型现在继承模型库的访问权限。如果某个模型无法读取,工作台仍可打开,并在诊断中显示对应路径。 -默认检测器改用 ogkalu Small INT8 提供文字框、PP-OCRv6 manga v0.2 提供文字行,取原框和文字行外接框对应边的中点作为最终边界。孤立行不会自动送去擦字。两张图均支持 ONNX Runtime CPU/CUDA。日语 OCR 使用 CharSpot Small(CPU),韩英继续使用 PP-OCRv5,背景修补使用 LaMa。模型包含所有必要配置、词表、清单及许可证共 **284,712,120 字节**,是 v2.5.0 的 **48.71%**。CharSpot 权重以 CC BY-NC-SA 4.0 供非商业使用,两张新检测图的模型卡标注 Apache-2.0。 +轻量检测器使用 ogkalu Small INT8 提供文字框、PP-OCRv6 manga v0.2 提供文字行,取原框和文字行外接框对应边的中点作为最终边界。孤立行不会自动送去擦字。两张图均支持 ONNX Runtime CPU/CUDA。日语 OCR 使用 CharSpot Small(CPU),韩英继续使用 PP-OCRv5,背景修补使用 LaMa。原版发布的轻量模型包共 **284,712,120 字节**,是 v2.5.0 的 **48.71%**。CharSpot 权重以 CC BY-NC-SA 4.0 供非商业使用,两张新检测图的模型卡标注 Apache-2.0。 仅有完整 v2.5.0 模型包时,新程序仍可使用旧检测器和旧 OCR。要在两套模型共存时指定旧检测器,请将 detector_model 设为现有 comic-text-detector.onnx 的绝对路径。切回新版设为 auto。完整回退可直接启动保留的旧安装。使用新输出目录比较,以免复用已有结果。 @@ -24,4 +28,4 @@ Windows 源码安装的模型现在继承模型库的访问权限。如果某个 ## English -Windows source installs now inherit the model library permissions. The workbench can open and report an inaccessible model path. Extract both ZIPs into a fresh directory and run ComiTrans.exe. The default detector combines ogkalu Small INT8 with PP-OCRv6 manga line detection and midpoint box refinement. Both graphs run in ONNX Runtime on CPU or CUDA. The package includes CharSpot Small for Japanese, PP-OCRv5 for Korean and English, and LaMa for repair. Its uncompressed model inventory is 284,712,120 bytes. On three Japanese pages the new pipeline matched 23 of 32 coarse regions at IoU ≥ 0.5, the same as the legacy detector, and covered at least 80% of 25 regions versus 20. Existing legacy model directories remain usable. Set detector_model to the absolute path of the old ONNX file to select it explicitly. See SHA256SUMS.txt to verify the archives. +Extract both ZIPs into a fresh directory and run ComiTrans.exe. Rebuilt model bundles include both detectors. Auto mode uses the legacy Comic Text Detector when CUDA starts successfully and prefers the lightweight ogkalu Small INT8 + PP-OCRv6 manga detector on CPU. An explicit detector path takes priority. Japanese OCR uses CharSpot Small on CPU; Korean and English use PP-OCRv5. See the SHA256SUMS.txt shipped with each build for its own checksums. diff --git a/docs/models/v2.5.1-packaging.json b/docs/models/v2.5.1-packaging.json index bb6cb54..1b0693a 100644 --- a/docs/models/v2.5.1-packaging.json +++ b/docs/models/v2.5.1-packaging.json @@ -1,5 +1,5 @@ { - "status": "Local v2.5.1 preview with midpoint split detector", + "status": "Historical v2.5.1 packaging evidence for the original split-only model set; not the checksums of later rebuilds", "archives": [ { "name": "ComiTrans-v2.5.1-app.zip", diff --git a/docs/releases/v2.5.1/release-page.md b/docs/releases/v2.5.1/release-page.md index 815da89..fd57bfb 100644 --- a/docs/releases/v2.5.1/release-page.md +++ b/docs/releases/v2.5.1/release-page.md @@ -6,11 +6,11 @@ ## 更新内容 -已有正式 v2.5.0 的用户可用同目录的 ComiTrans-v2.5.0-to-2.5.1-patch.zip 升级,不必重新下载几百 MB 的程序包:退出客户端,对包含 ComiTrans.exe 的原目录运行 Apply-Update.ps1 并选择该补丁即可。 +本次本地预览目录提供完整程序包和模型包。由 v2.5.0 升级时请解压到新目录,保留原安装和项目。 修复白色漫画气泡擦字后出现灰斑的问题:先检查框内纸色和笔画周围的像素,纸面足够均匀时,在已有擦除掩膜内按原纸色填充。 -检测器漏掉的字、注音和标点会留在气泡里。新增整框兜底:纸色从原图未擦像素测得,框内各区纸色一致且框内本身有文字种子时,按该纸色补涂整框,包括旧掩膜漏掉的位置。气泡边线、跨框轮廓、长发丝和大型画线保持原样;网点、渐变和黑底白字仍走原修补流程。仅在邻框有种子而本框没有文字时不会触发,框内画面占三成以上时也会跳过。 +对近白气泡里检测器漏掉的部分笔画和标点,会在已有文字种子附近查找符合形状条件的连通块再补擦。补擦不覆盖整框,稀疏网点和与文字无关的像素可保留。 在「设置 → 运行与输出 → GPU 安装说明与下载」点击「下载安装便携 GPU 运行库」,完成后重启。首次下载约 1.53 GB,需要兼容的 NVIDIA 驱动。DLL 保存在程序旁的 gpu-runtime 目录,无需另外安装 Python 或配置 PATH。 diff --git a/package_release.py b/package_release.py index c2c6a52..9d5347f 100644 --- a/package_release.py +++ b/package_release.py @@ -8,6 +8,7 @@ import zipfile from comic_translate_desktop import __version__ +from comic_translate_core.detector_paths import LEGACY_PATH from comic_translate_core.release_patch import MANIFEST_NAME, json_bytes, manifest_for_files ROOT = Path(__file__).resolve().parent @@ -19,6 +20,7 @@ ] MODEL_BASELINE_BYTES = 584_467_185 # v2.5.0 archive members, uncompressed; docs/models/v2.5.0-manifest.json MODEL_LIMIT_BYTES = MODEL_BASELINE_BYTES * 3 // 2 +MODEL_ARCHIVE_PREFIX = "ComiTrans/comic-translate-ai/models/" SKIP_DIRS = {"models", "gpu-runtime", "user_fonts", "Log", "logs", "__pycache__", ".cache"} @@ -75,10 +77,18 @@ def collect_app(dist: Path): return files +def legacy_detector_entry(): + baseline = json.loads((ROOT / "docs/models/v2.5.0-manifest.json").read_text(encoding="utf-8")) + return next(entry for entry in baseline["files"] if entry["path"] == LEGACY_PATH.as_posix()) + + def collect_models(): from scripts.model_package import verify files = [(MODELS_SRC / rel, rel) for rel in MODEL_FILES] + legacy = legacy_detector_entry() + verify(MODELS_SRC, {"files": [legacy]}) + files.append((MODELS_SRC / LEGACY_PATH, legacy["path"])) for package in ("charspot-small", "split-detector"): manifest_path = ROOT / f"docs/models/{package}.json" manifest = json.loads(manifest_path.read_text(encoding="utf-8")) @@ -89,7 +99,7 @@ def collect_models(): names = [entry["path"] for entry in manifest["files"]] + ["model-manifest.json"] files.extend((folder / name, f"{folder.name}/{name}") for name in names) validate_model_budget(files) - return [(path, "ComiTrans/comic-translate-ai/models/" + rel) for path, rel in files] + return [(path, MODEL_ARCHIVE_PREFIX + rel) for path, rel in files] def validate_model_budget(files): @@ -99,10 +109,10 @@ def validate_model_budget(files): return total -def verify_reused_models(archive_path, inventory_path): +def verify_reused_models(archive_path, inventory_path, *, additional_files=()): """App-only builds must reuse the audited model set for this release.""" inventory = json.loads(inventory_path.read_text(encoding="utf-8")) - expected = {entry["path"]: entry for entry in inventory["files"]} + expected = {entry["path"]: entry for entry in (*inventory["files"], *additional_files)} with zipfile.ZipFile(archive_path) as archive: entries = archive.infolist() if (len(entries) != len(expected) or set(archive.namelist()) != set(expected) @@ -151,7 +161,11 @@ def main(): if args.app_only and not model_target.is_file(): raise FileNotFoundError(f'--app-only requires an existing model archive: {model_target}') if args.app_only: - verify_reused_models(model_target, ROOT / "docs" / "models" / f"v{__version__}-inventory.json") + legacy = legacy_detector_entry() + verify_reused_models( + model_target, ROOT / "docs" / "models" / f"v{__version__}-inventory.json", + additional_files=[{**legacy, "path": MODEL_ARCHIVE_PREFIX + legacy["path"]}], + ) model_files = None else: model_files = collect_models() diff --git a/scripts/download_cuda_detector.py b/scripts/download_cuda_detector.py new file mode 100644 index 0000000..6b83edc --- /dev/null +++ b/scripts/download_cuda_detector.py @@ -0,0 +1,51 @@ +"""Install the audited CUDA detector without overwriting a custom model.""" +import argparse +from pathlib import Path +import sys +from uuid import uuid4 + +import requests + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +from comic_translate_core.detector_paths import LEGACY_PATH +from package_release import legacy_detector_entry +from scripts.model_package import digest, verify + + +def install(models_root): + entry = legacy_detector_entry() + manifest = {"files": [entry]} + target = models_root / LEGACY_PATH + if target.exists(): + verify(models_root, manifest) + return target + target.parent.mkdir(parents=True, exist_ok=True) + # Create the download beside its destination so it inherits the model + # library's permissions when the verified file is moved into place. + temporary = target.with_name(f".{target.name}-{uuid4().hex}.part") + try: + with requests.get(entry["source_url"], stream=True, timeout=(15, 90)) as response: + response.raise_for_status() + with temporary.open("wb") as stream: + size = 0 + for chunk in response.iter_content(1024 * 1024): + size += len(chunk) + if size > entry["bytes"]: + raise ValueError("Detector download exceeds the audited size") + stream.write(chunk) + if size != entry["bytes"] or digest(temporary) != entry["sha256"]: + raise ValueError("Detector download failed verification") + if target.exists(): + verify(models_root, manifest) + return target + temporary.rename(target) + finally: + temporary.unlink(missing_ok=True) + return target + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--models-root", type=Path, default=ROOT / "comic-translate-ai/models") + print(install(parser.parse_args().models_root)) diff --git a/tests/test_model_upgrade.py b/tests/test_model_upgrade.py index ab334de..037bf3e 100644 --- a/tests/test_model_upgrade.py +++ b/tests/test_model_upgrade.py @@ -39,10 +39,44 @@ def test_detector_migration_and_explicit_rollback(self): self.assertEqual(config._detector_path(saved_default), old) new.parent.mkdir() new.touch() + self.assertEqual(config._detector_path("auto"), old) new.with_name(LINE_FILE).touch() self.assertEqual(config._detector_path(saved_default), new) self.assertEqual(config._detector_path("auto"), new) self.assertEqual(config._detector_path(str(old)), old) + with patch.object(config, "CONFIG_PATH", Path(directory) / "config.yaml"): + self.assertEqual(config.load_ai_config()["cuda_detector_model"], str(old)) + self.assertIsNone(config.save_ai_config({"use_gpu": False})["cuda_detector_model"]) + explicit = config.save_ai_config({"use_gpu": True, "detector_model": str(new)}) + self.assertIsNone(explicit["cuda_detector_model"]) + + def test_auto_detector_uses_legacy_only_when_cuda_is_active(self): + from onnx_text_detector import create_text_detector + from comic_translate_core.detector_paths import REGION_FILE + + with (patch('onnx_text_detector.create_onnx_session') as session, + patch('onnx_split_detector.SplitTextDetector') as split): + self.assertIs(create_text_detector(REGION_FILE, "cpu", cuda_model_path="fast.onnx"), + split.return_value) + session.assert_not_called() + session.return_value.get_providers.return_value = ["CUDAExecutionProvider"] + fast = create_text_detector(REGION_FILE, "cuda", cuda_model_path="fast.onnx") + self.assertIs(fast.session, session.return_value) + session.assert_called_once_with("fast.onnx", "cuda", require_cuda=True) + session.side_effect = RuntimeError("CUDA unavailable") + self.assertIs(create_text_detector(REGION_FILE, "cuda", cuda_model_path="fast.onnx"), + split.return_value) + + def test_cuda_only_session_rejects_silent_cpu_fallback(self): + from comic_translate_core.onnx_session import create_onnx_session + + with (patch('onnxruntime.get_available_providers', return_value=['CUDAExecutionProvider']), + patch('comic_translate_core.onnx_session._preload_cuda'), + patch('onnxruntime.InferenceSession') as session): + session.return_value.get_providers.return_value = ['CPUExecutionProvider'] + with self.assertRaisesRegex(RuntimeError, 'did not activate CUDA'): + create_onnx_session("fast.onnx", "cuda", require_cuda=True) + session.assert_called_once() def test_overlapping_regions_own_lines_once_and_ignore_orphans(self): from onnx_split_detector import assign_lines, midpoint_box diff --git a/tests/test_text_mask.py b/tests/test_text_mask.py index c45b61a..75e97e9 100644 --- a/tests/test_text_mask.py +++ b/tests/test_text_mask.py @@ -111,6 +111,21 @@ def test_box_fallback_keeps_a_crossing_balloon_border(self): self.assertFalse(np.any(result.box_fill_mask[border] > 0)) self.assertGreater(result.diagnostics['protected_box_pixels'], 0) + def test_box_fallback_preserves_sparse_art_outside_the_erase_mask(self): + image = np.full((120, 160, 3), 248, np.uint8) + seed = np.zeros(image.shape[:2], np.uint8) + for x in (45, 60): + image[46:66, x:x+6] = 10 + seed[46:66, x:x+6] = 255 + art = np.zeros(seed.shape, bool) + art[78, 73:118:3] = True # fifteen isolated screen dots + art[70:73, 108:114] = True + image[78, 73:118:3] = 20 + image[70:73, 108:114] = 238 + result = AdaptiveTextMask().generate(MaskRequest(image, (32, 30, 126, 93), seed, 16)) + self.assertIsNotNone(result.box_fill_mask) + self.assertFalse(np.any((result.erase_mask | result.box_fill_mask)[art])) + def test_box_fallback_requires_its_own_seeds(self): image, truth, seed = self.fixture((255,)*3, (0,)*3) leak = np.zeros_like(seed)