Skip to content

Commit 673b2b3

Browse files
committed
feat: support to log_level
1 parent 82abe85 commit 673b2b3

File tree

6 files changed

+37
-22
lines changed

6 files changed

+37
-22
lines changed

demo.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
# 只识别
2222
from rapid_videocr import RapidVideOCR, RapidVideOCRInput
2323

24-
input_args = RapidVideOCRInput(is_batch_rec=False)
24+
input_args = RapidVideOCRInput(is_batch_rec=False, log_level="critical")
2525
extractor = RapidVideOCR(input_args)
2626

2727
rgb_dir = "tests/test_files/RGBImages"

rapid_videocr/main.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,14 @@
88
from .export import ExportStrategyFactory, OutputFormat
99
from .ocr_processor import OCRProcessor
1010
from .utils.crop_by_project import CropByProject
11-
from .utils.logger import Logger
11+
from .utils.logger import logger
1212
from .utils.typings import IMAGE_EXTENSIONS, RapidVideOCRInput
1313
from .utils.utils import mkdir
1414

1515

1616
class RapidVideOCR:
1717
def __init__(self, input_params: RapidVideOCRInput):
18-
self.logger = Logger(logger_name=__name__).get_log()
18+
logger.setLevel(input_params.log_level.upper())
1919

2020
self.ocr_processor = OCRProcessor(
2121
input_params.ocr_params, input_params.batch_size
@@ -78,12 +78,11 @@ def export_file(
7878
):
7979
try:
8080
strategy = ExportStrategyFactory.create_strategy(self.out_format)
81-
8281
mkdir(save_dir)
8382
strategy.export(save_dir, save_name, srt_result, ass_result, txt_result)
84-
self.logger.info("[OCR] Results saved to directory: %s", save_dir)
83+
logger.info(f"[OCR] Results saved to directory: {save_dir}")
8584
except ValueError as e:
86-
self.logger.error("Export failed: %s", str(e))
85+
logger.error(f"Export failed: {e}")
8786
raise
8887

8988
def print_console(self, txt_result: List):

rapid_videocr/ocr_processor.py

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@
99
from rapidocr import RapidOCR
1010
from tqdm import tqdm
1111

12-
from .utils.logger import Logger
12+
from .utils.logger import logger
13+
from .utils.typings import LOG_LEVEL_MAP
1314
from .utils.utils import (
1415
compute_centroid,
1516
compute_poly_iou,
@@ -21,11 +22,15 @@
2122

2223
class OCRProcessor:
2324
def __init__(self, ocr_params: Optional[Dict] = None, batch_size: int = 10):
24-
self.logger = Logger(logger_name=__name__).get_log()
2525
self.ocr_engine = self._init_ocr_engine(ocr_params)
2626
self.batch_size = batch_size
2727

2828
def _init_ocr_engine(self, ocr_params: Optional[Dict] = None) -> RapidOCR:
29+
log_level_dict = {"Global.log_level": LOG_LEVEL_MAP[logger.level]}
30+
if ocr_params is None:
31+
return RapidOCR(params=log_level_dict)
32+
33+
ocr_params.update(log_level_dict)
2934
return RapidOCR(params=ocr_params)
3035

3136
def __call__(
@@ -40,7 +45,7 @@ def __call__(
4045
return srt_results, ass_results, txt_results
4146

4247
def single_rec(self, img_list: List[Path]) -> List[Tuple[int, str, str, str]]:
43-
self.logger.info("[OCR] Running with single recognition.")
48+
logger.info("[OCR] Running with single recognition.")
4449

4550
rec_results = []
4651
for i, img_path in enumerate(tqdm(img_list, desc="OCR")):
@@ -112,7 +117,7 @@ def _preprocess_image(img_path: Path) -> np.ndarray:
112117
def _generate_srt_results(
113118
rec_results: List[Tuple[int, str, str, str]],
114119
) -> List[str]:
115-
return [f"{i+1}\n{time_str}\n{txt}\n" for i, time_str, txt, _ in rec_results]
120+
return [f"{i + 1}\n{time_str}\n{txt}\n" for i, time_str, txt, _ in rec_results]
116121

117122
@staticmethod
118123
def _generate_ass_results(
@@ -128,7 +133,7 @@ def _generate_txt_result(rec_results: List[Tuple[int, str, str, str]]) -> List[s
128133
return [f"{txt}\n" for _, _, txt, _ in rec_results]
129134

130135
def batch_rec(self, img_list: List[Path]) -> List[Tuple[int, str, str, str]]:
131-
self.logger.info("[OCR] Running with concat recognition.")
136+
logger.info("[OCR] Running with concat recognition.")
132137

133138
img_nums = len(img_list)
134139
rec_results = []

rapid_videocr/utils/logger.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ def __init__(self, log_level=logging.DEBUG, logger_name=None):
1313
self.logger.propagate = False
1414

1515
formatter = colorlog.ColoredFormatter(
16-
"%(log_color)s[%(levelname)s] %(asctime)s [RapidVideOCR] %(filename)s:%(lineno)d: %(message)s",
16+
"%(log_color)s[%(levelname)s] %(asctime)s %(filename)s:%(lineno)d: %(message)s",
1717
log_colors={
1818
"DEBUG": "cyan",
1919
"INFO": "green",
@@ -35,3 +35,6 @@ def __init__(self, log_level=logging.DEBUG, logger_name=None):
3535

3636
def get_log(self):
3737
return self.logger
38+
39+
40+
logger = Logger(log_level=logging.INFO).get_log()

rapid_videocr/utils/typings.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,3 +28,14 @@ class RapidVideOCRInput:
2828
batch_size: int = 10
2929
out_format: str = OutputFormat.ALL.value
3030
ocr_params: Optional[Dict[str, Any]] = None
31+
log_level: str = "info" # debug / info / warning / error / critical
32+
33+
34+
LOG_LEVEL_MAP = {
35+
50: "CRITICAL",
36+
40: "ERROR",
37+
30: "WARNING",
38+
20: "INFO",
39+
10: "DEBUG",
40+
0: "NOTSET",
41+
}

rapid_videocr/vsf_ocr_cli.py

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from pathlib import Path
66

77
from .main import OutputFormat, RapidVideOCR, RapidVideOCRInput
8-
from .utils.logger import Logger
8+
from .utils.logger import logger
99
from .utils.typings import VideoFormat
1010
from .utils.utils import float_range
1111
from .vsf_cli import VideoSubFinder, VideoSubFinderInput
@@ -17,7 +17,6 @@ def __init__(
1717
vsf_input_params: VideoSubFinderInput,
1818
ocr_input_params: RapidVideOCRInput,
1919
):
20-
self.logger = Logger(logger_name=__name__).get_log()
2120
self.vsf = VideoSubFinder(vsf_input_params)
2221
self.video_ocr = RapidVideOCR(ocr_input_params)
2322
self.video_formats = [VideoFormat[v].value for v in VideoFormat.__members__]
@@ -31,13 +30,13 @@ def __call__(self, video_path: str, output_dir: str = "outputs"):
3130
else:
3231
video_list = [video_path]
3332

34-
self.logger.info(
33+
logger.info(
3534
"Extracting subtitle images with VideoSubFinder (takes quite a long time) ..."
3635
)
3736
video_num = len(video_list)
3837
for i, one_video in enumerate(video_list):
39-
self.logger.info(
40-
"[%s/%s] Starting to extract %s key frame", i + 1, video_num, one_video
38+
logger.info(
39+
f"[{i + 1}{video_num}] Starting to extract {one_video} key frame"
4140
)
4241

4342
save_name = Path(one_video).stem
@@ -47,16 +46,14 @@ def __call__(self, video_path: str, output_dir: str = "outputs"):
4746
try:
4847
self.vsf(str(one_video), str(save_vsf_dir))
4948
except Exception as e:
50-
self.logger.error("Extract %s error, %s, skip", one_video, e)
49+
logger.error(f"Extract {one_video} error, {e}, skip")
5150
continue
5251

53-
self.logger.info(
54-
"[%s/%s] Starting to run %s ocr", i + 1, video_num, one_video
55-
)
52+
logger.info(f"{i + 1}/{video_num}] Starting to run {one_video} ocr")
5653

5754
rgb_dir = Path(save_vsf_dir) / "RGBImages"
5855
if not list(rgb_dir.iterdir()):
59-
self.logger.warning("Extracting frames from %s is 0, skip", one_video)
56+
logger.warning(f"Extracting frames from {one_video} is 0, skip")
6057
continue
6158
self.video_ocr(rgb_dir, save_dir, save_name=save_name)
6259

0 commit comments

Comments
 (0)