Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 52 additions & 1 deletion assets/i18n/en.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,15 @@
{
"CUDA 加速": "CUDA",
"下次任务生效。自动检测模式会按 CUDA 是否可用选择模型。": "Applies to the next job. Auto detection selects a model based on CUDA availability.",
"CUDA 设置未保存": "CUDA setting not saved",
"CUDA 设置未保存:{_0}": "Could not save the CUDA setting: {_0}",
"下次任务将尝试 CUDA 加速": "CUDA requested for the next job",
"下次任务将使用 CPU": "Next job will use CPU",
"自动模式按 CUDA 状态选择检测器;手动选择模型可固定路径。": "Auto selects a detector based on CUDA availability. Browse to pin a model path.",
"无法读取模型路径:{_0}": "Cannot access model path: {_0}",
"{_0}/{_1} 个路径存在;开始翻译前会检查当前使用的模型。": "{_0}/{_1} paths found. Active models are checked before translation.",
"跳过 {_0} 个无法导入的文件": "Skipped {_0} files that could not be imported",
"正在导入 {_0} 个结果到精修列表…": "Importing {_0} results into the typesetting list…",
"自动(使用已安装的日语模型)": "Auto (use installed Japanese OCR)",
"该本地 OCR 仅用于日语,请选择自动或自定义 OCR。": "This local OCR supports Japanese only. Choose Auto or custom OCR.",
"CharSpot Small: {_4}\n检测: {_0}\nBaberu OCR: {_1}\nmanga-ocr: {_2}\n修复: {_3}": "CharSpot Small: {_4}\nDetector: {_0}\nBaberu OCR: {_1}\nmanga-ocr: {_2}\nInpainting: {_3}",
Expand Down Expand Up @@ -628,5 +639,45 @@
"减少动效(关闭淡入与呼吸动画)": "Reduce motion (disable fades and pulsing)",
"开启后不再播放页面淡入与运行中呼吸动画。": "Stops page fades and the running-state pulse.",
"缩放工具": "Zoom tool",
"点击放大,Alt+点击缩小 · Z": "Click to zoom in, Alt+click to zoom out · Z"
"点击放大,Alt+点击缩小 · Z": "Click to zoom in, Alt+click to zoom out · Z",
"性能与渲染": "Performance and rendering",
"同时在途准备、翻译与修补的页数(1–16,默认 4)。数值越大吞吐越高,但更吃显存与内存;8 GB 显存建议 2–4。": "Pages prepared, translated, and retouched at the same time (1–16, default 4). Higher values improve throughput but use more VRAM and RAM; 2–4 is recommended on 8 GB GPUs.",
"PDF 页图的分辨率(96–400,默认 200)。越高越清晰,也越慢、越占内存;对图片输入没有影响。": "Resolution of rendered PDF pages (96–400, default 200). Higher is sharper but slower and uses more memory; image inputs are unaffected.",
"新排版使用的基准字号(8–96,默认 16)。精修页可以逐块调整,这里只改变之后生成的译文。": "Base font size for new typesetting (8–96, default 16). Individual blocks can still be adjusted in the editor; this only affects pages generated afterwards.",
"启用「AI 字体判别」时,每块文本重复判定的次数(1–5,默认 3)。次数越多越稳定,但更耗 token。": "How many times each text block is probed when AI font matching is enabled (1–5, default 3). More samples are more stable but consume more tokens.",
"最大并行页数": "Max parallel pages",
"PDF 渲染 DPI": "PDF render DPI",
"默认字号": "Default font size",
"字体判别采样次数": "Font probe samples",
"并行与字号只影响之后生成的页面;修改 PDF DPI 会让断点续传重新渲染 PDF。": "Parallelism and font size only affect pages generated afterwards. Changing PDF DPI makes resume re-render PDFs.",
"模型文件": "Model files",
"检测模型": "Detector model",
"修复模型": "Inpainting model",
"CharSpot OCR 目录": "CharSpot OCR folder",
"manga-ocr 目录": "manga-ocr folder",
"Baberu OCR 目录": "Baberu OCR folder",
"留空使用内置默认路径;更换文件后下一次任务会重新加载模型。": "Leave empty to use the built-in default path. Replacing a file reloads the model on the next task.",
"模型检查": "Model check",
"恢复推荐默认值": "Restore recommended defaults",
"只恢复本页字段,点击「保存配置」后才会写入。": "Only resets fields on this page; click Save settings to write them.",
"配置文件:{_0}": "Config file: {_0}",
"选择模型目录": "Choose model folder",
"04 详细配置": "04 Detailed settings",
"微调运行与模型细节": "Tune runtime and model details",
"原先需要手动编辑 config.yaml 的选项集中在这里,保存后下一次任务生效。": "Options that previously required editing config.yaml are gathered here. Changes apply to the next task.",
"全部 {_0} 个路径存在": "All {_0} paths found",
"{_0}/{_1} 个路径存在,缺失项会在开始翻译前提示": "{_0}/{_1} paths found; missing ones are reported before translating",
"一键精修": "Retouch all",
"把上次任务生成的全部图片或 PDF 加入嵌字精修列表": "Add every image or PDF from the last task to the typesetting list",
"上次任务还没有可精修的结果": "No editable results from the last task yet",
"已把 {_0} 个结果加入精修列表。": "Added {_0} results to the retouch list.",
"填白": "Fill white",
"填黑": "Fill black",
"把框选区域整块填成白色(可撤回)。": "Fill the selected rectangle with white (undoable).",
"把框选区域整块填成黑色(可撤回)。": "Fill the selected rectangle with black (undoable).",
"选区包含已还原气泡,请先恢复该气泡的处理结果再填色。": "The selection contains a restored bubble; restore its processed result before filling.",
"已把选区填为白色 · 未保存,可撤回修补。": "Selection filled with white · unsaved, undo available.",
"已把选区填为黑色 · 未保存,可撤回修补。": "Selection filled with black · unsaved, undo available.",
"选区超出图片范围。": "The selection is outside the image.",
"在画布拖动框选背景,再点击“修补选区”或“填白 / 填黑”;译文保持独立。": "Drag a background selection on the canvas, then choose Repair, Fill white, or Fill black. Text stays independent."
}
53 changes: 52 additions & 1 deletion assets/i18n/ja.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,15 @@
{
"CUDA 加速": "CUDA 加速",
"下次任务生效。自动检测模式会按 CUDA 是否可用选择模型。": "次回の処理から適用されます。自動検出では CUDA の利用可否に応じてモデルを選びます。",
"CUDA 设置未保存": "CUDA 設定は未保存",
"CUDA 设置未保存:{_0}": "CUDA 設定を保存できませんでした:{_0}",
"下次任务将尝试 CUDA 加速": "次回の処理で CUDA を試行",
"下次任务将使用 CPU": "次回の処理は CPU を使用",
"自动模式按 CUDA 状态选择检测器;手动选择模型可固定路径。": "自動では CUDA の利用可否に応じてモデルを選びます。手動で選択したパスは固定されます。",
"无法读取模型路径:{_0}": "モデルパスにアクセスできません:{_0}",
"{_0}/{_1} 个路径存在;开始翻译前会检查当前使用的模型。": "{_0}/{_1} 件のパスが見つかりました。翻訳の開始前に使用するモデルを確認します。",
"跳过 {_0} 个无法导入的文件": "読み込めなかった {_0} 件をスキップしました",
"正在导入 {_0} 个结果到精修列表…": "{_0} 件の結果を編集リストに読み込み中…",
"自动(使用已安装的日语模型)": "自動(インストール済みの日本語 OCR を使用)",
"该本地 OCR 仅用于日语,请选择自动或自定义 OCR。": "このローカル OCR は日本語専用です。自動またはカスタム OCR を選択してください。",
"CharSpot Small: {_4}\n检测: {_0}\nBaberu OCR: {_1}\nmanga-ocr: {_2}\n修复: {_3}": "CharSpot Small: {_4}\n検出:{_0}\nBaberu OCR:{_1}\nmanga-ocr:{_2}\n背景修復:{_3}",
Expand Down Expand Up @@ -628,5 +639,45 @@
"减少动效(关闭淡入与呼吸动画)": "動きを減らす(フェードと明滅を無効化)",
"开启后不再播放页面淡入与运行中呼吸动画。": "ページのフェードと実行中の明滅を停止します。",
"缩放工具": "ズームツール",
"点击放大,Alt+点击缩小 · Z": "クリックで拡大、Alt+クリックで縮小 · Z"
"点击放大,Alt+点击缩小 · Z": "クリックで拡大、Alt+クリックで縮小 · Z",
"性能与渲染": "パフォーマンスと描画",
"同时在途准备、翻译与修补的页数(1–16,默认 4)。数值越大吞吐越高,但更吃显存与内存;8 GB 显存建议 2–4。": "同時に準備・翻訳・修正するページ数(1〜16、既定 4)。大きくすると処理量は増えますが、VRAM とメモリを多く使います。8 GB の GPU では 2〜4 を推奨します。",
"PDF 页图的分辨率(96–400,默认 200)。越高越清晰,也越慢、越占内存;对图片输入没有影响。": "PDF ページ画像の解像度(96〜400、既定 200)。高いほど精細ですが遅くなり、メモリも多く使います。画像入力には影響しません。",
"新排版使用的基准字号(8–96,默认 16)。精修页可以逐块调整,这里只改变之后生成的译文。": "新しい組版の基準文字サイズ(8〜96、既定 16)。エディターではブロックごとに調整できます。ここでは今後生成するページにのみ反映されます。",
"启用「AI 字体判别」时,每块文本重复判定的次数(1–5,默认 3)。次数越多越稳定,但更耗 token。": "「AI フォント判定」が有効なとき、各テキストブロックを判定する回数(1〜5、既定 3)。多いほど安定しますが、トークン消費が増えます。",
"最大并行页数": "最大並列ページ数",
"PDF 渲染 DPI": "PDF 描画 DPI",
"默认字号": "既定の文字サイズ",
"字体判别采样次数": "フォント判定サンプル数",
"并行与字号只影响之后生成的页面;修改 PDF DPI 会让断点续传重新渲染 PDF。": "並列数と文字サイズは今後生成するページにのみ影響します。PDF DPI を変更すると、再開時に PDF を再描画します。",
"模型文件": "モデルファイル",
"检测模型": "検出モデル",
"修复模型": "修復モデル",
"CharSpot OCR 目录": "CharSpot OCR フォルダー",
"manga-ocr 目录": "manga-ocr フォルダー",
"Baberu OCR 目录": "Baberu OCR フォルダー",
"留空使用内置默认路径;更换文件后下一次任务会重新加载模型。": "空欄の場合は内蔵の既定パスを使用します。ファイルを変更すると、次回のタスクでモデルを再読み込みします。",
"模型检查": "モデル確認",
"恢复推荐默认值": "推奨の既定値に戻す",
"只恢复本页字段,点击「保存配置」后才会写入。": "このページの項目だけを戻します。「設定を保存」を押すまで書き込みません。",
"配置文件:{_0}": "設定ファイル: {_0}",
"选择模型目录": "モデルフォルダーを選択",
"04 详细配置": "04 詳細設定",
"微调运行与模型细节": "実行とモデルの詳細を調整",
"原先需要手动编辑 config.yaml 的选项集中在这里,保存后下一次任务生效。": "これまで config.yaml を直接編集する必要があった項目をここにまとめました。保存すると次回のタスクから反映されます。",
"全部 {_0} 个路径存在": "{_0} 件すべて存在",
"{_0}/{_1} 个路径存在,缺失项会在开始翻译前提示": "{_0}/{_1} 件が存在。不足分は翻訳開始前に通知されます",
"一键精修": "一括写植調整",
"把上次任务生成的全部图片或 PDF 加入嵌字精修列表": "前回のタスクで生成した画像または PDF をすべて写植調整リストに追加します",
"上次任务还没有可精修的结果": "前回のタスクには写植調整できる結果がまだありません",
"已把 {_0} 个结果加入精修列表。": "写植調整リストに {_0} 件の結果を追加しました。",
"填白": "白で塗る",
"填黑": "黒で塗る",
"把框选区域整块填成白色(可撤回)。": "選択範囲を白で塗りつぶします(元に戻せます)。",
"把框选区域整块填成黑色(可撤回)。": "選択範囲を黒で塗りつぶします(元に戻せます)。",
"选区包含已还原气泡,请先恢复该气泡的处理结果再填色。": "選択範囲に元画像へ戻した吹き出しがあります。処理結果に戻してから塗りつぶしてください。",
"已把选区填为白色 · 未保存,可撤回修补。": "選択範囲を白で塗りつぶしました・未保存、元に戻せます。",
"已把选区填为黑色 · 未保存,可撤回修补。": "選択範囲を黒で塗りつぶしました・未保存、元に戻せます。",
"选区超出图片范围。": "選択範囲が画像の外にあります。",
"在画布拖动框选背景,再点击“修补选区”或“填白 / 填黑”;译文保持独立。": "キャンバスで背景を囲んでから「選択範囲を修復」「白で塗る」「黒で塗る」を選びます。訳文は独立したままです。"
}
6 changes: 4 additions & 2 deletions comic-translate-ai/main/comic_translator_pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
13 changes: 10 additions & 3 deletions comic-translate-ai/main/onnx_text_detector.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,19 +103,26 @@ 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)
return OnnxTextDetector(model_path, device=device)


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
Expand Down
8 changes: 6 additions & 2 deletions comic_translate_core/onnx_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand All @@ -50,20 +50,24 @@ 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']
session = ort.InferenceSession(str(model_path), **kwargs)

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:
Expand Down
20 changes: 18 additions & 2 deletions comic_translate_core/text_mask.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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


Expand Down
Loading
Loading