From 5791387e461d5d43362399ddd2147147c88aed5e Mon Sep 17 00:00:00 2001 From: AuroraWright Date: Fri, 26 Jan 2024 00:27:25 +0100 Subject: [PATCH] Allow overriding of CLI arguments in the config --- owocr/__main__.py | 24 +++++++++++++++--- owocr/config.py | 53 +++++++++++++++++++++++++++++++++++++++ owocr/ocr.py | 9 ++----- owocr/run.py | 64 ++++++++++++++++++++--------------------------- owocr_config.ini | 6 +++++ 5 files changed, 109 insertions(+), 47 deletions(-) create mode 100644 owocr/config.py diff --git a/owocr/__main__.py b/owocr/__main__.py index a7e8e5d..958ea5d 100644 --- a/owocr/__main__.py +++ b/owocr/__main__.py @@ -1,9 +1,27 @@ import fire - -from owocr.run import run - +import inspect +from owocr.run import run, init_config def main(): + init_config() + + from owocr.run import config + fullargspec = inspect.getfullargspec(run) + old_defaults = fullargspec[0] + old_default_values = fullargspec[3] + new_defaults = [] + + if config.has_config: + index = 0 + for argument in old_defaults: + if config.get_general(argument) == None: + new_defaults.append(old_default_values[index]) + else: + new_defaults.append(config.get_general(argument)) + index += 1 + + run.__defaults__ = tuple(new_defaults) + fire.Fire(run) diff --git a/owocr/config.py b/owocr/config.py new file mode 100644 index 0000000..7d332c3 --- /dev/null +++ b/owocr/config.py @@ -0,0 +1,53 @@ +import os +import configparser + +class Config: + has_config = False + general_config = {} + engine_config = {} + + def _parse(self, value): + value = value.strip() + if value.lower() == 'false': + return False + if value.lower() == 'true': + return True + try: + int(value) + return int(value) + except ValueError: + pass + try: + float(value) + return float(value) + except ValueError: + pass + return value + + def __init__(self): + config_file = os.path.join(os.path.expanduser('~'),'.config','owocr_config.ini') + config = configparser.ConfigParser() + res = config.read(config_file) + + if len(res) != 0: + self.has_config = True + for key in config: + if key == 'general': + for sub_key in config[key]: + self.general_config[sub_key.lower()] = self._parse(config[key][sub_key]) + elif key != 'DEFAULT': + self.engine_config[key.lower()] = {} + for sub_key in config[key]: + self.engine_config[key.lower()][sub_key.lower()] = self._parse(config[key][sub_key]) + + def get_general(self, value): + try: + return self.general_config[value] + except KeyError: + return None + + def get_engine(self, value): + try: + return self.engine_config[value] + except KeyError: + return None \ No newline at end of file diff --git a/owocr/ocr.py b/owocr/ocr.py index e81d2ee..eda8fea 100644 --- a/owocr/ocr.py +++ b/owocr/ocr.py @@ -78,18 +78,13 @@ class MangaOcr: key = 'm' available = False - def __init__(self, config={'pretrained_model_name_or_path':'kha-white/manga-ocr-base','force_cpu':'False'}, pretrained_model_name_or_path='', force_cpu=False): + def __init__(self, config={'pretrained_model_name_or_path':'kha-white/manga-ocr-base','force_cpu': False}): if 'manga_ocr' not in sys.modules: logger.warning('manga-ocr not available, Manga OCR will not work!') else: - if pretrained_model_name_or_path == '': - pretrained_model_name_or_path = config['pretrained_model_name_or_path'] - if config['force_cpu'] == 'True': - force_cpu = True - logger.disable('manga_ocr') logger.info(f'Loading Manga OCR model') - self.model = MOCR(pretrained_model_name_or_path, force_cpu) + self.model = MOCR(config['pretrained_model_name_or_path'], config['force_cpu']) self.available = True logger.info('Manga OCR ready') diff --git a/owocr/run.py b/owocr/run.py index 7b5e87b..9413bb7 100644 --- a/owocr/run.py +++ b/owocr/run.py @@ -1,8 +1,6 @@ import sys import time import threading -import os -import configparser from pathlib import Path import fire @@ -21,6 +19,7 @@ from notifypy import Notify import inspect from owocr import * +from owocr.config import Config try: import win32gui @@ -31,6 +30,7 @@ try: except ImportError: pass +config = None class WindowsClipboardThread(threading.Thread): def __init__(self): @@ -197,6 +197,11 @@ def get_path_key(path): return path, path.lstat().st_mtime +def init_config(): + global config + config = Config() + + def run(read_from='clipboard', write_to='clipboard', engine='', @@ -205,6 +210,8 @@ def run(read_from='clipboard', delete_images=False ): """ + Japanese OCR client + Run OCR in the background, waiting for new images to appear either in system clipboard or a directory, or to be sent via a websocket. Recognized texts can be either saved to system clipboard, appended to a text file or sent via a websocket. @@ -227,56 +234,39 @@ def run(read_from='clipboard', websocket_port = 7331 notifications = False - config_file = os.path.join(os.path.expanduser('~'),'.config','owocr_config.ini') - config = configparser.ConfigParser() - res = config.read(config_file) + if config.has_config: + if config.get_general('engines'): + for config_engine in config.get_general('engines').split(','): + config_engines.append(config_engine.lower()) - if len(res) != 0: - try: - for config_engine in config['general']['engines'].split(','): - config_engines.append(config_engine.strip().lower()) - except KeyError: - pass + if config.get_general('logger_format'): + logger_format = config.get_general('logger_format') - try: - logger_format = config['general']['logger_format'].strip() - except KeyError: - pass + if config.get_general('engine_color'): + engine_color = config.get_general('engine_color') - try: - engine_color = config['general']['engine_color'].strip() - except KeyError: - pass + if config.get_general('delay_secs'): + delay_secs = config.get_general('delay_secs') - try: - delay_secs = float(config['general']['delay_secs'].strip()) - except KeyError: - pass + if config.get_general('websocket_port'): + websocket_port = config.get_general('websocket_port') - try: - websocket_port = int(config['general']['websocket_port'].strip()) - except KeyError: - pass - - try: - if config['general']['notifications'].strip().lower() == 'true': - notifications = True - except KeyError: - pass + if config.get_general('notifications'): + notifications = config.get_general('notifications') logger.configure(handlers=[{'sink': sys.stderr, 'format': logger_format}]) - if len(res) != 0: + if config.has_config: logger.info('Parsed config file') else: logger.warning('No config file, defaults will be used') for _,engine_class in sorted(inspect.getmembers(sys.modules[__name__], lambda x: hasattr(x, '__module__') and __package__ + '.ocr' in x.__module__ and inspect.isclass(x))): if len(config_engines) == 0 or engine_class.name in config_engines: - try: - engine_instance = engine_class(config[engine_class.name]) - except KeyError: + if config.get_engine(engine_class.name) == None: engine_instance = engine_class() + else: + engine_instance = engine_class(config.get_engine(engine_class.name)) if engine_instance.available: engine_instances.append(engine_instance) diff --git a/owocr_config.ini b/owocr_config.ini index 0c596cc..f6d4479 100644 --- a/owocr_config.ini +++ b/owocr_config.ini @@ -1,10 +1,16 @@ [general] ;engines = avision,glens,gvision,azure,mangaocr,winrtocr,easyocr,paddleocr +;engine = glens +;read_from = clipboard +;write_to = clipboard +;pause_at_startup = False ;logger_format = {time:HH:mm:ss.SSS} | {message} ;engine_color = cyan ;websocket_port = 7331 ;delay_secs = 0.5 ;notifications = False +;ignore_flag = False +;delete_images = False [winrtocr] ;url = http://aaa.xxx.yyy.zzz:8000 [azure]