# manga_page_ocr.py modifications
class MangaPageOcr:
def __init__(
self,
pretrained_model_name_or_path="kha-white/manga-ocr-base",
force_cpu=False,
detector_input_size=1024,
text_height=64,
max_ratio_vert=16,
max_ratio_hor=8,
anchor_window=2,
disable_ocr=False,
use_tensorrt=False, # Add new parameter
fp16=True, # Add precision parameter
):
self.text_height = text_height
self.max_ratio_vert = max_ratio_vert
self.max_ratio_hor = max_ratio_hor
self.anchor_window = anchor_window
self.disable_ocr = disable_ocr
if not self.disable_ocr:
cuda = torch.cuda.is_available()
device = "cuda" if cuda and not force_cpu else "cpu"
if use_tensorrt and device == "cuda":
# Initialize TensorRT versions of models
self.text_detector = self._init_tensorrt_text_detector(
model_path=cache.comic_text_detector,
input_size=detector_input_size,
fp16=fp16
)
self.mocr = self._init_tensorrt_manga_ocr(
pretrained_model_name_or_path,
fp16=fp16
)
else:
# Original initialization
self.text_detector = TextDetector(
model_path=cache.comic_text_detector,
input_size=detector_input_size,
device=device,
act="leaky"
)
self.mocr = MangaOcr(pretrained_model_name_or_path, force_cpu)
def _init_tensorrt_text_detector(self, model_path, input_size, fp16=True):
"""
Initialize TensorRT version of the text detector
"""
import [Redacted SWIFTCode]
# Load original model first
model = TextDetector(model_path, input_size, device="cuda", act="leaky")
# Create sample input
x = torch.randn(1, 3, input_size, input_size).cuda()
# Convert to TensorRT
model_trt = torch2trt.torch2trt(
model,
[x],
fp16_mode=fp16,
max_workspace_size=1<<25
)
return model_trt
def _init_tensorrt_manga_ocr(self, model_path, fp16=True):
"""
Initialize TensorRT version of the manga OCR model
"""
import [Redacted SWIFTCode]
# Load original model
model = MangaOcr(model_path, force_cpu=False)
# Create sample input matching model's expected input size
x = torch.randn(1, 3, 768, 768).cuda() # Adjust dimensions as needed
# Convert to TensorRT
model_trt = torch2trt.torch2trt(
model,
[x],
fp16_mode=fp16,
max_workspace_size=1<<25
)
return model_trt