-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuncategorized.py
2327 lines (1920 loc) · 84.2 KB
/
uncategorized.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# Utility Functions to run Jupyter notebooks.
# Dave Babbitt <[email protected]>
# Author: Dave Babbitt, Machine Learning Engineer
# coding: utf-8
# Soli Deo gloria
"""
Run this in a Git Bash terminal if you push anything:
cd ~/OneDrive/Documents/GitHub/notebooks/sh
./update_share_submodules.sh
"""
from base_config import BaseConfig
from bs4 import BeautifulSoup as bs
from datetime import timedelta
from os import (
listdir as listdir, makedirs as makedirs, path as osp,
walk as walk
)
from pandas import (
DataFrame, Series, concat
)
from re import (
IGNORECASE
)
import humanize
import inspect
import math
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
import re
import seaborn as sns
import subprocess
import sys
# Check for presence of 'get_ipython' function (exists in Jupyter)
try:
get_ipython()
from IPython.display import display
except NameError:
def display(message):
"""
Display a message. If IPython's display is unavailable, fall back to
printing.
Parameters:
message (str): The message to display.
"""
print(message)
class Uncategorized(BaseConfig):
def __init__(
self, data_folder_path=None, saves_folder_path=None, verbose=False
):
# Assume the data folder exists
if data_folder_path is None:
self.data_folder = osp.join(os.pardir, 'data')
else:
self.data_folder = data_folder_path
# Assume the saves folder exists
if saves_folder_path is None:
self.saves_folder = osp.join(os.pardir, 'saves')
else:
self.saves_folder = saves_folder_path
super().__init__() # Inherit shared attributes
self.pip_command_str = f'{sys.executable} -m pip'
# Create the assumed directories
self.saves_text_folder = osp.join(self.saves_folder, 'txt')
makedirs(name=self.saves_text_folder, exist_ok=True)
self.saves_wav_folder = osp.join(self.saves_folder, 'wav')
makedirs(name=self.saves_wav_folder, exist_ok=True)
self.txt_folder = osp.join(self.data_folder, 'txt')
makedirs(self.txt_folder, exist_ok=True)
# Create the model directories
self.bin_folder = osp.join(self.data_folder, 'bin')
makedirs(self.bin_folder, exist_ok=True)
self.cache_folder = osp.join(self.data_folder, 'cache')
makedirs(self.cache_folder, exist_ok=True)
self.data_models_folder = osp.join(self.data_folder, 'models')
makedirs(name=self.data_models_folder, exist_ok=True)
self.db_folder = osp.join(self.data_folder, 'db')
makedirs(self.db_folder, exist_ok=True)
self.graphs_folder = osp.join(self.saves_folder, 'graphs')
makedirs(self.graphs_folder, exist_ok=True)
self.indices_folder = osp.join(self.saves_folder, 'indices')
makedirs(self.indices_folder, exist_ok=True)
# Ensure the Scripts folder is in PATH
self.anaconda_folder = osp.dirname(sys.executable)
self.scripts_folder = osp.join(self.anaconda_folder, 'Scripts')
if self.scripts_folder not in sys.path:
sys.path.insert(1, self.scripts_folder)
# Handy list of the different types of encodings
self.encoding_errors_list = ['ignore', 'replace', 'xmlcharrefreplace']
self.encoding_error = self.encoding_errors_list[2]
self.decoding_types_list = [
'ascii', 'cp037', 'cp437', 'cp863', 'utf_32', 'utf_32_be',
'utf_32_le', 'utf_16', 'utf_16_be', 'utf_16_le', 'utf_7',
'utf_8', 'utf_8_sig', 'latin1', 'iso8859-1'
]
self.decoding_type = self.decoding_types_list[11]
self.decoding_errors_list = self.encoding_errors_list.copy()
self.decoding_error = self.decoding_errors_list[2]
# Regular expressions to determine URL from file path
s = r'\b(https?|file)://[-A-Z0-9+&@#/%?=~_|$!:,.;]*[A-Z0-9+&@#/%=~_|$]'
self.url_regex = re.compile(s, IGNORECASE)
s = r'\b[c-d]:\\(?:[^\\/:*?"<>|\x00-\x1F]{0,254}'
s += r'[^.\\/:*?"<>|\x00-\x1F]\\)*(?:[^\\/:*?"<>'
s += r'|\x00-\x1F]{0,254}[^.\\/:*?"<>|\x00-\x1F])'
self.filepath_regex = re.compile(s, IGNORECASE)
# Compile the pattern for identifying function definitions
self.simple_defs_regex = re.compile(r'\bdef ([a-z0-9_]+)\(')
# Create a pattern to match function definitions
self.ipynb_defs_regex = re.compile('\\s+"def ([a-z0-9_]+)\\(')
# Create a regex for finding instance methods and self usage
s = '^ def ([a-z]+[a-z_]+)\\(\\s*self,\\s+(?:[^\\)]+)\\):'
self.instance_defs_regex = re.compile(s, re.MULTILINE)
# Create a regex to search for self references within function bodies
self.self_regex = re.compile('\\bself\\b')
# Compile regex to find all unprefixed comments in the source code
self.comment_regex = re.compile('^( *)# ([^\r\n]+)', re.MULTILINE)
# Compile a regex pattern to match non-alphanumeric characters
self.lower_ascii_regex = re.compile('[^a-z0-9]+')
# Module lists
self.object_evaluators = [
fn for fn in dir(inspect) if fn.startswith('is')
]
# -------------------
# Numeric Functions
# -------------------
@staticmethod
def float_to_ratio(value, tolerance=0.01):
"""
Convert a float to a ratio of two integers, approximating the float
within a specified tolerance.
Parameters:
value (float): The float to convert.
tolerance (float, optional):
The acceptable difference between the float and the ratio.
Default is 0.01.
Returns:
tuple:
A tuple of two integers (numerator, denominator) representing
the ratio that approximates the float.
"""
# Use helper function to check if the fraction is within tolerance
from fractions import Fraction
def is_within_tolerance(numerator, denominator, value, tolerance):
"""
Check if the ratio (numerator/denominator) is within the given
tolerance of the target value.
"""
return abs(numerator / denominator - value) <= tolerance
# Validate input
if not isinstance(value, (float, int)):
raise TypeError('Input value must be a float or an integer.')
if not isinstance(tolerance, float) or tolerance <= 0:
raise ValueError('Tolerance must be a positive float.')
# Use the Fraction module to find an approximate fraction
fraction = Fraction(value).limit_denominator()
numerator, denominator = (fraction.numerator, fraction.denominator)
# Adjust the fraction only if needed
while not is_within_tolerance(
numerator, denominator, value, tolerance
):
numerator += 1
if is_within_tolerance(numerator, denominator, value, tolerance):
break
denominator += 1
return (numerator, denominator)
# -------------------
# String Functions
# -------------------
@staticmethod
def format_timedelta(time_delta):
"""
Format a time delta object to a string in the
format '0 sec', '30 sec', '1 min', '1:30', '2 min', etc.
Parameters:
time_delta: A time delta object representing a duration.
Returns:
A string representing the formatted time delta in a human-readable
format: '0 sec', '30 sec', '1 min', '1:30', '2 min', etc.
"""
# Extract total seconds from the time delta object
seconds = time_delta.total_seconds()
# Calculate the number of whole minutes
minutes = int(seconds // 60)
# Calculate the remaining seconds after accounting for minutes
seconds = int(seconds % 60)
# Format the output string for zero minutes, showing only seconds
if minutes == 0:
return f'{seconds} sec'
# If there are minutes and seconds, return in 'min:sec' format
elif seconds > 0:
return f'{minutes}:{seconds:02}' # noqa: E231
# If there are only minutes, return in 'min' format
else:
return f'{minutes} min'
# -------------------
# List Functions
# -------------------
@staticmethod
def get_shape(list_of_lists):
"""
Return the shape of a list of lists, assuming the sublists are all of
the same length.
Parameters:
list_of_lists: A list of lists.
Returns:
A tuple representing the shape of the list of lists.
"""
# Check if the list of lists is empty
if not list_of_lists:
return ()
# Get the length of the first sublist
num_cols = len(list_of_lists[0])
# Check if all of the sublists are the same length
for sublist in list_of_lists:
if len(sublist) != num_cols:
raise ValueError(
'All of the sublists must be the same length.'
)
# Return a tuple representing the shape of the list of lists
return (len(list_of_lists), num_cols)
@staticmethod
def get_numbered_text(
numbering_format,
current_number_dict={'1': 1, 'A': 1, 'a': 1, 'i': 1, 'I': 1}
):
"""
Apply numbering based on a format string and a current number.
This static method takes a numbering format string
(`numbering_format`) and a current number dictionary
(`current_number_dict`) as inputs. It then parses the format
string to identify numbering placeholders (letters 'A', 'a', '1',
'I', or 'i') and replaces them with the corresponding numbered
representation based on the current number of that placeholder.
The function supports the following numbering formats:
- '1': Sequential numbering, starting from 1 (e.g., 'Step 1'
becomes 'Step 2').
- 'A': Uppercase alphabetic numbering, starting from A (e.g.,
'Part A' becomes 'Part B').
- 'a': Lowercase alphabetic numbering, starting from a (e.g.,
'Section a' becomes 'Section b').
- 'i': Roman numeral numbering, starting from i (e.g., 'Point i'
becomes 'Point ii').
- 'I': Roman numeral numbering, starting from I (e.g., 'Epoch I'
becomes 'Epoch II').
Parameters:
numbering_format (str):
The numbering format string, which should contain one of the
following characters: 'A', '1', 'a', 'I', or 'i'. These
characters represent the place in the string where the
current number should be inserted, and their case and type
represent the format that the number should be in.
current_number_dict (dict with strs as keys and ints as values,
optional):
The current number based on the format codes to replace the
placeholder in the numbering format. Defaults to {'1': 1,
'A': 1, 'a': 1, 'i': 1, 'I': 1}.
Returns:
str
The formatted string with the current number inserted in
place of the placeholder.
Raises:
AssertionError
If the `numbering_format` string does not contain any of the
supported numbering placeholders (A, a, 1, I, or i).
"""
if isinstance(current_number_dict, int):
current_number_dict = {
'1': current_number_dict, 'A': current_number_dict,
'a': current_number_dict, 'i': current_number_dict,
'I': current_number_dict
}
# Extract the format codes by keeping only 'A', '1', 'a', 'I', or 'i'
format_codes = re.sub('[^A1aiI]+', '', numbering_format)
# If the format codes are empty, return the numbering_format as is
if not format_codes:
return numbering_format
# Extract each character as the numbering code
for format_code in format_codes:
# Is the format code '1'?
if format_code == '1':
# Apply sequential numbering (replace with current number)
numbering_format = numbering_format.replace(
format_code, str(current_number_dict[format_code])
)
# Is the format code 'i'?
elif format_code == 'i':
# Apply lowercase roman numeral numbering
import roman
numbering_format = numbering_format.replace(
format_code, roman.toRoman(
current_number_dict[format_code]
).lower()
)
# Is the format code 'I'?
elif format_code == 'I':
# Apply uppercase roman numeral numbering
import roman
numbering_format = numbering_format.replace(
format_code, roman.toRoman(
current_number_dict[format_code]
).upper()
)
# Otherwise
else:
# Adjust the ASCII code by the offset value of the format
new_char_code = ord(
format_code
) + current_number_dict[format_code] - 1
# Apply alphabetic numbering
numbering_format = numbering_format.replace(
format_code, chr(new_char_code)
)
return numbering_format
def apply_multilevel_numbering(
self, text_list,
level_map={0: "", 4: "A. ", 8: "1. ", 12: "a) ", 16: "i) "},
add_indent_back_in=False, verbose=False
):
"""
Take a list of strings with indentation and infix or prefix them
with the appropriate numbering text based on a multi-level list
style.
Parameters:
text_list:
A list of strings, where each string may be prepended with 0,
4, 8, 12, or 16 spaces representing indentation levels, or
a list of tuples (int, str), where the int is the number of
spaces and the str is the left-stripped text.
level_map:
A dictionary that maps indentation to numbering format.
Defaults to {0: "", 4: "A. ", 8: "1. ", 12: "a) ", 16: "i) "}.
add_indent_back_in:
Whether to prepend the indention
Returns:
A new list of strings with numbering text prepended based on
indentation.
Example:
level_count = 8
text_list = [
' ' * (i*4) + f'This is level {i}'
for i in range(level_count+1)
]
text_list += [
' ' * (i*4) + f'This is level {i} again'
for i in range(level_count, -1, -1)
]
numbered_list = nu.apply_multilevel_numbering(
text_list,
level_map={
0: "", 4: "I. ", 8: "A. ", 12: "1. ", 16: "a. ",
20: "I) ", 24: "A) ", 28: "1) ", 32: "a) "
}, add_indent_back_in=True
)
for line in numbered_list:
print(line)
"""
# Initialize current_level to track current indentation level
current_level = 0
# Initialize map to track current number within a level
current_number_map = {0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}
numbered_text_list = []
# Loop through each sentence in text_list
for text in text_list:
# Get the level by the indent
if isinstance(text, tuple):
indent = text[0]
text = text[1]
else:
indent = len(text) - len(text.lstrip())
if verbose:
print(f'indent = {indent}')
new_level = indent // 4
if verbose:
print(f'new_level = {new_level}')
# Handle level changes and update numbering
if new_level > current_level:
current_level = new_level
current_number_map[current_level] = 1
elif new_level < current_level:
current_level = new_level
current_number_map[current_level] = current_number_map.get(
current_level, 0
) + 1
else:
current_number_map[current_level] = current_number_map.get(
current_level, 0
) + 1
if verbose:
print(
'current_number_map[current_level] ='
f' current_number_map[{current_level}] ='
f' {current_number_map[current_level]}'
)
# Generate numbering text and prepend it to the string
numbered_text = self.get_numbered_text(
level_map[indent],
current_number_dict=current_number_map[current_level]
)
if verbose:
print(f'numbered_text = "{numbered_text}"')
if add_indent_back_in:
level_str = ' ' * (current_level-1) + numbered_text
level_str += text.lstrip()
else:
level_str = numbered_text + text.lstrip()
numbered_text_list.append(level_str)
return numbered_text_list
# -------------------
# File Functions
# -------------------
@staticmethod
def get_function_file_path(func):
"""
Get the relative or absolute file path where a function is stored.
Parameters:
func: A Python function.
Returns:
A string representing the relative or absolute file path where
the function is stored.
Example:
my_function = lambda: None
file_path = nu.get_function_file_path(my_function)
print(osp.abspath(file_path))
"""
# Work out which source or compiled file an object was defined in
file_path = inspect.getfile(func)
# Is the function defined in a Jupyter notebook?
if file_path.startswith('<stdin>'):
# Return the absolute file path
return osp.abspath(file_path)
# Otherwise, return the relative file path
else:
return osp.relpath(file_path)
@staticmethod
def modify_inkscape_labels(
file_path, output_path='C:\\Users\\daveb\\Downloads\\scratchpad.svg',
verbose=False
):
"""
Modify an SVG file by changing the 'id' attribute to the value of the
'inkscape:label' and removing the 'inkscape:label' attribute.
Parameters:
file_path (str): Path to the SVG file to modify.
output_path (str): Path to save the modified SVG file.
Returns:
None
"""
if not osp.exists(file_path):
raise FileNotFoundError(
f'The file at {file_path} does not exist.'
)
# Open and parse the SVG file
with open(file_path, 'r', encoding='utf-8') as file:
svg_content = file.read()
soup = bs(svg_content, 'xml') # Use 'xml' parser for SVG
# Find all tags with 'inkscape:label' and 'id' attributes
for tag in soup.find_all(attrs={'inkscape:label': True, 'id': True}):
inkscape_label = tag.get('inkscape:label', '').strip()
tag_id = tag.get('id', '').strip()
if inkscape_label and tag_id:
if verbose:
print(f"Changing id '{tag_id}' to '{inkscape_label}'")
# Update 'id' attribute with the value of 'inkscape:label'
tag['id'] = inkscape_label
# Remove the 'inkscape:label' attribute
del tag['inkscape:label']
# Save the modified SVG content to the output file
with open(output_path, 'w', encoding='utf-8') as output_file:
output_file.write(str(soup))
# -------------------
# Path Functions
# -------------------
@staticmethod
def get_top_level_folder_paths(folder_path, verbose=False):
"""
Get all top-level folder paths within a given directory.
Parameters:
folder_path (str): The path to the directory to scan for
top-level folders.
verbose (bool, optional):
Whether to print debug or status messages. Defaults to False.
Returns:
list[str]: A list of absolute paths to all top-level folders
within the provided directory.
Raises:
FileNotFoundError: If the provided folder path does not exist.
NotADirectoryError:
If the provided folder path points to a file or non-existing
directory.
Notes:
This function does not recursively scan for subfolders within the
top-level folders. If `verbose` is True, it will print the number
of discovered top-level folders.
"""
# Make sure the provided folder exists and is a directory
if not osp.exists(folder_path):
raise FileNotFoundError(
f'Directory {folder_path} does not exist.'
)
if not osp.isdir(folder_path):
raise NotADirectoryError(
f'Path {folder_path} is not a directory.'
)
# Initialize an empty list to store top-level folder paths
top_level_folders = []
# Iterate through items in the specified folder
for item in listdir(folder_path):
# Construct the full path for each item
full_item_path = osp.join(folder_path, item)
# Is the item a directory?
if osp.isdir(full_item_path):
# Add its path to the list
top_level_folders.append(full_item_path)
# Optionally print information based on the `verbose` flag
if verbose:
print(
f'Found {len(top_level_folders)} top-level folders'
f' in {folder_path}.'
)
# Return the list of top-level folder paths
return top_level_folders
@staticmethod
def print_all_files_ending_starting_with(
root_dir='D:\\Documents\\GitHub', ends_with='.yml',
starts_with='install_config_',
black_list=['$RECYCLE.BIN', '$Recycle.Bin']
):
if isinstance(root_dir, list):
root_dir_list = root_dir
else:
root_dir_list = [root_dir]
if isinstance(ends_with, list):
endswith_list = ends_with
else:
endswith_list = [ends_with]
if isinstance(starts_with, list):
startswith_list = starts_with
else:
startswith_list = [starts_with]
for root_dir in root_dir_list:
for sub_directory, directories_list, files_list in os.walk(
root_dir
):
if all(map(lambda x: x not in sub_directory, black_list)):
for file_name in files_list:
endswith_bool = False
for ends_with in endswith_list:
endswith_bool = (
endswith_bool or file_name.endswith(ends_with)
)
startswith_bool = False
for starts_with in startswith_list:
startswith_bool = (
startswith_bool
or file_name.startswith(starts_with)
)
if endswith_bool and startswith_bool:
file_path = osp.join(sub_directory, file_name)
print(file_path)
@staticmethod
def print_all_files_starting_with(
root_dir='D:\\Vagrant_Projects\\local-vagrant', starts_with='host',
black_list=['$RECYCLE.BIN', '$Recycle.Bin']
):
if isinstance(root_dir, list):
root_dir_list = root_dir
else:
root_dir_list = [root_dir]
if isinstance(starts_with, list):
startswith_list = starts_with
else:
startswith_list = [starts_with]
for root_dir in root_dir_list:
for sub_directory, directories_list, files_list in os.walk(
root_dir
):
if all(map(lambda x: x not in sub_directory, black_list)):
for file_name in files_list:
startswith_bool = False
for starts_with in startswith_list:
startswith_bool = (
startswith_bool
or file_name.startswith(starts_with)
)
if startswith_bool:
file_path = osp.join(sub_directory, file_name)
print(file_path)
@staticmethod
def print_all_files_ending_with(
root_dir='D:\\', ends_with='.box',
black_list=['$RECYCLE.BIN', '$Recycle.Bin']
):
if isinstance(root_dir, list):
root_dir_list = root_dir
else:
root_dir_list = [root_dir]
if isinstance(ends_with, list):
endswith_list = ends_with
else:
endswith_list = [ends_with]
for root_dir in root_dir_list:
for sub_directory, directories_list, files_list in os.walk(
root_dir
):
if all(map(lambda x: x not in sub_directory, black_list)):
for file_name in files_list:
endswith_bool = False
for ends_with in endswith_list:
endswith_bool = (
endswith_bool or file_name.endswith(ends_with)
)
if endswith_bool:
file_path = osp.join(sub_directory, file_name)
print(file_path)
@staticmethod
def get_git_lfs_track_commands(
repository_name, repository_dir='D:\\Documents\\GitHub'
):
black_list = [osp.join(repository_dir, repository_name, '.git')]
file_types_set = set()
for sub_directory, directories_list, files_list in os.walk(
osp.join(repository_dir, repository_name)
):
if all(map(lambda x: x not in sub_directory, black_list)):
for file_name in files_list:
file_path = osp.join(sub_directory, file_name)
bytes_count = osp.getsize(file_path)
if bytes_count > 50_000_000:
file_types_set.add(file_name.split('.')[-1])
print('git lfs install')
for file_type in file_types_set:
print('git lfs track "*.{}"'.format(file_type))
print('git add .gitattributes')
@staticmethod
def get_specific_gitignore_files(
repository_name, repository_dir='D:\\Documents\\GitHub',
text_editor_path='C:\\Program Files\\Notepad++\\notepad++.exe'
):
print(
'\n # Ignore big files (GitHub will warn you when pushing'
' files larger than 50 MB. You will not be allowed to\n #'
' push files larger than 100 MB.) Tip: If you regularly push'
' large files to GitHub, consider introducing\n # Git Large'
' File Storage (Git LFS) as part of your workflow.'
)
repository_path = osp.join(repository_dir, repository_name)
black_list = [osp.join(repository_path, '.git')]
for sub_directory, directories_list, files_list in os.walk(
repository_path
):
if all(map(lambda x: x not in sub_directory, black_list)):
for file_name in files_list:
file_path = osp.join(sub_directory, file_name)
bytes_count = osp.getsize(file_path)
if bytes_count > 50_000_000:
print('/'.join(
osp.relpath(file_path, repository_path).split(
os.sep
)
))
file_path = osp.join(repository_dir, repository_name, '.gitignore')
print()
subprocess.run([text_editor_path, osp.abspath(file_path)])
def remove_empty_folders(self, folder_path, remove_root=True):
"""
Function to remove empty folders
"""
if not osp.isdir(folder_path):
return
# Remove empty subfolders
files = os.listdir(folder_path)
if len(files):
for f in files:
full_path = osp.join(folder_path, f)
if osp.isdir(full_path):
self.remove_empty_folders(full_path)
# If folder empty, delete it
files = os.listdir(folder_path)
if len(files) == 0 and remove_root:
print('Removing empty folder: {}'.format(folder_path))
os.rmdir(folder_path)
@staticmethod
def get_all_directories_containing(
root_dir='C:\\', contains_str='activate',
black_list=['$RECYCLE.BIN', '$Recycle.Bin', '.git']
):
dir_path_list = []
if type(root_dir) == list:
root_dir_list = root_dir
else:
root_dir_list = [root_dir]
if type(contains_str) == list:
contains_list = contains_str
else:
contains_list = [contains_str]
for root_dir in root_dir_list:
for sub_directory, directories_list, files_list in os.walk(
root_dir
):
if all(map(lambda x: x not in sub_directory, black_list)):
for dir_name in directories_list:
contains_bool = False
for contains_str in contains_list:
contains_bool = (
contains_bool or contains_str in dir_name
)
if contains_bool:
dir_path = osp.join(sub_directory, dir_name)
dir_path_list.append(dir_path)
return dir_path_list
@staticmethod
def get_all_directories_named(
root_dir='C:\\', named_str='activate',
black_list=['$RECYCLE.BIN', '$Recycle.Bin', '.git']
):
dir_path_list = []
if type(root_dir) == list:
root_dir_list = root_dir
else:
root_dir_list = [root_dir]
if type(named_str) == list:
named_list = named_str
else:
named_list = [named_str]
for root_dir in root_dir_list:
for parent_directory, child_folders, _ in os.walk(root_dir):
if all(map(lambda x: x not in parent_directory, black_list)):
for dir_name in child_folders:
named_bool = False
for named_str in named_list:
named_bool = named_bool or named_str == dir_name
if named_bool:
dir_path = osp.join(parent_directory, dir_name)
dir_path_list.append(dir_path)
return dir_path_list
# -------------------
# Storage Functions
# -------------------
# -------------------
# Module Functions
# -------------------
def add_staticmethod_decorations(
self, python_folder=osp.join(os.pardir, 'py'), verbose=True
):
"""
Scan a Python folder structure and automatically add static method
decorators to non-static method-decorated instance methods.
This method searches through all Python files in a specified
folder, excluding certain blacklisted directories, and refactors
functions that do not reference the 'self' variable to be static
methods by adding the static method decorator.
Parameters:
python_folder (str, optional):
Relative path to the folder to scan for Python files
verbose (bool, optional):
Whether to print debug or status messages. Defaults to False.
Returns:
None
Note:
This function modifies files in-place. It's recommended to back
up the folder structure before running it.
"""
# Create a list of directories to exclude from the search
black_list = ['.ipynb_checkpoints', '$Recycle.Bin']
# Print starting message if verbose
if verbose:
print(
'Scanning Python folder structure to add staticmethod'
' decorations'
)
# Helper funtion
def f():
# Open the file and read its contents
with open(file_path, 'r', encoding=self.encoding_type) as f:
file_text = f.read()
# Split the file text into function parts
fn_parts_list = self.instance_defs_regex.split(file_text)
# Iterate over function names and bodies
for fn_name, fn_body in zip(
fn_parts_list[1::2], fn_parts_list[2::2]
):
# Check if the function body does not use 'self'
if not self.self_regex.search(fn_body):
# Create a new regex specific to the method name
s = f'^ def {fn_name}\\(\\s*self' # noqa: E272, E222
s += ',\\s+(?:[^\\)]+)\\):' # noqa: E231
instance_def_regex = re.compile(s, re.MULTILINE)
# Search for the method definition in the file text
match_obj = instance_def_regex.search(file_text)
# Update file text if method is not decorated
if match_obj:
replaced_str = match_obj.group()
# Prepare str with static method decorator
replacing_str = ' @staticmethod\n'
replacing_str += replaced_str.replace('self, ', '')
# Replace original method def with refactored one
file_text = file_text.replace(
replaced_str, replacing_str
)
# Write the modified text back to the file
with open(file_path, 'w', encoding=self.encoding_type) as f:
print(file_text.rstrip(), file=f)
# Walk through the directory tree
for sub_directory, directories_list, files_list in walk(
python_folder
):
# Skip blacklisted directories
if all(map(lambda x: x not in sub_directory, black_list)):
# Process each Python file in the directory
for file_name in files_list:
if file_name.endswith('.py'):
# Construct the full path to the Python file
file_path = osp.join(sub_directory, file_name)
try:
f()
# Handle any exceptions during file read/write
except Exception as e:
print(
f'{e.__class__.__name__} error trying to'
f' read {file_name}: {str(e).strip()}'
)
def update_modules_list(self, modules_list=None, verbose=False):
"""
Update the list of modules that are installed.
Parameters:
modules_list (list of str, optional):
The list of modules to update. If None, the list of installed
modules will be used. Defaults to None.
verbose (bool, optional):
Whether to print debug or status messages. Defaults to False.
Returns:
None
"""
# Create the modules list with pip if not supplied
if modules_list is None:
self.modules_list = [
o.decode().split(' ')[0]
for o in subprocess.check_output(
f'{self.pip_command_str} list'.split(' ')
).splitlines()[2:]
]
# Set the class variable if it is
else: