Spaces:
Sleeping
Sleeping
HF Spaces: Errno13: file permission creating log file
Browse files- file_handler/file_utils.py +120 -30
- ui/gradio_ui.py +12 -9
- utils/get_config.py +118 -2
- utils/lib_loader.py +3 -1
- utils/logger.py +3 -1
file_handler/file_utils.py
CHANGED
|
@@ -1,11 +1,12 @@
|
|
| 1 |
# file_handler/file_utils.py
|
| 2 |
#import os
|
| 3 |
from pathlib import Path
|
|
|
|
| 4 |
from itertools import chain
|
| 5 |
from typing import List, Union, Any, Mapping
|
| 6 |
from PIL import Image
|
| 7 |
|
| 8 |
-
import utils.config as config
|
| 9 |
|
| 10 |
##SMY: Might be deprecated vis duplicated. See marker/marker/config/parser.py ~ https://github.com/datalab-to/marker/blob/master/marker/config/parser.py#L169
|
| 11 |
#def create_outputdir(root: Union[str, Path], out_dir:Union[str, Path] = None) -> Path: #List[Path]:
|
|
@@ -27,6 +28,87 @@ def create_outputdir(root: Union[str, Path], output_dir_string:str = None) -> Pa
|
|
| 27 |
output_dir.mkdir(mode=0o2644, parents=True, exist_ok=True)
|
| 28 |
return output_dir
|
| 29 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
def check_create_logfile(filename: str, dir_path: Union[str, Path]="logs") -> Path:
|
| 31 |
"""
|
| 32 |
check if log file exists, else create one and return the file path.
|
|
@@ -44,42 +126,53 @@ def check_create_logfile(filename: str, dir_path: Union[str, Path]="logs") -> Pa
|
|
| 44 |
|
| 45 |
# 1. Get the path of the current script's parent directory (the project folder).
|
| 46 |
# `__file__` is a special variable that holds the path to the current script.
|
| 47 |
-
#project_root = Path(__file__).parent.parent
|
| 48 |
-
|
| 49 |
-
# 1. Get the designated writable directory for Hugging Face Spaces: '/data'
|
| 50 |
-
writable_dir = Path("/data")
|
| 51 |
-
try:
|
| 52 |
-
if not writable_dir.is_dir():
|
| 53 |
-
writable_dir.mkdir(exist_ok=True)
|
| 54 |
-
except PermissionError: ##[Errno 13] Permission denied: '/home/user/app/logs/app_logging_2025-09-18.log'
|
| 55 |
-
warnings.warn("[Errno 13] Permission denied, possibly Persistent Storage not enable: attempting temp folder")
|
| 56 |
-
writable_dir = Path(tempfile.gettempdir()) #
|
| 57 |
-
|
| 58 |
-
# check log dir path
|
| 59 |
-
dir_path = dir_path if isinstance(dir_path, Path) else Path(dir_path)
|
| 60 |
|
| 61 |
# 2. Define the path for the logs directory.
|
| 62 |
# The `/` operator is overloaded to join paths easily.
|
| 63 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
|
| 65 |
-
# 3.
|
| 66 |
# `mkdir()` with `exist_ok=True` prevents a FileExistsError if the folder exists.
|
| 67 |
-
logs_dir
|
|
|
|
|
|
|
| 68 |
|
| 69 |
# 4. Create log file with a timestamp inside the new logs directory.
|
| 70 |
-
# This ensures a unique file is created
|
| 71 |
timestamp = datetime.datetime.now().strftime("%Y-%m-%d") #.strftime("%Y-%m-%d_%H-%M-%S")
|
| 72 |
log_file = logs_dir / f"{Path(filename).stem}_{timestamp}.log"
|
| 73 |
|
| 74 |
-
# 5. Check if the file exists (it won't,if it's not the same day).
|
| 75 |
-
if not log_file.exists():
|
| 76 |
# If the file doesn't exist, touch() will create an empty file.
|
| 77 |
-
log_file.touch()
|
| 78 |
|
| 79 |
-
print(f"Created log file at: {log_file}") ##debug
|
| 80 |
|
| 81 |
return log_file
|
| 82 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
def check_create_file(filename: str, dir_path: Union[str, Path]="logs") -> Path:
|
| 84 |
"""
|
| 85 |
check if File exists, else create one and return the file path.
|
|
@@ -91,8 +184,9 @@ def check_create_file(filename: str, dir_path: Union[str, Path]="logs") -> Path:
|
|
| 91 |
The pathlib.Path object for the file
|
| 92 |
"""
|
| 93 |
# Get project root
|
| 94 |
-
project_root = Path(__file__).
|
| 95 |
-
|
|
|
|
| 96 |
#file_dir = Path("logs") / file_dir if not isinstance(file_dir, Path) else Path(file_dir)
|
| 97 |
dir_path = dir_path if isinstance(dir_path, Path) else Path(dir_path)
|
| 98 |
|
|
@@ -101,7 +195,8 @@ def check_create_file(filename: str, dir_path: Union[str, Path]="logs") -> Path:
|
|
| 101 |
# `parents=True` creates any missing parent directories.
|
| 102 |
# `exist_ok=True` prevents an error if the directory already exists.
|
| 103 |
dir_path = project_root / dir_path
|
| 104 |
-
dir_path.
|
|
|
|
| 105 |
#dir_path.chmod(0)
|
| 106 |
|
| 107 |
file_path = dir_path / filename # Concatenate directory and filename to get full path
|
|
@@ -118,11 +213,6 @@ def check_create_file(filename: str, dir_path: Union[str, Path]="logs") -> Path:
|
|
| 118 |
|
| 119 |
return file_path
|
| 120 |
|
| 121 |
-
## debug
|
| 122 |
-
#from pathlib import Path
|
| 123 |
-
#from typing import Union
|
| 124 |
-
#print(f'file: {check_create_file("app_logging.log")}')
|
| 125 |
-
|
| 126 |
def is_file_with_extension(path_obj: Path) -> bool:
|
| 127 |
"""
|
| 128 |
Checks if a pathlib.Path object is a file and has a non-empty extension.
|
|
|
|
| 1 |
# file_handler/file_utils.py
|
| 2 |
#import os
|
| 3 |
from pathlib import Path
|
| 4 |
+
import sys
|
| 5 |
from itertools import chain
|
| 6 |
from typing import List, Union, Any, Mapping
|
| 7 |
from PIL import Image
|
| 8 |
|
| 9 |
+
#import utils.config as config ##SMY: currently unused
|
| 10 |
|
| 11 |
##SMY: Might be deprecated vis duplicated. See marker/marker/config/parser.py ~ https://github.com/datalab-to/marker/blob/master/marker/config/parser.py#L169
|
| 12 |
#def create_outputdir(root: Union[str, Path], out_dir:Union[str, Path] = None) -> Path: #List[Path]:
|
|
|
|
| 28 |
output_dir.mkdir(mode=0o2644, parents=True, exist_ok=True)
|
| 29 |
return output_dir
|
| 30 |
|
| 31 |
+
def find_file(file_name: str) -> Path: #configparser.ConfigParser:
|
| 32 |
+
"""
|
| 33 |
+
Finds file from the same directory, parent's sibling or grandparent directory of the calling script.
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
file_name: The name of the file to find.
|
| 37 |
+
|
| 38 |
+
Returns:
|
| 39 |
+
The path of the file.
|
| 40 |
+
|
| 41 |
+
Raises:
|
| 42 |
+
FileNotFoundError: If the file cannot be found.
|
| 43 |
+
Drawback:
|
| 44 |
+
Return the first result from the for loop iteration through the generator produced by rglob(). As soon as the first match is found, the function returns it, making the process very efficient by not searching any further but might not match the exact.
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
# 1. Get the current script's path, its parent and its grandparent directory
|
| 48 |
+
# Start the search from the directory of the file this function is in
|
| 49 |
+
try:
|
| 50 |
+
current_path = Path(sys.argv[0]).resolve()
|
| 51 |
+
except IndexError:
|
| 52 |
+
# Handle cases where sys.argv[0] might not exist (e.g., in some IDEs)
|
| 53 |
+
current_path = Path(__file__).resolve()
|
| 54 |
+
#current_path = Path('.').resolve() ##unreliable
|
| 55 |
+
|
| 56 |
+
parent_dir = current_path.parent
|
| 57 |
+
grandparent_dir = current_path.parent.parent
|
| 58 |
+
|
| 59 |
+
# Walk up the directory tree until the config file is found
|
| 60 |
+
'''
|
| 61 |
+
for parent in [current_path, *current_path.parents]:
|
| 62 |
+
config_path = parent / file_name
|
| 63 |
+
if config_path.is_file():
|
| 64 |
+
return config_path
|
| 65 |
+
raise FileNotFoundError(f"Configuration file '{file_name}' not found.")
|
| 66 |
+
'''
|
| 67 |
+
try:
|
| 68 |
+
# 1. Search the parent directory directly
|
| 69 |
+
parent_filepath = parent_dir / file_name
|
| 70 |
+
if parent_filepath.is_file():
|
| 71 |
+
return parent_filepath
|
| 72 |
+
|
| 73 |
+
# 2. Search the grandparent directory directly
|
| 74 |
+
grandparent_filepath = grandparent_dir / file_name
|
| 75 |
+
if grandparent_filepath.is_file():
|
| 76 |
+
return grandparent_filepath
|
| 77 |
+
|
| 78 |
+
# 3. Search recursively in all subdirectories of the grandparent.
|
| 79 |
+
# This will cover all sibling directories of the parent.
|
| 80 |
+
for p in grandparent_dir.rglob(file_name):
|
| 81 |
+
if p.is_file():
|
| 82 |
+
return p
|
| 83 |
+
|
| 84 |
+
return None
|
| 85 |
+
except Exception as exc:
|
| 86 |
+
return exc
|
| 87 |
+
|
| 88 |
+
def resolve_grandparent_object(gp_object:str):
|
| 89 |
+
###
|
| 90 |
+
# Create a Path object based on current file's location, resolve it to an absolute path,
|
| 91 |
+
# and then get its parent's parent using chained .parent calls or the parents[] attribute.
|
| 92 |
+
|
| 93 |
+
# 1. Get the current script's path, its parent and its grandparent directory
|
| 94 |
+
try:
|
| 95 |
+
current_path = Path(sys.argv[0]).resolve()
|
| 96 |
+
except IndexError:
|
| 97 |
+
# Handle cases where sys.argv[0] might not exist (e.g., in some IDEs)
|
| 98 |
+
#current_path = Path(__file__).resolve()
|
| 99 |
+
current_path = Path('.').resolve()
|
| 100 |
+
|
| 101 |
+
parent_dir = current_path.parent
|
| 102 |
+
grandparent_dir = current_path.parent.parent
|
| 103 |
+
|
| 104 |
+
#grandparent_dir = Path(__file__).resolve().parent.parent
|
| 105 |
+
|
| 106 |
+
sys.path.insert(0, f"{grandparent_dir}") #\\file_handler")
|
| 107 |
+
sys.path.insert(1, f"{grandparent_dir}\\{gp_object}")
|
| 108 |
+
#print(f"resolve: sys.path[0]: {sys.path[0]}") ##debug
|
| 109 |
+
#print(f"resolve: sys.path[1]: {sys.path[1]}") ##debug
|
| 110 |
+
|
| 111 |
+
|
| 112 |
def check_create_logfile(filename: str, dir_path: Union[str, Path]="logs") -> Path:
|
| 113 |
"""
|
| 114 |
check if log file exists, else create one and return the file path.
|
|
|
|
| 126 |
|
| 127 |
# 1. Get the path of the current script's parent directory (the project folder).
|
| 128 |
# `__file__` is a special variable that holds the path to the current script.
|
| 129 |
+
#project_root = Path(__file__).resolve().parent.parent
|
| 130 |
+
project_root = Path(__file__).resolve().parents[1] ##SMY: parents[1] gets the second-level parent (the grandparent)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
|
| 132 |
# 2. Define the path for the logs directory.
|
| 133 |
# The `/` operator is overloaded to join paths easily.
|
| 134 |
+
writable_dir = project_root / dir_path if isinstance(dir_path, str) else Path(dir_path)
|
| 135 |
+
|
| 136 |
+
try:
|
| 137 |
+
|
| 138 |
+
writable_dir.mkdir(mode=0o2644, parents=True, exist_ok=True)
|
| 139 |
+
except PermissionError: ##[Errno 13] Permission denied: '/home/user/app/logs/app_logging_2025-09-18.log'
|
| 140 |
+
warnings.warn("[Errno 13] Permission denied, possibly insufficient permission or Persistent Storage not enable: attempting chmod 0o2644")
|
| 141 |
+
#writable_dir = Path(tempfile.gettempdir()) #
|
| 142 |
+
writable_dir.mkdir(mode=0o2644, parents=True, exist_ok=True)
|
| 143 |
+
writable_dir.chmod(0o2644)
|
| 144 |
+
if not writable_dir.is_dir():
|
| 145 |
+
warnings.warn(f"Working without log files in directory: {writable_dir}")
|
| 146 |
|
| 147 |
+
# 3. Define and create the logs directory if it doesn't already exist.
|
| 148 |
# `mkdir()` with `exist_ok=True` prevents a FileExistsError if the folder exists.
|
| 149 |
+
logs_dir = writable_dir / dir_path #project_root / dir_path
|
| 150 |
+
if not logs_dir.is_dir():
|
| 151 |
+
logs_dir.mkdir(mode=0o2644, parents=True, exist_ok=True)
|
| 152 |
|
| 153 |
# 4. Create log file with a timestamp inside the new logs directory.
|
| 154 |
+
# This ensures a unique log file is created for the day the script runs.
|
| 155 |
timestamp = datetime.datetime.now().strftime("%Y-%m-%d") #.strftime("%Y-%m-%d_%H-%M-%S")
|
| 156 |
log_file = logs_dir / f"{Path(filename).stem}_{timestamp}.log"
|
| 157 |
|
| 158 |
+
# 5. Check if the file exists (it won't, if it's not the same day).
|
| 159 |
+
if not log_file.exists(): # or log_file.is_file():
|
| 160 |
# If the file doesn't exist, touch() will create an empty file.
|
| 161 |
+
log_file.touch(exist_ok=True)
|
| 162 |
|
| 163 |
+
#print(f"Created log file at: {log_file}") ##debug
|
| 164 |
|
| 165 |
return log_file
|
| 166 |
|
| 167 |
+
## debug
|
| 168 |
+
'''
|
| 169 |
+
from pathlib import Path
|
| 170 |
+
from typing import Union
|
| 171 |
+
resolve_grandparent_object("file_handler")
|
| 172 |
+
print(f'file: {check_create_logfile("app_logging.log")}')
|
| 173 |
+
'''
|
| 174 |
+
|
| 175 |
+
##SMY: to revisit. Make generic for any file apart from log files
|
| 176 |
def check_create_file(filename: str, dir_path: Union[str, Path]="logs") -> Path:
|
| 177 |
"""
|
| 178 |
check if File exists, else create one and return the file path.
|
|
|
|
| 184 |
The pathlib.Path object for the file
|
| 185 |
"""
|
| 186 |
# Get project root
|
| 187 |
+
#project_root = Path(__file__).resolve().parent.parent ##SMY: `__file__` is a special variable pointing to current file`
|
| 188 |
+
project_root = Path(__file__).resolve().parents[1] ##SMY: leverages parents. Get 2nd level
|
| 189 |
+
|
| 190 |
#file_dir = Path("logs") / file_dir if not isinstance(file_dir, Path) else Path(file_dir)
|
| 191 |
dir_path = dir_path if isinstance(dir_path, Path) else Path(dir_path)
|
| 192 |
|
|
|
|
| 195 |
# `parents=True` creates any missing parent directories.
|
| 196 |
# `exist_ok=True` prevents an error if the directory already exists.
|
| 197 |
dir_path = project_root / dir_path
|
| 198 |
+
if not dir_path.is_dir():
|
| 199 |
+
dir_path.mkdir(parents=True, exist_ok=True, mode=0o2664) #, mode=0o2644)
|
| 200 |
#dir_path.chmod(0)
|
| 201 |
|
| 202 |
file_path = dir_path / filename # Concatenate directory and filename to get full path
|
|
|
|
| 213 |
|
| 214 |
return file_path
|
| 215 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
def is_file_with_extension(path_obj: Path) -> bool:
|
| 217 |
"""
|
| 218 |
Checks if a pathlib.Path object is a file and has a non-empty extension.
|
ui/gradio_ui.py
CHANGED
|
@@ -21,6 +21,8 @@ from converters.pdf_to_md import PdfToMarkdownConverter, init_worker
|
|
| 21 |
#from converters.md_to_pdf import MarkdownToPdfConverter
|
| 22 |
#from converters.html_to_md import HtmlToMarkdownConverter ##SMY: PENDING: implementation
|
| 23 |
|
|
|
|
|
|
|
| 24 |
from utils.get_config import get_config_value
|
| 25 |
from utils.logger import get_logger
|
| 26 |
|
|
@@ -79,15 +81,16 @@ def convert_batch(
|
|
| 79 |
return "Initialising ProcessPool: No files uploaded."
|
| 80 |
|
| 81 |
# Get config values if not provided
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
|
|
|
| 91 |
|
| 92 |
# Create the initargs tuple from the Gradio inputs: # 'files' is an iterable, and handled separately.
|
| 93 |
init_args = (
|
|
|
|
| 21 |
#from converters.md_to_pdf import MarkdownToPdfConverter
|
| 22 |
#from converters.html_to_md import HtmlToMarkdownConverter ##SMY: PENDING: implementation
|
| 23 |
|
| 24 |
+
from file_handler.file_utils import find_file
|
| 25 |
+
|
| 26 |
from utils.get_config import get_config_value
|
| 27 |
from utils.logger import get_logger
|
| 28 |
|
|
|
|
| 81 |
return "Initialising ProcessPool: No files uploaded."
|
| 82 |
|
| 83 |
# Get config values if not provided
|
| 84 |
+
config_file = find_file("config.ini") ##from file_handler.file_utils
|
| 85 |
+
model_id = get_config_value(config_file, "MARKER_CAP", "MODEL_ID") if not model_id else model_id
|
| 86 |
+
openai_base_url = get_config_value(config_file, "MARKER_CAP", "OPENAI_BASE_URL") if not openai_base_url else openai_base_url
|
| 87 |
+
openai_image_format = get_config_value(config_file, "MARKER_CAP", "OPENAI_IMAGE_FORMAT") if not openai_image_format else openai_image_format
|
| 88 |
+
max_workers = get_config_value(config_file, "MARKER_CAP", "MAX_WORKERS") if not max_workers else max_workers
|
| 89 |
+
max_retries = get_config_value(config_file, "MARKER_CAP", "MAX_RETRIES") if not max_retries else max_retries
|
| 90 |
+
output_format = get_config_value(config_file, "MARKER_CAP", "OUTPUT_FORMAT") if not output_format else output_format
|
| 91 |
+
output_dir_string = str(get_config_value(config_file, "MARKER_CAP", "OUTPUT_DIR") if not output_dir_string else output_dir_string)
|
| 92 |
+
use_llm = get_config_value(config_file, "MARKER_CAP", "USE_LLM") if not use_llm else use_llm
|
| 93 |
+
page_range = get_config_value(config_file,"MARKER_CAP", "PAGE_RANGE") if not page_range else page_range
|
| 94 |
|
| 95 |
# Create the initargs tuple from the Gradio inputs: # 'files' is an iterable, and handled separately.
|
| 96 |
init_args = (
|
utils/get_config.py
CHANGED
|
@@ -4,7 +4,88 @@ from pathlib import Path
|
|
| 4 |
#from utils.get_arg_name import get_arg_name_as_string
|
| 5 |
import traceback
|
| 6 |
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
""" Load config file, locate section, read parameter and return value """
|
| 9 |
|
| 10 |
try:
|
|
@@ -15,4 +96,39 @@ def get_config_value(section:str, parameter:str, fallback:str=None, configfile:
|
|
| 15 |
except Exception as exc:
|
| 16 |
tb = traceback.format_exc()
|
| 17 |
raise RuntimeWarning(f"Error loading config: {exc}\n{tb}")
|
| 18 |
-
#pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
#from utils.get_arg_name import get_arg_name_as_string
|
| 5 |
import traceback
|
| 6 |
|
| 7 |
+
'''
|
| 8 |
+
##debug
|
| 9 |
+
import sys
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
#base_grandparent = Path(__file__).resolve().parent.parent
|
| 12 |
+
grandparent_dir = Path('.').resolve() #.parent.parent
|
| 13 |
+
sys.path.insert(0, f"{grandparent_dir}") #\\file_handler")
|
| 14 |
+
##end debug
|
| 15 |
+
#'''
|
| 16 |
+
#import file_handler
|
| 17 |
+
from file_handler.file_utils import find_file
|
| 18 |
+
|
| 19 |
+
def get_config_value(config_file:Path, section_key:str, parameter:str, fallback:str=None) -> str: # configfile: Union[str, Path]="utils\\config.ini"):
|
| 20 |
+
""" Load config file, locate section, read parameter and return value
|
| 21 |
+
|
| 22 |
+
Args:
|
| 23 |
+
section_key: The section key
|
| 24 |
+
parameter: The parameter key to read from the configuration file
|
| 25 |
+
fallback: The fallback parameter if the parameter value not found
|
| 26 |
+
config_file: The configuration file to load.
|
| 27 |
+
|
| 28 |
+
Returns:
|
| 29 |
+
The key parameter value.
|
| 30 |
+
|
| 31 |
+
Raises:
|
| 32 |
+
RuntimeWarning: If the configuration file cannot be loaded or parameter key found.
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
try:
|
| 36 |
+
#config_file = find_config(config_file)
|
| 37 |
+
cfg = config()
|
| 38 |
+
if config_file.is_file():
|
| 39 |
+
cfg.read(config_file)
|
| 40 |
+
param_value = cfg[section_key].get(option=parameter, fallback=fallback) #"C:\\Dat\\dev\\gtk3-runtime\\bin")
|
| 41 |
+
return param_value
|
| 42 |
+
else:
|
| 43 |
+
raise RuntimeWarning(f"Configuration file not found: {config_file}")
|
| 44 |
+
except KeyError as exc:
|
| 45 |
+
tb = traceback.format_exc()
|
| 46 |
+
raise RuntimeWarning(f"Error loading parameter key: {exc}\n{tb}")
|
| 47 |
+
except Exception as exc:
|
| 48 |
+
tb = traceback.format_exc()
|
| 49 |
+
raise RuntimeWarning(f"Error loading config or parameter key: {exc}\n{tb}")
|
| 50 |
+
#pass
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
##debug
|
| 55 |
+
'''
|
| 56 |
+
config_file_path = find_file("config.ini") #file_handler.file_utils.
|
| 57 |
+
config_value = get_config_value(config_file_path, "LIBRARIES_CAP", "WEASYPRINT_DLL_DIRECTORIES")
|
| 58 |
+
print(f"config value: {config_value}")
|
| 59 |
+
'''
|
| 60 |
+
|
| 61 |
+
##SMY: moved to file_handler.file_utils as find_file()
|
| 62 |
+
def find_config(config_file_name: str = "config.ini") -> config: #configparser.ConfigParser:
|
| 63 |
+
"""
|
| 64 |
+
Finds and loads a configuration file named 'config_file_name' from the
|
| 65 |
+
same directory or a parent directory of the calling script.
|
| 66 |
+
|
| 67 |
+
Args:
|
| 68 |
+
config_file_name: The name of the configuration file to load.
|
| 69 |
+
|
| 70 |
+
Returns:
|
| 71 |
+
A ConfigParser object with the loaded configuration.
|
| 72 |
+
|
| 73 |
+
Raises:
|
| 74 |
+
FileNotFoundError: If the configuration file cannot be found.
|
| 75 |
+
"""
|
| 76 |
+
# Start the search from the directory of the file this function is in
|
| 77 |
+
search_path = Path(__file__).resolve().parent
|
| 78 |
+
|
| 79 |
+
# Walk up the directory tree until the config file is found
|
| 80 |
+
for parent in [search_path, *search_path.parents]:
|
| 81 |
+
config_path = parent / config_file_name
|
| 82 |
+
if config_path.is_file():
|
| 83 |
+
return config_path
|
| 84 |
+
raise FileNotFoundError(f"Configuration file '{config_file_name}' not found.")
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def get_config_value_old(section:str, parameter:str, fallback:str=None, configfile: Union[str, Path]="utils\\config.ini"):
|
| 89 |
""" Load config file, locate section, read parameter and return value """
|
| 90 |
|
| 91 |
try:
|
|
|
|
| 96 |
except Exception as exc:
|
| 97 |
tb = traceback.format_exc()
|
| 98 |
raise RuntimeWarning(f"Error loading config: {exc}\n{tb}")
|
| 99 |
+
#pass
|
| 100 |
+
|
| 101 |
+
##TODO: //STOP
|
| 102 |
+
# ##SMY: HF Space RuntimeWarning: Error loading config: 'MARKER_CAP'
|
| 103 |
+
'''
|
| 104 |
+
from pathlib import Path
|
| 105 |
+
import configparser
|
| 106 |
+
from typing import Optional
|
| 107 |
+
|
| 108 |
+
def load_config(config_file_name: str = "config.ini") -> configparser.ConfigParser:
|
| 109 |
+
"""
|
| 110 |
+
Finds and loads a configuration file named 'config_file_name' from the
|
| 111 |
+
same directory or a parent directory of the calling script.
|
| 112 |
+
|
| 113 |
+
Args:
|
| 114 |
+
config_file_name: The name of the configuration file to load.
|
| 115 |
+
|
| 116 |
+
Returns:
|
| 117 |
+
A ConfigParser object with the loaded configuration.
|
| 118 |
+
|
| 119 |
+
Raises:
|
| 120 |
+
FileNotFoundError: If the configuration file cannot be found.
|
| 121 |
+
"""
|
| 122 |
+
# Start the search from the directory of the file this function is in
|
| 123 |
+
search_path = Path(__file__).resolve().parent
|
| 124 |
+
|
| 125 |
+
# Walk up the directory tree until the config file is found
|
| 126 |
+
for parent in [search_path, *search_path.parents]:
|
| 127 |
+
config_path = parent / config_file_name
|
| 128 |
+
if config_path.is_file():
|
| 129 |
+
config = configparser.ConfigParser()
|
| 130 |
+
config.read(config_path)
|
| 131 |
+
return config
|
| 132 |
+
|
| 133 |
+
raise FileNotFoundError(f"Configuration file '{config_file_name}' not found.")
|
| 134 |
+
'''
|
utils/lib_loader.py
CHANGED
|
@@ -24,7 +24,9 @@ def set_weasyprint_library(libpath: Union[str, Path] = None, config_file: Union[
|
|
| 24 |
cfg.read(config_file) #"utils\\config.ini")
|
| 25 |
lib_path = cfg["LIBRARIES_CAP"].get(f"WEASYPRINT_DLL_DIRECTORIES", "C:\\Dat\\dev\\gtk3-runtime\\bin")
|
| 26 |
'''
|
| 27 |
-
|
|
|
|
|
|
|
| 28 |
|
| 29 |
# Check if the file exists before attempting to load it
|
| 30 |
#if not os.path.exists(libobject):
|
|
|
|
| 24 |
cfg.read(config_file) #"utils\\config.ini")
|
| 25 |
lib_path = cfg["LIBRARIES_CAP"].get(f"WEASYPRINT_DLL_DIRECTORIES", "C:\\Dat\\dev\\gtk3-runtime\\bin")
|
| 26 |
'''
|
| 27 |
+
from file_handler.file_utils import find_file
|
| 28 |
+
config_file = find_file("config.ini") ##from file_handler.file_utils
|
| 29 |
+
lib_path = get_config_value(config_file, "LIBRARIES_CAP", "WEASYPRINT_DLL_DIRECTORIES") if not libpath else "C:\\msys64\\mingw64\\bin"
|
| 30 |
|
| 31 |
# Check if the file exists before attempting to load it
|
| 32 |
#if not os.path.exists(libobject):
|
utils/logger.py
CHANGED
|
@@ -5,7 +5,7 @@ import logging
|
|
| 5 |
import sys
|
| 6 |
from datetime import datetime, timezone
|
| 7 |
|
| 8 |
-
'''
|
| 9 |
def get_logger(name: str) -> logging.Logger:
|
| 10 |
"""
|
| 11 |
Returns a logger configured with a console handler.
|
|
@@ -67,6 +67,8 @@ def setup_logging(level: int = None) -> None:
|
|
| 67 |
#file_handler = logging.FileHandler("logs/app_logging.log", mode="a", encoding="utf-8")
|
| 68 |
from file_handler.file_utils import check_create_logfile
|
| 69 |
file_handler = logging.FileHandler(check_create_logfile("app_logging.log"), mode="a", encoding="utf-8")
|
|
|
|
|
|
|
| 70 |
file_handler.setFormatter(JsonFormatter())
|
| 71 |
|
| 72 |
root = logging.getLogger()
|
|
|
|
| 5 |
import sys
|
| 6 |
from datetime import datetime, timezone
|
| 7 |
|
| 8 |
+
''' ##SMY: discarded
|
| 9 |
def get_logger(name: str) -> logging.Logger:
|
| 10 |
"""
|
| 11 |
Returns a logger configured with a console handler.
|
|
|
|
| 67 |
#file_handler = logging.FileHandler("logs/app_logging.log", mode="a", encoding="utf-8")
|
| 68 |
from file_handler.file_utils import check_create_logfile
|
| 69 |
file_handler = logging.FileHandler(check_create_logfile("app_logging.log"), mode="a", encoding="utf-8")
|
| 70 |
+
## Getting filepermission error
|
| 71 |
+
|
| 72 |
file_handler.setFormatter(JsonFormatter())
|
| 73 |
|
| 74 |
root = logging.getLogger()
|