abstract-utilities 0.2.2.540__py3-none-any.whl → 0.2.2.667__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 +13 -4
- abstract_utilities/class_utils/abstract_classes.py +104 -34
- abstract_utilities/class_utils/caller_utils.py +57 -0
- abstract_utilities/class_utils/global_utils.py +35 -20
- abstract_utilities/class_utils/imports/imports.py +1 -1
- abstract_utilities/directory_utils/src/directory_utils.py +19 -1
- abstract_utilities/file_utils/imports/classes.py +59 -55
- abstract_utilities/file_utils/imports/imports.py +0 -4
- abstract_utilities/file_utils/imports/module_imports.py +1 -1
- abstract_utilities/file_utils/src/__init__.py +2 -3
- abstract_utilities/file_utils/src/file_filters/__init__.py +1 -0
- abstract_utilities/file_utils/src/file_filters/ensure_utils.py +490 -0
- abstract_utilities/file_utils/src/file_filters/filter_params.py +150 -0
- abstract_utilities/file_utils/src/file_filters/filter_utils.py +78 -0
- abstract_utilities/file_utils/src/file_filters/predicate_utils.py +44 -0
- abstract_utilities/file_utils/src/file_reader.py +0 -1
- abstract_utilities/file_utils/src/find_collect.py +10 -86
- abstract_utilities/file_utils/src/find_content.py +210 -0
- abstract_utilities/file_utils/src/initFunctionsGen.py +36 -23
- abstract_utilities/file_utils/src/initFunctionsGens.py +280 -0
- abstract_utilities/file_utils/src/reader_utils/__init__.py +4 -0
- abstract_utilities/file_utils/src/reader_utils/directory_reader.py +53 -0
- abstract_utilities/file_utils/src/reader_utils/file_reader.py +543 -0
- abstract_utilities/file_utils/src/reader_utils/file_readers.py +376 -0
- abstract_utilities/file_utils/src/reader_utils/imports.py +18 -0
- abstract_utilities/file_utils/src/reader_utils/pdf_utils.py +300 -0
- abstract_utilities/import_utils/circular_import_finder.py +222 -0
- abstract_utilities/import_utils/circular_import_finder2.py +118 -0
- abstract_utilities/import_utils/imports/__init__.py +1 -1
- abstract_utilities/import_utils/imports/init_imports.py +3 -0
- abstract_utilities/import_utils/imports/module_imports.py +4 -1
- abstract_utilities/import_utils/imports/utils.py +1 -1
- abstract_utilities/import_utils/src/__init__.py +1 -0
- abstract_utilities/import_utils/src/clean_imports.py +156 -25
- abstract_utilities/import_utils/src/dot_utils.py +11 -0
- abstract_utilities/import_utils/src/extract_utils.py +4 -0
- abstract_utilities/import_utils/src/import_functions.py +66 -2
- abstract_utilities/import_utils/src/import_utils.py +39 -0
- abstract_utilities/import_utils/src/layze_import_utils/__init__.py +2 -0
- abstract_utilities/import_utils/src/layze_import_utils/lazy_utils.py +41 -0
- abstract_utilities/import_utils/src/layze_import_utils/nullProxy.py +32 -0
- abstract_utilities/import_utils/src/nullProxy.py +30 -0
- abstract_utilities/import_utils/src/pkg_utils.py +58 -4
- abstract_utilities/import_utils/src/sysroot_utils.py +56 -1
- abstract_utilities/imports.py +3 -2
- abstract_utilities/json_utils/json_utils.py +11 -3
- abstract_utilities/log_utils/log_file.py +73 -24
- abstract_utilities/parse_utils/parse_utils.py +23 -0
- abstract_utilities/path_utils/imports/module_imports.py +1 -1
- abstract_utilities/path_utils/path_utils.py +32 -35
- abstract_utilities/read_write_utils/imports/imports.py +1 -1
- abstract_utilities/read_write_utils/read_write_utils.py +102 -32
- abstract_utilities/safe_utils/safe_utils.py +30 -0
- abstract_utilities/type_utils/__init__.py +5 -1
- abstract_utilities/type_utils/get_type.py +116 -0
- abstract_utilities/type_utils/imports/__init__.py +1 -0
- abstract_utilities/type_utils/imports/constants.py +134 -0
- abstract_utilities/type_utils/imports/module_imports.py +25 -1
- abstract_utilities/type_utils/is_type.py +455 -0
- abstract_utilities/type_utils/make_type.py +126 -0
- abstract_utilities/type_utils/mime_types.py +68 -0
- abstract_utilities/type_utils/type_utils.py +0 -877
- {abstract_utilities-0.2.2.540.dist-info → abstract_utilities-0.2.2.667.dist-info}/METADATA +1 -1
- {abstract_utilities-0.2.2.540.dist-info → abstract_utilities-0.2.2.667.dist-info}/RECORD +66 -41
- {abstract_utilities-0.2.2.540.dist-info → abstract_utilities-0.2.2.667.dist-info}/WHEEL +0 -0
- {abstract_utilities-0.2.2.540.dist-info → abstract_utilities-0.2.2.667.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
# attach_functions.py — single helper you can import anywhere
|
|
2
|
+
# attach_dynamic.py
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
from .find_collect import *
|
|
5
|
+
from ..imports import *
|
|
6
|
+
|
|
7
|
+
def caller_path():
|
|
8
|
+
frame = inspect.stack()[1]
|
|
9
|
+
return os.path.abspath(frame.filename)
|
|
10
|
+
def _is_defined_here(mod: types.ModuleType, obj: object) -> bool:
|
|
11
|
+
try:
|
|
12
|
+
return inspect.getmodule(obj) is mod
|
|
13
|
+
except Exception:
|
|
14
|
+
return False
|
|
15
|
+
|
|
16
|
+
def _collect_callables(mod: types.ModuleType) -> Dict[str, Callable]:
|
|
17
|
+
out: Dict[str, Callable] = {}
|
|
18
|
+
names = getattr(mod, "__all__", None)
|
|
19
|
+
if names:
|
|
20
|
+
# trust the author's export list
|
|
21
|
+
for n in names:
|
|
22
|
+
fn = getattr(mod, n, None)
|
|
23
|
+
if callable(fn):
|
|
24
|
+
out[n] = fn
|
|
25
|
+
return out
|
|
26
|
+
# otherwise, discover top-level callables defined in this module
|
|
27
|
+
for n in dir(mod):
|
|
28
|
+
if n.startswith("_"):
|
|
29
|
+
continue
|
|
30
|
+
obj = getattr(mod, n, None)
|
|
31
|
+
if callable(obj) and _is_defined_here(mod, obj):
|
|
32
|
+
out[n] = obj
|
|
33
|
+
return out
|
|
34
|
+
|
|
35
|
+
def _import_module_by_name(name: str) -> Optional[types.ModuleType]:
|
|
36
|
+
try:
|
|
37
|
+
return importlib.import_module(name)
|
|
38
|
+
except Exception:
|
|
39
|
+
return None
|
|
40
|
+
|
|
41
|
+
def _import_module_by_path(pkg_name: str, base_dir: str, filename: str) -> Optional[types.ModuleType]:
|
|
42
|
+
mod_name = f"{pkg_name}.functions"
|
|
43
|
+
path = os.path.join(base_dir, filename)
|
|
44
|
+
spec = importlib.util.spec_from_file_location(mod_name, path)
|
|
45
|
+
if not spec or not spec.loader:
|
|
46
|
+
return None
|
|
47
|
+
mod = importlib.util.module_from_spec(spec)
|
|
48
|
+
sys.modules[mod_name] = mod
|
|
49
|
+
spec.loader.exec_module(mod)
|
|
50
|
+
return mod
|
|
51
|
+
|
|
52
|
+
def _walk_functions_package(pkg_name: str, pkg_mod: types.ModuleType) -> List[types.ModuleType]:
|
|
53
|
+
"""Import all immediate submodules in the functions/ package."""
|
|
54
|
+
mods: List[types.ModuleType] = [pkg_mod]
|
|
55
|
+
pkg_dir = os.path.dirname(pkg_mod.__file__ or "")
|
|
56
|
+
for info in pkgutil.iter_modules([pkg_dir]):
|
|
57
|
+
# only import direct children (no recursion here; easy to add if you need)
|
|
58
|
+
child_name = f"{pkg_mod.__name__}.{info.name}"
|
|
59
|
+
m = _import_module_by_name(child_name)
|
|
60
|
+
if m:
|
|
61
|
+
mods.append(m)
|
|
62
|
+
return mods
|
|
63
|
+
|
|
64
|
+
def _discover_functions(base_pkg: str, *, hot_reload: bool) -> List[Tuple[str, Callable, str]]:
|
|
65
|
+
"""
|
|
66
|
+
Returns a list of (export_name, callable, module_basename).
|
|
67
|
+
Works if you have base_pkg.functions.py or base_pkg/functions/ package.
|
|
68
|
+
"""
|
|
69
|
+
# Prefer normal import of '<base_pkg>.functions'
|
|
70
|
+
fqn = f"{base_pkg}.functions"
|
|
71
|
+
mod = _import_module_by_name(fqn)
|
|
72
|
+
|
|
73
|
+
if mod is None:
|
|
74
|
+
# fallback: sibling functions.py, even without being a package
|
|
75
|
+
base = _import_module_by_name(base_pkg)
|
|
76
|
+
if not base or not getattr(base, "__file__", None):
|
|
77
|
+
return []
|
|
78
|
+
base_dir = os.path.dirname(base.__file__)
|
|
79
|
+
if os.path.isfile(os.path.join(base_dir, "functions.py")):
|
|
80
|
+
mod = _import_module_by_path(base_pkg, base_dir, "functions.py")
|
|
81
|
+
else:
|
|
82
|
+
return []
|
|
83
|
+
|
|
84
|
+
if hot_reload:
|
|
85
|
+
try:
|
|
86
|
+
mod = importlib.reload(mod) # type: ignore[arg-type]
|
|
87
|
+
except Exception:
|
|
88
|
+
pass
|
|
89
|
+
|
|
90
|
+
results: List[Tuple[str, Callable, str]] = []
|
|
91
|
+
modules: List[types.ModuleType]
|
|
92
|
+
|
|
93
|
+
if hasattr(mod, "__path__"): # it's a package: import children
|
|
94
|
+
modules = _walk_functions_package(base_pkg, mod)
|
|
95
|
+
else:
|
|
96
|
+
modules = [mod]
|
|
97
|
+
|
|
98
|
+
for m in modules:
|
|
99
|
+
exported = _collect_callables(m)
|
|
100
|
+
module_basename = m.__name__.split(".")[-1]
|
|
101
|
+
for name, fn in exported.items():
|
|
102
|
+
results.append((name, fn, module_basename))
|
|
103
|
+
return results
|
|
104
|
+
|
|
105
|
+
def attach_functions(
|
|
106
|
+
obj_or_cls,
|
|
107
|
+
base_pkg: str | None = None,
|
|
108
|
+
hot_reload: bool = True,
|
|
109
|
+
prefix_with_module: bool = False,
|
|
110
|
+
include_private: bool = True,
|
|
111
|
+
only_defined_here: bool = True, # don't attach stuff imported from elsewhere
|
|
112
|
+
) -> list[str]:
|
|
113
|
+
"""
|
|
114
|
+
Attach all free functions found in <base_pkg>.functions (module or package)
|
|
115
|
+
to the *class* of obj_or_cls. Returns the list of attached attribute names.
|
|
116
|
+
"""
|
|
117
|
+
cls = obj_or_cls if inspect.isclass(obj_or_cls) else obj_or_cls.__class__
|
|
118
|
+
# Derive "<package>.functions" from the class's module unless you pass base_pkg
|
|
119
|
+
caller_mod = cls.__module__
|
|
120
|
+
pkg_root = (base_pkg or caller_mod.rsplit(".", 1)[0]).rstrip(".")
|
|
121
|
+
funcs_pkg_name = f"{pkg_root}.functions"
|
|
122
|
+
|
|
123
|
+
def _import(name: str) -> ModuleType | None:
|
|
124
|
+
try:
|
|
125
|
+
if hot_reload and name in sys.modules:
|
|
126
|
+
return importlib.reload(sys.modules[name])
|
|
127
|
+
return importlib.import_module(name)
|
|
128
|
+
except Exception:
|
|
129
|
+
return None
|
|
130
|
+
|
|
131
|
+
def _is_pkg(m: ModuleType) -> bool:
|
|
132
|
+
return hasattr(m, "__path__")
|
|
133
|
+
|
|
134
|
+
mod = _import(funcs_pkg_name)
|
|
135
|
+
if mod is None:
|
|
136
|
+
# Nothing to attach (no functions.py or functions/ next to your class)
|
|
137
|
+
setattr(cls, "_attached_functions", tuple())
|
|
138
|
+
return []
|
|
139
|
+
|
|
140
|
+
modules: list[ModuleType] = [mod]
|
|
141
|
+
if _is_pkg(mod):
|
|
142
|
+
# attach from every submodule under functions/
|
|
143
|
+
for it in pkgutil.iter_modules(mod.__path__):
|
|
144
|
+
sub = _import(f"{funcs_pkg_name}.{it.name}")
|
|
145
|
+
if sub is not None:
|
|
146
|
+
modules.append(sub)
|
|
147
|
+
|
|
148
|
+
attached: list[str] = []
|
|
149
|
+
for m in modules:
|
|
150
|
+
for name, obj in vars(m).items():
|
|
151
|
+
# only callables (skip classes), and keep them sane
|
|
152
|
+
if not callable(obj) or isinstance(obj, type):
|
|
153
|
+
continue
|
|
154
|
+
if only_defined_here and getattr(obj, "__module__", None) != m.__name__:
|
|
155
|
+
continue
|
|
156
|
+
if not include_private and name.startswith("_"):
|
|
157
|
+
continue
|
|
158
|
+
if name.startswith("__") and name.endswith("__"):
|
|
159
|
+
continue
|
|
160
|
+
attr = f"{m.__name__.rsplit('.', 1)[-1]}__{name}" if prefix_with_module else name
|
|
161
|
+
try:
|
|
162
|
+
setattr(cls, attr, obj) # set on CLASS → becomes bound method on instances
|
|
163
|
+
attached.append(attr)
|
|
164
|
+
except Exception:
|
|
165
|
+
# don't explode if one name collides; keep going
|
|
166
|
+
continue
|
|
167
|
+
|
|
168
|
+
# handy for debugging
|
|
169
|
+
try:
|
|
170
|
+
setattr(cls, "_attached_functions", tuple(attached))
|
|
171
|
+
except Exception:
|
|
172
|
+
pass
|
|
173
|
+
return attached
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def isTab(item):
|
|
179
|
+
item_lower = item.lower()
|
|
180
|
+
for key in ['console','tab']:
|
|
181
|
+
if item_lower.endswith(key):
|
|
182
|
+
return True
|
|
183
|
+
return False
|
|
184
|
+
def get_dir(root,item):
|
|
185
|
+
if None in [root]:
|
|
186
|
+
return None
|
|
187
|
+
path = root
|
|
188
|
+
if item != None:
|
|
189
|
+
path = os.path.join(path,item)
|
|
190
|
+
return path
|
|
191
|
+
def isDir(root,item=None):
|
|
192
|
+
path = get_dir(root,item)
|
|
193
|
+
if path:
|
|
194
|
+
return os.path.isdir(path)
|
|
195
|
+
def check_dir_item(root,item=None):
|
|
196
|
+
return (item and isTab(item) and isDir(root,item))
|
|
197
|
+
def get_dirs(root = None):
|
|
198
|
+
root = root or ABSROOT
|
|
199
|
+
dirpaths = [get_dir(root,item) for item in os.listdir(root) if check_dir_item(root,item)]
|
|
200
|
+
return dirpaths
|
|
201
|
+
def ifFunctionsInFile(root):
|
|
202
|
+
items = [os.path.join(root, "functions"),os.path.join(root, "functions.py")]
|
|
203
|
+
for item in items:
|
|
204
|
+
if os.path.exists(item):
|
|
205
|
+
return item
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def get_for_all_tabs(root = None):
|
|
209
|
+
root = root or get_initial_caller_dir()
|
|
210
|
+
if os.path.isfile(root):
|
|
211
|
+
root = os.path.dirname(root)
|
|
212
|
+
all_tabs = get_dirs(root = root)
|
|
213
|
+
for ROOT in all_tabs:
|
|
214
|
+
FUNCS_DIR = ifFunctionsInFile(ROOT)
|
|
215
|
+
if FUNCS_DIR == None:
|
|
216
|
+
for ROOT in get_dirs(root = ROOT):
|
|
217
|
+
apply_inits(ROOT)
|
|
218
|
+
else:
|
|
219
|
+
apply_inits(ROOT)
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def apply_inits(ROOT):
|
|
223
|
+
FUNCS_DIR = ifFunctionsInFile(ROOT)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
if_fun_dir = isDir(FUNCS_DIR)
|
|
227
|
+
if if_fun_dir != None:
|
|
228
|
+
|
|
229
|
+
if if_fun_dir:
|
|
230
|
+
filepaths = collect_filepaths(FUNCS_DIR,allowed_exts='.py',add=True)
|
|
231
|
+
|
|
232
|
+
else:
|
|
233
|
+
filepaths = [FUNCS_DIR]
|
|
234
|
+
|
|
235
|
+
# Parse top-level def names
|
|
236
|
+
def extract_funcs(path: str):
|
|
237
|
+
funcs = []
|
|
238
|
+
for line in read_from_file(path).splitlines():
|
|
239
|
+
m = re.match(r"^def\s+([A-Za-z_]\w*)\s*\(self", line)
|
|
240
|
+
if m:
|
|
241
|
+
funcs.append(m.group(1))
|
|
242
|
+
return funcs
|
|
243
|
+
|
|
244
|
+
# Build functions/__init__.py that re-exports all discovered functions
|
|
245
|
+
import_lines = []
|
|
246
|
+
all_funcs = []
|
|
247
|
+
for fp in filepaths:
|
|
248
|
+
module = os.path.splitext(os.path.basename(fp))[0]
|
|
249
|
+
funcs = extract_funcs(fp)
|
|
250
|
+
if funcs:
|
|
251
|
+
import_lines.append(f"from .{module} import ({', '.join(funcs)})")
|
|
252
|
+
all_funcs.extend(funcs)
|
|
253
|
+
if if_fun_dir:
|
|
254
|
+
functions_init = "\n".join(import_lines) + ("\n" if import_lines else "")
|
|
255
|
+
write_to_file(contents=functions_init, file_path=os.path.join(FUNCS_DIR, "__init__.py"))
|
|
256
|
+
|
|
257
|
+
# Prepare the tuple literal of function names for import + loop
|
|
258
|
+
uniq_funcs = sorted(set(all_funcs))
|
|
259
|
+
func_tuple = ", ".join(uniq_funcs) + ("," if len(uniq_funcs) == 1 else "")
|
|
260
|
+
|
|
261
|
+
# Generate apiConsole/initFuncs.py using the safer setattr-loop
|
|
262
|
+
init_funcs_src = textwrap.dedent(f"""\
|
|
263
|
+
|
|
264
|
+
from abstract_utilities import get_logFile
|
|
265
|
+
from .functions import ({func_tuple})
|
|
266
|
+
logger=get_logFile(__name__)
|
|
267
|
+
def initFuncs(self):
|
|
268
|
+
try:
|
|
269
|
+
for f in ({func_tuple}):
|
|
270
|
+
setattr(self, f.__name__, f)
|
|
271
|
+
except Exception as e:
|
|
272
|
+
logger.info(f"{{e}}")
|
|
273
|
+
return self
|
|
274
|
+
""")
|
|
275
|
+
|
|
276
|
+
write_to_file(contents=init_funcs_src, file_path=os.path.join(ROOT, "initFuncs.py"))
|
|
277
|
+
|
|
278
|
+
def call_for_all_tabs():
|
|
279
|
+
root = get_initial_caller_dir()
|
|
280
|
+
get_for_all_tabs(root)
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
from .imports import *
|
|
2
|
+
from .file_readers import *
|
|
3
|
+
# ─── Example walker ──────────────────────────────────────────────────────────
|
|
4
|
+
_logger = get_logFile(__name__)
|
|
5
|
+
|
|
6
|
+
def read_files(files=None,allowed=None):
|
|
7
|
+
allowed = allowed or make_allowed_predicate()
|
|
8
|
+
files = get_all_files(make_list(files or []),allowed)
|
|
9
|
+
collected = {}
|
|
10
|
+
for full_path in files:
|
|
11
|
+
ext = Path(full_path).suffix.lower()
|
|
12
|
+
|
|
13
|
+
# ——— 1) Pure-text quick reads —————————————
|
|
14
|
+
if ext in {'.txt', '.md', '.csv', '.tsv', '.log'}:
|
|
15
|
+
try:
|
|
16
|
+
with open(full_path, 'r', encoding='utf-8', errors='replace') as f:
|
|
17
|
+
collected[full_path] = f.read()
|
|
18
|
+
except Exception as e:
|
|
19
|
+
#_logger.warning(f"Failed to read {full_path} as text: {e}")
|
|
20
|
+
pass
|
|
21
|
+
continue
|
|
22
|
+
|
|
23
|
+
# ——— 2) Try your DataFrame loader ——————————
|
|
24
|
+
try:
|
|
25
|
+
df_or_map = get_df(full_path)
|
|
26
|
+
if isinstance(df_or_map, (pd.DataFrame, gpd.GeoDataFrame)):
|
|
27
|
+
collected[full_path] = df_or_map
|
|
28
|
+
#_logger.info(f"Loaded DataFrame: {full_path}")
|
|
29
|
+
continue
|
|
30
|
+
|
|
31
|
+
if isinstance(df_or_map, dict):
|
|
32
|
+
for sheet, df in df_or_map.items():
|
|
33
|
+
key = f"{full_path}::[{sheet}]"
|
|
34
|
+
collected[key] = df
|
|
35
|
+
#_logger.info(f"Loaded sheet DataFrame: {key}")
|
|
36
|
+
continue
|
|
37
|
+
except Exception as e:
|
|
38
|
+
#_logger.debug(f"get_df failed for {full_path}: {e}")
|
|
39
|
+
pass
|
|
40
|
+
# ——— 3) Fallback to generic text extractor ————
|
|
41
|
+
try:
|
|
42
|
+
parts = read_file_as_text(full_path) # List[str]
|
|
43
|
+
combined = "\n\n".join(parts)
|
|
44
|
+
collected[full_path] = combined
|
|
45
|
+
#_logger.info(f"Read fallback text for: {full_path}")
|
|
46
|
+
except Exception as e:
|
|
47
|
+
_logger.warning(f"Could not read {full_path} at all: {e}")
|
|
48
|
+
|
|
49
|
+
return collected
|
|
50
|
+
def read_directory(*args,**kwargs) -> Dict[str, Union[pd.DataFrame, str]]:
|
|
51
|
+
directories,cfg,allowed,include_files,recursive = get_file_filters(*args,**kwargs)
|
|
52
|
+
|
|
53
|
+
return read_files(files=directories[0],allowed=allowed)
|