pygenutils 15.11.1__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.
Files changed (39) hide show
  1. pygenutils/__init__.py +18 -0
  2. pygenutils/arrays_and_lists/__init__.py +12 -0
  3. pygenutils/arrays_and_lists/conversions.py +265 -0
  4. pygenutils/arrays_and_lists/data_manipulation.py +590 -0
  5. pygenutils/arrays_and_lists/maths.py +123 -0
  6. pygenutils/arrays_and_lists/patterns.py +478 -0
  7. pygenutils/audio_and_video/__init__.py +12 -0
  8. pygenutils/audio_and_video/audio_and_video_manipulation.py +399 -0
  9. pygenutils/audio_and_video/merge_audio_and_video.py +73 -0
  10. pygenutils/audio_and_video/merge_audio_or_video.py +54 -0
  11. pygenutils/audio_and_video/trim_media.py +55 -0
  12. pygenutils/dictionaries/__init__.py +10 -0
  13. pygenutils/dictionaries/dict_handler.py +127 -0
  14. pygenutils/dictionaries/dict_operators.py +105 -0
  15. pygenutils/number_bases/__init__.py +11 -0
  16. pygenutils/number_bases/base_converters.py +363 -0
  17. pygenutils/number_bases/binary_operations.py +183 -0
  18. pygenutils/number_bases/bitwise_operators.py +137 -0
  19. pygenutils/operative_systems/__init__.py +9 -0
  20. pygenutils/operative_systems/os_operations.py +386 -0
  21. pygenutils/sets_and_intervals/__init__.py +10 -0
  22. pygenutils/sets_and_intervals/interval_handler.py +251 -0
  23. pygenutils/sets_and_intervals/sets_handler.py +110 -0
  24. pygenutils/strings/__init__.py +10 -0
  25. pygenutils/strings/string_handler.py +830 -0
  26. pygenutils/strings/text_formatters.py +640 -0
  27. pygenutils/time_handling/__init__.py +14 -0
  28. pygenutils/time_handling/calendar_utils.py +341 -0
  29. pygenutils/time_handling/countdown.py +132 -0
  30. pygenutils/time_handling/date_and_time_maths.py +801 -0
  31. pygenutils/time_handling/date_and_time_utils.py +900 -0
  32. pygenutils/time_handling/program_snippet_exec_timers.py +250 -0
  33. pygenutils/time_handling/time_formatters.py +1053 -0
  34. pygenutils/time_handling/time_utils.py +112 -0
  35. pygenutils-15.11.1.dist-info/METADATA +203 -0
  36. pygenutils-15.11.1.dist-info/RECORD +39 -0
  37. pygenutils-15.11.1.dist-info/WHEEL +5 -0
  38. pygenutils-15.11.1.dist-info/licenses/LICENSE +21 -0
  39. pygenutils-15.11.1.dist-info/top_level.txt +1 -0
