abstract-utilities 0.2.2.450__py3-none-any.whl → 0.2.2.452__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of abstract-utilities might be problematic. Click here for more details.
- abstract_utilities/__init__.py +17 -43
- abstract_utilities/abstract_classes.py +49 -0
- abstract_utilities/class_utils.py +39 -3
- abstract_utilities/cmd_utils/imports/__init__.py +1 -0
- abstract_utilities/cmd_utils/imports/imports.py +10 -0
- abstract_utilities/cmd_utils/pexpect_utils.py +310 -0
- abstract_utilities/cmd_utils/user_utils.py +1 -1
- abstract_utilities/compare_utils/__init__.py +3 -0
- abstract_utilities/compare_utils/best_match.py +150 -0
- abstract_utilities/{compare_utils.py → compare_utils/compare_utils.py} +1 -1
- abstract_utilities/compare_utils/find_value.py +105 -0
- abstract_utilities/dynimport.py +7 -15
- abstract_utilities/env_utils/__init__.py +3 -0
- abstract_utilities/env_utils/abstractEnv.py +129 -0
- abstract_utilities/env_utils/envy_it.py +33 -0
- abstract_utilities/env_utils/imports/__init__.py +2 -0
- abstract_utilities/env_utils/imports/imports.py +8 -0
- abstract_utilities/env_utils/imports/utils.py +122 -0
- abstract_utilities/file_utils/__init__.py +3 -0
- abstract_utilities/file_utils/file_utils/__init__.py +7 -0
- abstract_utilities/file_utils/file_utils/file_filters.py +104 -0
- abstract_utilities/{robust_reader → file_utils/file_utils}/file_reader.py +5 -19
- abstract_utilities/{robust_readers/file_filters.py → file_utils/file_utils/file_utils.py} +2 -1
- abstract_utilities/{robust_readers → file_utils/file_utils}/filter_params.py +1 -38
- abstract_utilities/file_utils/file_utils/find_collect.py +153 -0
- abstract_utilities/file_utils/file_utils/imports.py +1 -0
- abstract_utilities/file_utils/file_utils/map_utils.py +29 -0
- abstract_utilities/{robust_reader → file_utils/file_utils}/pdf_utils.py +1 -9
- abstract_utilities/file_utils/imports/__init__.py +5 -0
- abstract_utilities/file_utils/imports/classes.py +381 -0
- abstract_utilities/file_utils/imports/constants.py +39 -0
- abstract_utilities/file_utils/imports/file_functions.py +10 -0
- abstract_utilities/file_utils/imports/imports.py +13 -0
- abstract_utilities/file_utils/imports/module_imports.py +10 -0
- abstract_utilities/file_utils/req.py +329 -0
- abstract_utilities/json_utils.py +35 -0
- abstract_utilities/log_utils.py +14 -3
- abstract_utilities/path_utils.py +90 -6
- abstract_utilities/read_write_utils.py +99 -156
- abstract_utilities/robust_reader/__init__.py +1 -1
- abstract_utilities/robust_reader/imports/__init__.py +1 -0
- abstract_utilities/robust_reader/imports/imports.py +12 -0
- abstract_utilities/robust_readers/__init__.py +0 -1
- abstract_utilities/robust_readers/imports.py +8 -0
- abstract_utilities/robust_readers/initFuncGen.py +92 -76
- abstract_utilities/safe_utils.py +133 -0
- abstract_utilities/ssh_utils/__init__.py +3 -0
- abstract_utilities/ssh_utils/classes.py +127 -0
- abstract_utilities/ssh_utils/imports.py +10 -0
- abstract_utilities/ssh_utils/pexpect_utils.py +315 -0
- abstract_utilities/ssh_utils/utils.py +188 -0
- abstract_utilities/string_utils.py +12 -0
- abstract_utilities/type_utils.py +0 -1
- {abstract_utilities-0.2.2.450.dist-info → abstract_utilities-0.2.2.452.dist-info}/METADATA +5 -3
- abstract_utilities-0.2.2.452.dist-info/RECORD +84 -0
- abstract_utilities-0.2.2.450.dist-info/RECORD +0 -49
- {abstract_utilities-0.2.2.450.dist-info → abstract_utilities-0.2.2.452.dist-info}/WHEEL +0 -0
- {abstract_utilities-0.2.2.450.dist-info → abstract_utilities-0.2.2.452.dist-info}/top_level.txt +0 -0
|
@@ -1,115 +1,38 @@
|
|
|
1
1
|
"""
|
|
2
2
|
read_write_utils.py
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
-------------------
|
|
4
|
+
Unified read/write utility for safe file operations.
|
|
5
|
+
Supports:
|
|
6
|
+
- Writing content to a file
|
|
7
|
+
- Reading content from a file
|
|
8
|
+
- Creating and reading if missing
|
|
9
|
+
- Detecting file/content params via positional args or kwargs
|
|
6
10
|
|
|
7
11
|
Usage:
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
1. Write content to a file.
|
|
11
|
-
2. Read content from a file.
|
|
12
|
-
3. Check if a string has a file extension.
|
|
13
|
-
4. Read from or write to a file depending on the number of arguments.
|
|
14
|
-
5. Create a file if it does not exist, then read from it.
|
|
12
|
+
from abstract_utilities.read_write_utils import *
|
|
13
|
+
"""
|
|
15
14
|
|
|
16
|
-
Each function includes a docstring to further explain its purpose, input parameters, and return values.
|
|
17
15
|
import os
|
|
16
|
+
from .ssh_utils.utils import run_cmd
|
|
17
|
+
from .abstract_classes import run_pruned_func
|
|
18
|
+
_FILE_PATH_KEYS = ['file', 'filepath', 'file_path', 'path', 'directory', 'f', 'dst', 'dest']
|
|
19
|
+
_CONTENTS_KEYS = ['cont', 'content', 'contents', 'data', 'datas', 'dat', 'src', 'source']
|
|
18
20
|
|
|
19
|
-
# File and Directory Operations
|
|
20
|
-
os.rename(src, dst) # Rename a file or directory
|
|
21
|
-
os.remove(path) # Remove a file
|
|
22
|
-
os.unlink(path) # Alias for os.remove()
|
|
23
|
-
os.rmdir(path) # Remove an empty directory
|
|
24
|
-
os.makedirs(path) # Create directories recursively
|
|
25
|
-
os.makedirs(path, exist_ok=True) # Create directories, ignore if exists
|
|
26
|
-
os.mkdir(path) # Create a single directory
|
|
27
|
-
os.listdir(path) # List files and directories in a path
|
|
28
|
-
os.chdir(path) # Change current working directory
|
|
29
|
-
os.getcwd() # Get current working directory
|
|
30
|
-
os.stat(path) # Get file/directory information
|
|
31
|
-
os.lstat(path) # Get symbolic link information
|
|
32
|
-
os.symlink(src, dst) # Create a symbolic link
|
|
33
|
-
os.readlink(path) # Read the target of a symbolic link
|
|
34
|
-
os.getcwd() # Get current working directory
|
|
35
|
-
os.chdir(path) # Change current working directory
|
|
36
|
-
|
|
37
|
-
# File and Directory Information
|
|
38
|
-
os.path.exists(path) # Check if a path exists
|
|
39
|
-
os.path.isfile(path) # Check if a path points to a file
|
|
40
|
-
os.path.isdir(path) # Check if a path points to a directory
|
|
41
|
-
os.path.islink(path) # Check if a path points to a symbolic link
|
|
42
|
-
os.path.abspath(path) # Get the absolute path of a file/directory
|
|
43
|
-
os.path.basename(path) # Get the base name of a path
|
|
44
|
-
os.path.dirname(path) # Get the directory name of a path
|
|
45
|
-
os.path.join(path1, path2, ...) # Join path components into a single path
|
|
46
|
-
|
|
47
|
-
# File Permissions
|
|
48
|
-
os.chmod(path, mode) # Change file permissions
|
|
49
|
-
os.access(path, mode) # Check if a file is accessible with given mode
|
|
50
|
-
|
|
51
|
-
# File Times
|
|
52
|
-
os.path.getatime(path) # Get last access time of a file
|
|
53
|
-
os.path.getmtime(path) # Get last modification time of a file
|
|
54
|
-
os.path.getctime(path) # Get creation time of a file
|
|
55
|
-
os.utime(path, times) # Set access and modification times
|
|
56
|
-
|
|
57
|
-
# Working with Paths
|
|
58
|
-
os.path.split(path) # Split a path into (head, tail)
|
|
59
|
-
os.path.splitext(path) # Split a path into (root, ext)
|
|
60
|
-
os.path.normpath(path) # Normalize a path (e.g., convert slashes)
|
|
61
|
-
|
|
62
|
-
# Other
|
|
63
|
-
os.path.samefile(path1, path2) # Check if two paths refer to the same file
|
|
64
|
-
|
|
65
|
-
# Directory Traversal
|
|
66
|
-
for root, dirs, files in os.walk(top, topdown=True):
|
|
67
|
-
# Traverse a directory tree, yielding root, dirs, and files lists
|
|
68
|
-
|
|
69
|
-
# Temporary Files and Directories
|
|
70
|
-
import tempfile
|
|
71
|
-
tempfile.mkstemp() # Create a temporary file
|
|
72
|
-
tempfile.mkdtemp() # Create a temporary directory
|
|
73
|
-
tempfile.TemporaryFile() # Create a temporary file object
|
|
74
|
-
|
|
75
|
-
# Environment Variables
|
|
76
|
-
os.environ # Dictionary of environment variables
|
|
77
|
-
os.environ['VAR_NAME'] # Access an environment variable
|
|
78
|
-
os.environ.get('VAR_NAME') # Access an environment variable (with default)
|
|
79
|
-
|
|
80
|
-
# Path Manipulation
|
|
81
|
-
os.path.abspath(path) # Convert relative path to absolute path
|
|
82
|
-
os.path.join(path1, path2, ...) # Join paths together
|
|
83
|
-
os.path.split(path) # Split a path into directory and filename
|
|
84
|
-
os.path.dirname(path) # Get the directory part of a path
|
|
85
|
-
os.path.basename(path) # Get the filename part of a path
|
|
86
|
-
os.path.exists(path) # Check if a path exists
|
|
87
|
-
os.path.isfile(path) # Check if a path points to a file
|
|
88
|
-
os.path.isdir(path) # Check if a path points to a directory
|
|
89
|
-
|
|
90
|
-
# File Permissions
|
|
91
|
-
os.chmod(path, mode) # Change file permissions
|
|
92
|
-
|
|
93
|
-
# Miscellaneous
|
|
94
|
-
os.getpid() # Get the current process ID
|
|
95
|
-
os.getlogin() # Get the name of the logged-in user
|
|
96
|
-
|
|
97
|
-
"""
|
|
98
|
-
import os
|
|
99
|
-
def break_down_find_existing(path):
|
|
100
|
-
test_path = ''
|
|
101
|
-
for part in path.split(os.sep):
|
|
102
|
-
test_path = os.path.join(test_path, part)
|
|
103
|
-
if not os.path.exists(test_path):
|
|
104
|
-
return test_path if test_path else None
|
|
105
|
-
return test_path
|
|
106
21
|
|
|
22
|
+
# --- Helper utilities --------------------------------------------------------
|
|
107
23
|
def string_in_keys(strings, kwargs):
|
|
108
|
-
|
|
24
|
+
"""Find a matching keyword in kwargs that contains any of the given substrings."""
|
|
25
|
+
for key in kwargs:
|
|
26
|
+
for s in strings:
|
|
27
|
+
if s.lower() in key.lower():
|
|
28
|
+
return key
|
|
29
|
+
return None
|
|
30
|
+
|
|
109
31
|
|
|
110
32
|
def get_path(paths):
|
|
33
|
+
"""Return the first valid path among given paths."""
|
|
111
34
|
for path in paths:
|
|
112
|
-
if isinstance(path,str):
|
|
35
|
+
if isinstance(path, str):
|
|
113
36
|
if os.path.isfile(path):
|
|
114
37
|
return path
|
|
115
38
|
dirname = os.path.dirname(path)
|
|
@@ -117,83 +40,103 @@ def get_path(paths):
|
|
|
117
40
|
return path
|
|
118
41
|
return None
|
|
119
42
|
|
|
43
|
+
|
|
44
|
+
def break_down_find_existing(path):
|
|
45
|
+
"""Return the first non-existent subpath within a path chain."""
|
|
46
|
+
test_path = ''
|
|
47
|
+
for part in path.split(os.sep):
|
|
48
|
+
test_path = os.path.join(test_path, part)
|
|
49
|
+
if not os.path.exists(test_path):
|
|
50
|
+
return test_path if test_path else None
|
|
51
|
+
return test_path
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
# --- Parameter parsing --------------------------------------------------------
|
|
120
55
|
def check_read_write_params(*args, **kwargs):
|
|
121
|
-
|
|
122
|
-
contents
|
|
123
|
-
|
|
124
|
-
|
|
56
|
+
"""
|
|
57
|
+
Determine file_path and contents from arguments.
|
|
58
|
+
Returns a tuple: (file_path, contents)
|
|
59
|
+
"""
|
|
60
|
+
file_key = string_in_keys(_FILE_PATH_KEYS, kwargs)
|
|
61
|
+
content_key = string_in_keys(_CONTENTS_KEYS, kwargs)
|
|
62
|
+
|
|
63
|
+
file_path = kwargs.get(file_key) if file_key else None
|
|
64
|
+
contents = kwargs.get(content_key) if content_key else None
|
|
125
65
|
|
|
126
|
-
# Handle positional
|
|
66
|
+
# Handle positional args (fallback)
|
|
127
67
|
if file_path is None and len(args) > 0:
|
|
128
68
|
file_path = args[0]
|
|
129
69
|
if contents is None and len(args) > 1:
|
|
130
70
|
contents = args[1]
|
|
131
|
-
elif contents is None and len(args) > 0 and file_path != args[0]:
|
|
132
|
-
contents = args[0]
|
|
133
|
-
|
|
134
|
-
if file_path is None or contents is None:
|
|
135
|
-
raise ValueError("Both 'file_path' and 'contents' (or 'data') are required.")
|
|
136
71
|
|
|
72
|
+
if file_path is None:
|
|
73
|
+
raise ValueError("Missing file_path argument.")
|
|
137
74
|
return file_path, contents
|
|
138
75
|
|
|
139
|
-
def write_to_file(file_path=None, contents=None,*args, **kwargs):
|
|
140
|
-
"""
|
|
141
|
-
Write contents to a file. If the file does not exist, it is created.
|
|
142
|
-
|
|
143
|
-
Args:
|
|
144
|
-
file_path: The path of the file to write to.
|
|
145
|
-
contents: The content to write to the file.
|
|
146
|
-
|
|
147
|
-
Returns:
|
|
148
|
-
The contents that were written to the file.
|
|
149
|
-
"""
|
|
150
|
-
params = check_read_write_params(file_path=file_path, contents=contents,*args, **kwargs)
|
|
151
|
-
if params:
|
|
152
|
-
with open(params[0], 'w', encoding='UTF-8') as f:
|
|
153
|
-
f.write(params[1])
|
|
154
|
-
return contents
|
|
155
|
-
|
|
156
76
|
|
|
157
|
-
|
|
77
|
+
# --- Core functionality -------------------------------------------------------
|
|
78
|
+
def write_to_file(*args, **kwargs):
|
|
158
79
|
"""
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
file_path: The path of the file to read from.
|
|
163
|
-
|
|
164
|
-
Returns:
|
|
165
|
-
The contents of the file.
|
|
80
|
+
Write contents to a file (create if missing).
|
|
81
|
+
|
|
82
|
+
Returns the file_path written.
|
|
166
83
|
"""
|
|
167
|
-
|
|
84
|
+
file_path, contents = check_read_write_params(*args, **kwargs)
|
|
85
|
+
if contents is None:
|
|
86
|
+
raise ValueError("Missing contents to write.")
|
|
87
|
+
|
|
88
|
+
os.makedirs(os.path.dirname(file_path) or ".", exist_ok=True)
|
|
89
|
+
with open(file_path, "w", encoding="utf-8") as f:
|
|
90
|
+
f.write(str(contents))
|
|
91
|
+
return file_path
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def read_from_file(file_path,**kwargs):
|
|
95
|
+
user_at_host = kwargs.get("user_at_host")
|
|
96
|
+
if user_at_host:
|
|
97
|
+
kwargs["cwd"] = kwargs.get('cwd') or os.path.dirname(file_path)
|
|
98
|
+
basename = os.path.basename(file_path)
|
|
99
|
+
kwargs["cmd"] = f'cat {basename}'
|
|
100
|
+
return run_pruned_func(run_cmd,**kwargs)
|
|
101
|
+
"""Read text content from a file."""
|
|
102
|
+
with open(file_path, "r", encoding="utf-8") as f:
|
|
168
103
|
return f.read()
|
|
169
104
|
|
|
170
|
-
|
|
105
|
+
|
|
106
|
+
def create_and_read_file(*args, **kwargs):
|
|
171
107
|
"""
|
|
172
|
-
Create
|
|
173
|
-
|
|
174
|
-
Args:
|
|
175
|
-
file_path: The path of the file to create and read from.
|
|
176
|
-
contents: The content to write to the file if it does not exist.
|
|
177
|
-
|
|
178
|
-
Returns:
|
|
179
|
-
The contents of the file.
|
|
108
|
+
Create the file (if missing) and read contents from it.
|
|
180
109
|
"""
|
|
110
|
+
file_path, contents = check_read_write_params(*args, **kwargs)
|
|
181
111
|
if not os.path.isfile(file_path):
|
|
182
|
-
write_to_file(
|
|
112
|
+
write_to_file(file_path, contents or "")
|
|
183
113
|
return read_from_file(file_path)
|
|
114
|
+
|
|
115
|
+
|
|
184
116
|
def is_file_extension(obj: str) -> bool:
|
|
185
|
-
"""
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
Returns:
|
|
192
|
-
True if the string has a file extension, False otherwise.
|
|
193
|
-
"""
|
|
194
|
-
return len(obj) >= 4 and '.' in obj[-4:-3]
|
|
117
|
+
"""Return True if obj looks like a filename with extension."""
|
|
118
|
+
if not isinstance(obj, str):
|
|
119
|
+
return False
|
|
120
|
+
root, ext = os.path.splitext(obj)
|
|
121
|
+
return bool(root and ext)
|
|
122
|
+
|
|
195
123
|
|
|
196
124
|
def delete_file(file_path: str):
|
|
125
|
+
"""Safely delete a file if it exists."""
|
|
197
126
|
if os.path.isfile(file_path):
|
|
198
127
|
os.remove(file_path)
|
|
128
|
+
return True
|
|
129
|
+
return False
|
|
130
|
+
|
|
199
131
|
|
|
132
|
+
def get_content_lines(*args, **kwargs):
|
|
133
|
+
"""Return a list of lines from string or file path."""
|
|
134
|
+
file_path, contents = check_read_write_params(*args, **kwargs)
|
|
135
|
+
if os.path.isfile(file_path):
|
|
136
|
+
contents = read_from_file(filepath)
|
|
137
|
+
|
|
138
|
+
if isinstance(contents, str):
|
|
139
|
+
return contents.splitlines()
|
|
140
|
+
elif isinstance(contents, list):
|
|
141
|
+
return contents
|
|
142
|
+
return []
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
from
|
|
1
|
+
from ..file_utils import *
|
|
2
2
|
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .imports import *
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import os,tempfile,shutil,logging,ezodf,fnmatch,pytesseract,pdfplumber
|
|
2
|
+
import pandas as pd
|
|
3
|
+
import geopandas as gpd
|
|
4
|
+
from datetime import datetime
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import *
|
|
7
|
+
from werkzeug.utils import secure_filename
|
|
8
|
+
from werkzeug.datastructures import FileStorage
|
|
9
|
+
from pdf2image import convert_from_path # only used for OCR fallback
|
|
10
|
+
from ...abstract_classes import SingletonMeta
|
|
11
|
+
from ..pdf_utils import *
|
|
12
|
+
from ...read_write_utils import *
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
from types import ModuleType
|
|
2
|
+
from typing import Iterable
|
|
3
|
+
from ..file_utils import get_caller_dir,get_caller_path,define_defaults,get_files_and_dirs
|
|
4
|
+
from ..read_write_utils import *
|
|
5
|
+
import textwrap, pkgutil, os, re, textwrap, sys, types, importlib, importlib.util
|
|
6
|
+
from typing import *
|
|
7
|
+
ABSPATH = os.path.abspath(__file__)
|
|
8
|
+
ABSROOT = os.path.dirname(ABSPATH)
|
|
@@ -1,33 +1,22 @@
|
|
|
1
1
|
# attach_functions.py — single helper you can import anywhere
|
|
2
2
|
# attach_dynamic.py
|
|
3
3
|
from __future__ import annotations
|
|
4
|
-
from
|
|
5
|
-
|
|
6
|
-
|
|
4
|
+
from .imports import *
|
|
5
|
+
def call_for_all_tabs(root = None,tab_control=True):
|
|
6
|
+
root = root or get_caller_dir()
|
|
7
|
+
get_for_all_tabs(root,tab_control=tab_control)
|
|
7
8
|
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
def get_caller_dir():
|
|
18
|
-
frame = inspect.stack()[1]
|
|
19
|
-
abspath = os.path.abspath(frame.filename)
|
|
20
|
-
return os.path.dirname(abspath)
|
|
21
|
-
def call_for_all_tabs():
|
|
22
|
-
|
|
23
|
-
root = get_caller_dir()
|
|
24
|
-
get_for_all_tabs(root)
|
|
25
|
-
|
|
26
|
-
ABSPATH = os.path.abspath(__file__)
|
|
27
|
-
ABSROOT = os.path.dirname(ABSPATH)
|
|
28
|
-
def clean_imports():
|
|
9
|
+
def get_clean_list(*args):
|
|
10
|
+
objs = []
|
|
11
|
+
for arg in args:
|
|
12
|
+
objs+= make_list(arg)
|
|
13
|
+
return list(set(objs))
|
|
14
|
+
def clean_imports(*args,**kwargs):
|
|
15
|
+
for pkg,imps in kwargs.items():
|
|
16
|
+
f"from {pkg} import make_list(imps)"
|
|
17
|
+
|
|
29
18
|
alls = str(list(set("""os,re,subprocess,sys,re,traceback,pydot, enum, inspect, sys, traceback, threading,json,traceback,logging,requests""".replace('\n','').replace(' ','').replace('\t','').split(','))))[1:-1].replace('"','').replace("'",'')
|
|
30
|
-
|
|
19
|
+
return
|
|
31
20
|
def isTab(item):
|
|
32
21
|
item_lower = item.lower()
|
|
33
22
|
for key in ['console','tab']:
|
|
@@ -57,11 +46,17 @@ def ifFunctionsInFile(root):
|
|
|
57
46
|
return item
|
|
58
47
|
|
|
59
48
|
|
|
60
|
-
def get_for_all_tabs(root = None):
|
|
49
|
+
def get_for_all_tabs(root = None,tab_control=True):
|
|
61
50
|
root = root or caller_path()
|
|
62
51
|
if os.path.isfile(root):
|
|
63
52
|
root = os.path.dirname(root)
|
|
64
|
-
|
|
53
|
+
if tab_control:
|
|
54
|
+
all_tabs = get_dirs(root = root)
|
|
55
|
+
else:
|
|
56
|
+
dirname = root
|
|
57
|
+
if root and os.path.isfile(root):
|
|
58
|
+
dirname = os.path.dirname(root)
|
|
59
|
+
all_tabs = [dirname]
|
|
65
60
|
for ROOT in all_tabs:
|
|
66
61
|
FUNCS_DIR = ifFunctionsInFile(ROOT)
|
|
67
62
|
if FUNCS_DIR == None:
|
|
@@ -71,52 +66,38 @@ def get_for_all_tabs(root = None):
|
|
|
71
66
|
apply_inits(ROOT)
|
|
72
67
|
|
|
73
68
|
|
|
74
|
-
def
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
funcs = extract_funcs(fp)
|
|
107
|
-
if funcs:
|
|
108
|
-
import_lines.append(f"from .{module} import ({', '.join(funcs)})")
|
|
109
|
-
all_funcs.extend(funcs)
|
|
110
|
-
if if_fun_dir:
|
|
111
|
-
functions_init = "\n".join(import_lines) + ("\n" if import_lines else "")
|
|
112
|
-
write_to_file(contents=functions_init, file_path=os.path.join(FUNCS_DIR, "__init__.py"))
|
|
113
|
-
|
|
114
|
-
# Prepare the tuple literal of function names for import + loop
|
|
115
|
-
uniq_funcs = sorted(set(all_funcs))
|
|
116
|
-
func_tuple = ", ".join(uniq_funcs) + ("," if len(uniq_funcs) == 1 else "")
|
|
117
|
-
|
|
118
|
-
# Generate apiConsole/initFuncs.py using the safer setattr-loop
|
|
119
|
-
init_funcs_src = textwrap.dedent(f"""\
|
|
69
|
+
def write_init_functions(import_lines,functions_dir):
|
|
70
|
+
functions_init = "\n".join(import_lines) + ("\n" if import_lines else "")
|
|
71
|
+
init_file_path = os.path.join(functions_dir, "__init__.py")
|
|
72
|
+
write_to_file(contents=functions_init, file_path=init_file_path)
|
|
73
|
+
return {"functions_init":functions_init,"init_file_path":init_file_path}
|
|
74
|
+
def extract_funcs(filepaths):
|
|
75
|
+
funcs = []
|
|
76
|
+
for line in read_from_file(path).splitlines():
|
|
77
|
+
m = re.match(r"^def\s+([A-Za-z_]\w*)\s*\(self", line)
|
|
78
|
+
if m:
|
|
79
|
+
funcs.append(m.group(1))
|
|
80
|
+
return funcs
|
|
81
|
+
def get_all_funcs(
|
|
82
|
+
filepaths,
|
|
83
|
+
all_funcs=None,
|
|
84
|
+
import_lines=None
|
|
85
|
+
):
|
|
86
|
+
import_lines = import_lines or []
|
|
87
|
+
all_funcs = all_funcs or []
|
|
88
|
+
for fp in filepaths:
|
|
89
|
+
basename = os.path.basename(fp)
|
|
90
|
+
module = os.path.splitext(basename)[0]
|
|
91
|
+
funcs = extract_funcs(fp)
|
|
92
|
+
if funcs:
|
|
93
|
+
import_lines.append(f"from .{module} import ({', '.join(funcs)})")
|
|
94
|
+
all_funcs.extend(funcs)
|
|
95
|
+
uniq_funcs = sorted(set(all_funcs))
|
|
96
|
+
func_tuple=", ".join(uniq_funcs) + ("," if len(uniq_funcs) == 1 else "")
|
|
97
|
+
all_funcs_js = {"import_lines":import_lines,"all_funcs":all_funcs,"uniq_funcs":uniq_funcs,"func_tuple":func_tuple}
|
|
98
|
+
return all_funcs_js
|
|
99
|
+
def get_init_funcs_str(func_tuple):
|
|
100
|
+
init_funcs_str = textwrap.dedent(f"""\
|
|
120
101
|
|
|
121
102
|
|
|
122
103
|
from .functions import ({func_tuple})
|
|
@@ -129,7 +110,42 @@ def apply_inits(ROOT):
|
|
|
129
110
|
logger.info(f"{{e}}")
|
|
130
111
|
return self
|
|
131
112
|
""")
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
113
|
+
return init_funcs_str
|
|
114
|
+
def get_function_file_paths(functions_dir):
|
|
115
|
+
filepaths=[]
|
|
116
|
+
if_fun_dir = isDir(functions_dir)
|
|
117
|
+
if if_fun_dir != None:
|
|
118
|
+
input(if_fun_dir)
|
|
119
|
+
if if_fun_dir:
|
|
120
|
+
CFG = define_defaults(allowed_exts='.py',
|
|
121
|
+
unallowed_exts = True,
|
|
122
|
+
exclude_types = True,
|
|
123
|
+
exclude_dirs = True,
|
|
124
|
+
exclude_patterns = True)
|
|
125
|
+
input(CFG)
|
|
126
|
+
_,filepaths = get_files_and_dirs(functions_dir,cfg=CFG)
|
|
127
|
+
else:
|
|
128
|
+
filepaths = [FUNCS_DIR]
|
|
129
|
+
input(filepaths)
|
|
130
|
+
return filepaths
|
|
131
|
+
def apply_inits(root=None,tab_control=True):
|
|
132
|
+
root = root or get_caller_dir()
|
|
133
|
+
FUNCS_DIR = ifFunctionsInFile(root)
|
|
134
|
+
if_fun_dir = isDir(FUNCS_DIR)
|
|
135
|
+
if if_fun_dir != None:
|
|
136
|
+
file_paths = get_function_file_paths(FUNCS_DIR)
|
|
137
|
+
|
|
138
|
+
all_funcs_js = get_all_funcs(
|
|
139
|
+
filepaths=file_paths
|
|
140
|
+
)
|
|
141
|
+
if if_fun_dir:
|
|
142
|
+
init_func_js = write_init_functions(import_lines=all_funcs_js.get('import_lines'),functions_dir=FUNCS_DIR)
|
|
143
|
+
all_funcs_js.update(init_func_js)
|
|
144
|
+
func_tuple = all_funcs_js.get("func_tuple")
|
|
145
|
+
init_funcs_str = get_init_funcs_str(func_tuple)
|
|
146
|
+
init_funcs_file_path = os.path.join(root, "initFuncs.py")
|
|
147
|
+
all_funcs_js["funcs_str"]=init_funcs_str
|
|
148
|
+
all_funcs_js["funcs_file_path"]=init_funcs_file_path
|
|
149
|
+
write_to_file(contents=init_funcs_str, file_path=init_funcs_file_path)
|
|
150
|
+
return all_funcs_js
|
|
135
151
|
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"""
|
|
2
|
+
abstract_safeops.py
|
|
3
|
+
-------------------
|
|
4
|
+
Utility functions for safely splitting, slicing, and retrieving elements from iterable or string objects
|
|
5
|
+
without raising exceptions on invalid input or out-of-range indices.
|
|
6
|
+
|
|
7
|
+
Designed for compatibility with the abstract_ ecosystem (e.g. abstract_utilities, abstract_math, etc.).
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from typing import *
|
|
11
|
+
from .type_utils import is_number
|
|
12
|
+
from .class_utils import get_caller_dir
|
|
13
|
+
|
|
14
|
+
_BASE_DIR = get_caller_dir()
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def safe_split(
|
|
18
|
+
string: Any,
|
|
19
|
+
char: Any,
|
|
20
|
+
i: Optional[int] = None,
|
|
21
|
+
default: Union[bool, Any] = False
|
|
22
|
+
) -> Union[str, List[str], Any, None]:
|
|
23
|
+
"""
|
|
24
|
+
Safely split a string by a character and optionally return index i.
|
|
25
|
+
|
|
26
|
+
Args:
|
|
27
|
+
string: Input string (or any object convertible to string).
|
|
28
|
+
char: Delimiter to split on.
|
|
29
|
+
i: Optional index to retrieve from the split result.
|
|
30
|
+
default: If True, return the original string on error.
|
|
31
|
+
If any other value, return that instead of raising.
|
|
32
|
+
|
|
33
|
+
Returns:
|
|
34
|
+
The split list, or the element at index i, or default behavior on error.
|
|
35
|
+
"""
|
|
36
|
+
if string is None or char is None:
|
|
37
|
+
return string
|
|
38
|
+
|
|
39
|
+
s, c = str(string), str(char)
|
|
40
|
+
if c not in s:
|
|
41
|
+
return string
|
|
42
|
+
|
|
43
|
+
parts = s.split(c)
|
|
44
|
+
|
|
45
|
+
if i is None:
|
|
46
|
+
return parts
|
|
47
|
+
|
|
48
|
+
if is_number(i):
|
|
49
|
+
idx = int(i)
|
|
50
|
+
if 0 <= idx < len(parts):
|
|
51
|
+
return parts[idx]
|
|
52
|
+
|
|
53
|
+
if default:
|
|
54
|
+
return string if default is True else default
|
|
55
|
+
|
|
56
|
+
return None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def safe_slice(
|
|
60
|
+
obj: Any,
|
|
61
|
+
i: Optional[int] = None,
|
|
62
|
+
k: Optional[int] = None,
|
|
63
|
+
default: Union[bool, Any] = False
|
|
64
|
+
) -> Any:
|
|
65
|
+
"""
|
|
66
|
+
Safely slice an iterable object or string, with fallback behavior on invalid indices.
|
|
67
|
+
|
|
68
|
+
Args:
|
|
69
|
+
obj: Iterable or string-like object.
|
|
70
|
+
i: Start index (can be negative).
|
|
71
|
+
k: End index (can be negative).
|
|
72
|
+
default: If True, returns the original object on error.
|
|
73
|
+
If any other value, return that value on error.
|
|
74
|
+
|
|
75
|
+
Returns:
|
|
76
|
+
The sliced object, or default behavior on error.
|
|
77
|
+
"""
|
|
78
|
+
# Null or invalid base case
|
|
79
|
+
if obj is None or isinstance(obj, bool):
|
|
80
|
+
return obj if default is True else default if default else None
|
|
81
|
+
|
|
82
|
+
# Non-iterable guard
|
|
83
|
+
if not hasattr(obj, "__getitem__"):
|
|
84
|
+
return obj if default is True else default if default else None
|
|
85
|
+
|
|
86
|
+
obj_len = len(obj)
|
|
87
|
+
|
|
88
|
+
# Normalize negative indices
|
|
89
|
+
if isinstance(i, int) and i < 0:
|
|
90
|
+
i = obj_len + i
|
|
91
|
+
if isinstance(k, int) and k < 0:
|
|
92
|
+
k = obj_len + k
|
|
93
|
+
|
|
94
|
+
# Bound indices
|
|
95
|
+
if i is not None:
|
|
96
|
+
i = max(0, min(i, obj_len))
|
|
97
|
+
if k is not None:
|
|
98
|
+
k = max(0, min(k, obj_len))
|
|
99
|
+
|
|
100
|
+
try:
|
|
101
|
+
return obj[i:k]
|
|
102
|
+
except Exception:
|
|
103
|
+
return obj if default is True else default if default else None
|
|
104
|
+
|
|
105
|
+
def safe_join(*paths):
|
|
106
|
+
paths = list(paths)
|
|
107
|
+
paths = [path for path in paths if path]
|
|
108
|
+
return os.path.join(*paths)
|
|
109
|
+
def safe_get(
|
|
110
|
+
obj: Any,
|
|
111
|
+
key: Union[int, str, None] = None,
|
|
112
|
+
default: Union[bool, Any] = False
|
|
113
|
+
) -> Any:
|
|
114
|
+
"""
|
|
115
|
+
Generalized safe getter for both indexable and mapping types.
|
|
116
|
+
|
|
117
|
+
Args:
|
|
118
|
+
obj: The object to access (list, dict, string, etc.).
|
|
119
|
+
key: Index or key to retrieve.
|
|
120
|
+
default: Fallback value or True for "return obj".
|
|
121
|
+
|
|
122
|
+
Returns:
|
|
123
|
+
Retrieved element, or default value on failure.
|
|
124
|
+
"""
|
|
125
|
+
if obj is None or key is None:
|
|
126
|
+
return obj if default is True else default if default else None
|
|
127
|
+
|
|
128
|
+
try:
|
|
129
|
+
if isinstance(obj, dict):
|
|
130
|
+
return obj.get(key, obj if default is True else default if default else None)
|
|
131
|
+
return obj[key]
|
|
132
|
+
except Exception:
|
|
133
|
+
return obj if default is True else default if default else None
|