pygenutils/__init__.py ADDED
@@ -0,0 +1,18 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ # pygenutils/__init__.py
5
+
6
+ __version__ = "15.11.1"
7
+
8
+ # Define what should be available when using 'from pygenutils import *'
9
+ __all__ = [
10
+ 'arrays_and_lists',
11
+ 'audio_and_video',
12
+ 'dictionaries',
13
+ 'number_bases',
14
+ 'operative_systems',
15
+ 'sets_and_intervals',
16
+ 'strings',
17
+ 'time_handling',
18
+ ]
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ # pygenutils/arrays_and_lists/__init__.py
5
+
6
+ # Define what should be available when using 'from pygenutils.arrays_and_lists import *'
7
+ __all__ = [
8
+ 'conversions',
9
+ 'data_manipulation',
10
+ 'maths',
11
+ 'patterns'
12
+ ]
@@ -0,0 +1,265 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ #----------------#
5
+ # Import modules #
6
+ #----------------#
7
+
8
+ import numpy as np
9
+
10
+ #------------------------#
11
+ # Import project modules #
12
+ #------------------------#
13
+
14
+ from filewise.general.introspection_utils import get_type_str
15
+
16
+ #------------------#
17
+ # Define functions #
18
+ #------------------#
19
+
20
+ # Data types #
21
+ #------------#
22
+
23
+ def convert_data_type(obj_data, old_type, new_type, colnames=None, convert_to_list=False):
24
+ """
25
+ Function that converts the original data type of the values in a given object
26
+ (numpy array, pandas DataFrame/Series) to the desired one.
27
+ If the new data type is the same as the original, the function returns
28
+ the object unchanged, and prints a message showing the latter.
29
+
30
+ Parameters
31
+ ----------
32
+ obj_data : pandas.DataFrame, pandas.Series, numpy.ndarray, or list
33
+ Object containing the data to be converted.
34
+ old_type : str
35
+ Current type of the object's values.
36
+ new_type : str
37
+ Type to which the data should be converted.
38
+ colnames : str, list of str, or '__all_columns__', optional
39
+ Column(s) to apply conversion in case of pandas DataFrame.
40
+ If '__all_columns__', conversion will be applied to all columns.
41
+ Not applicable for pandas Series or numpy arrays.
42
+ convert_to_list : bool, optional
43
+ If True, converts the result to a list before returning.
44
+
45
+ Returns
46
+ -------
47
+ obj_data : pandas.DataFrame, pandas.Series, numpy.ndarray, or list
48
+ Object with the converted data type, or unchanged if no conversion was made.
49
+
50
+ Raises
51
+ ------
52
+ TypeError
53
+ If the conversion to the new type cannot be done or if the object type is invalid.
54
+ KeyError
55
+ If specified columns are not found in pandas DataFrame.
56
+ """
57
+ # Get input object's type
58
+ obj_type = get_type_str(obj_data)
59
+
60
+ # Handle pandas DataFrames
61
+ if obj_type == "DataFrame":
62
+ if colnames is None:
63
+ raise ValueError("Please specify 'colnames' for pandas DataFrame.")
64
+ if colnames == '__all_columns__': # apply to all columns
65
+ colnames = obj_data.columns
66
+ elif isinstance(colnames, str):
67
+ colnames = [colnames] # convert to list for consistency
68
+ elif isinstance(colnames, list):
69
+ pass
70
+ else:
71
+ raise TypeError("'colnames' must be a string, list of strings, or '__all_columns__'.")
72
+
73
+ # Find missing columns
74
+ missing_cols = [col for col in colnames if col not in obj_data.columns]
75
+ if missing_cols:
76
+ raise KeyError(f"The following columns were not found: {missing_cols}")
77
+
78
+ # Apply conversion
79
+ data_converted = obj_data.copy()
80
+ for col in colnames:
81
+ if obj_data[col].dtype == old_type:
82
+ try:
83
+ data_converted[col] = obj_data[col].astype(new_type)
84
+ except:
85
+ raise TypeError(f"Cannot convert column '{col}' to type '{new_type}'.")
86
+ else:
87
+ print(f"Column '{col}' data type unchanged.")
88
+
89
+ return data_converted
90
+
91
+ # Handle pandas Series
92
+ elif obj_type == "Series":
93
+ if obj_data.dtype == old_type:
94
+ try:
95
+ return obj_data.astype(new_type)
96
+ except:
97
+ raise TypeError(f"Cannot convert Series to type '{new_type}'.")
98
+ else:
99
+ print("Series data type unchanged.")
100
+ return obj_data
101
+
102
+ # Handle numpy arrays and lists
103
+ elif obj_type in ["ndarray", "list"]:
104
+ try:
105
+ obj_data = np.array(obj_data) # convert to numpy array if it's not already
106
+ if obj_data.dtype == old_type:
107
+ try:
108
+ data_converted = obj_data.astype(new_type)
109
+ except:
110
+ raise TypeError(f"Cannot convert array to type '{new_type}'.")
111
+ if convert_to_list:
112
+ return list(data_converted)
113
+ return data_converted
114
+ else:
115
+ print("Array data type unchanged.")
116
+ if convert_to_list:
117
+ return list(obj_data)
118
+ return obj_data
119
+ except Exception as e:
120
+ raise TypeError(f"Error occurred during conversion: {e}")
121
+
122
+ # Raise TypeError if the object type is not supported
123
+ else:
124
+ raise TypeError("Unsupported object type. "
125
+ "Expected pandas DataFrame/Series, numpy array, or list.")
126
+
127
+
128
+ def combine_arrays(array_of_lists):
129
+ """
130
+ Combine a list of NumPy arrays or lists into a single NumPy array.
131
+
132
+ This function takes a list of NumPy arrays (or lists) and combines them
133
+ into a single NumPy array. It supports arrays with up to 3 dimensions.
134
+ If the arrays have inhomogeneous lengths, it uses `np.hstack` to flatten
135
+ and concatenate the arrays.
136
+
137
+ Parameters
138
+ ----------
139
+ array_of_lists : list
140
+ A list of NumPy arrays or lists to be combined.
141
+
142
+ Returns
143
+ -------
144
+ array : numpy.ndarray
145
+ A single NumPy array formed by combining the input arrays.
146
+
147
+ Raises
148
+ ------
149
+ ValueError
150
+ - If the arrays in the list have more than 3 dimensions.
151
+ - If the shapes of the arrays are inconsistent and cannot be combined.
152
+
153
+ Example
154
+ -------
155
+ >>> import numpy as np
156
+ >>> array1 = np.array([[1, 2], [3, 4]])
157
+ >>> array2 = np.array([[5, 6], [7, 8]])
158
+ >>> array_of_lists = [array1, array2]
159
+ >>> result = combine_arrays(array_of_lists)
160
+ >>> print(result)
161
+ [[1 2]
162
+ [3 4]
163
+ [5 6]
164
+ [7 8]]
165
+
166
+ Notes
167
+ -----
168
+ - If the arrays have different shapes, they are concatenated and flattened
169
+ using `np.hstack`.
170
+ - This function assumes that the input contains valid NumPy arrays or lists.
171
+ """
172
+ # Get the list of unique dimensions of the arrays #
173
+ dim_list = np.unique([arr.ndim for arr in array_of_lists])
174
+ ld = len(dim_list)
175
+
176
+ # If all arrays/lists are of the same dimension #
177
+ if ld == 1:
178
+ dims = dim_list[0]
179
+
180
+ if dims == 2:
181
+ array = np.vstack(array_of_lists)
182
+ elif dims == 3:
183
+ array = np.stack(array_of_lists)
184
+ else:
185
+ raise ValueError("Cannot handle arrays with dimensions greater than 3.")
186
+
187
+ # If the arrays/lists have inconsistent dimensions #
188
+ else:
189
+ array = np.hstack(array_of_lists)
190
+
191
+ return array
192
+
193
+
194
+ def flatten_to_string(obj, delim=" ", add_final_space=False):
195
+ """
196
+ Flatten the content of a list, NumPy array, or pandas DataFrame/Series
197
+ into a single string, where elements are separated by a specified delimiter.
198
+
199
+ This method takes an input object (list, NumPy array, pandas DataFrame, or Series),
200
+ flattens it (if needed), converts all elements to strings, and joins them into
201
+ a single string. Optionally, a final delimiter can be added to the end of the string.
202
+
203
+ Parameters
204
+ ----------
205
+ obj : list, numpy.ndarray, pandas.DataFrame, or pandas.Series
206
+ The input object containing data to be flattened and converted to a string.
207
+ delim : str, optional
208
+ The delimiter to use for separating elements in the resulting string.
209
+ By default, a space character (' ') is used.
210
+ add_final_space : bool, optional
211
+ If True, adds a delimiter (or space) at the end of the string.
212
+ Default is False.
213
+
214
+ Returns
215
+ -------
216
+ str
217
+ A single string containing all elements of the input object,
218
+ separated by the specified delimiter.
219
+
220
+ Raises
221
+ ------
222
+ TypeError
223
+ If the input object is not a list, numpy array, pandas DataFrame, or Series.
224
+
225
+ Example
226
+ -------
227
+ >>> import numpy as np
228
+ >>> arr = np.array([[1, 2], [3, 4]])
229
+ >>> flatten_to_string(arr, delim=',', add_final_space=True)
230
+ '1,2,3,4,'
231
+
232
+ Notes
233
+ -----
234
+ This method is particularly useful for converting arrays or lists of file names
235
+ into a single string to pass as arguments to shell commands or other processes
236
+ that require string input.
237
+ """
238
+ # Get input object type
239
+ obj_type = get_type_str(obj)
240
+
241
+ # Validate input type #
242
+ if obj_type not in ["list", "ndarray", "DataFrame", "Series"]:
243
+ raise TypeError("'flatten_to_string' supports lists, NumPy arrays, and pandas DataFrames/Series.")
244
+
245
+ # Convert pandas DataFrame/Series to NumPy array #
246
+ if obj_type not in ["DataFrame", "Series"]:
247
+ obj_val_array = obj.values
248
+ else:
249
+ obj_val_array = np.array(obj) # Ensure it's a NumPy array if it's a list
250
+
251
+ # Flatten the array if it has more than one dimension #
252
+ if hasattr(obj_val_array, "flatten"):
253
+ obj_val_array = obj_val_array.flatten()
254
+
255
+ # Convert all elements to strings #
256
+ obj_list = [str(el) for el in obj_val_array]
257
+
258
+ # Join all elements into a single string #
259
+ allobj_string = delim.join(obj_list)
260
+
261
+ # Optionally add a final delimiter/space #
262
+ if add_final_space:
263
+ allobj_string += delim
264
+
265
+ return allobj_string