I/O Utilities¶
The io module provides a collection of utility functions for handling various input/output operations, including file system interactions, and working with different file formats.
copy_dir(src, dst, replace=False)
¶
Copies a directory tree from the source to the destination.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
src
|
PathLike
|
The source directory path. |
required |
dst
|
PathLike
|
The destination directory path. |
required |
replace
|
bool
|
If True, the destination directory will be deleted if it already exists. Defaults to False. |
False
|
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the source directory does not exist. |
FileExistsError
|
If the destination directory already exists and
|
Example
Copy a directory to a new destination:
Replace an existing destination directory:
Output:Source code in opencrate/core/utils/io/system.py
create_archive(output_filename, source_dir, format='zip')
¶
Creates an archive from a directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_filename
|
str
|
The name of the archive file (without extension). |
required |
source_dir
|
PathLike
|
The path to the source directory. |
required |
format
|
str
|
The archive format. Valid formats are: 'zip', 'tar', 'gztar', 'bztar', and 'xztar'. Defaults to 'zip'. |
'zip'
|
Example
Create a zip archive:
Output:Create a gzipped tar archive for better compression:
Output:Source code in opencrate/core/utils/io/system.py
create_dir(path, replace=False)
¶
Creates a directory at the specified path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
PathLike
|
The path to the directory to be created. |
required |
replace
|
bool
|
If True, the directory will be deleted if it already exists. Defaults to False. |
False
|
Raises:
| Type | Description |
|---|---|
FileExistsError
|
If the directory already exists and |
Example
Create a new directory:
Output:Replace an existing directory:
Output:Source code in opencrate/core/utils/io/system.py
delete_dir(path)
¶
Deletes a directory and all its contents recursively.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
PathLike
|
The path to the directory to be deleted. |
required |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the directory does not exist. |
Example
Delete a directory:
Output:Raise an error if the directory does not exist:
Output:Source code in opencrate/core/utils/io/system.py
delete_file(file_path)
¶
Deletes a file at the specified path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
PathLike
|
The path to the file. |
required |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the file does not exist. |
Example
Delete a file:
Output:Raise an error if the file does not exist:
Output:Source code in opencrate/core/utils/io/system.py
download_file(url, file_path, replace=False)
¶
Downloads a file from a URL and saves it to the specified path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
The URL of the file to download. |
required |
file_path
|
PathLike
|
The path to save the downloaded file. |
required |
replace
|
bool
|
If True, the file will be deleted if it already exists. Defaults to False. |
False
|
Raises:
| Type | Description |
|---|---|
FileExistsError
|
If the file already exists and |
Example
Download a file:
Output:Download and replace an existing file:
Output:Source code in opencrate/core/utils/io/system.py
ensure_dir_exists(path)
¶
Ensures that a directory exists.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
PathLike
|
The path to the directory. |
required |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the path does not exist or is not a directory. |
Returns:
| Name | Type | Description |
|---|---|---|
Path |
Path
|
The Path object of the directory. |
Example
Check if a directory exists:
Raise an error if the directory does not exist:
Output:Source code in opencrate/core/utils/io/system.py
ensure_file_exists(path)
¶
Ensures that a file exists.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
PathLike
|
The path to the file. |
required |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the path does not exist or is not a file. |
Returns:
| Name | Type | Description |
|---|---|---|
Path |
Path
|
The Path object of the file. |
Example
Check if a file exists:
Raise an error if the file does not exist:
Output:Source code in opencrate/core/utils/io/system.py
extract_archive(archive_file, dest_dir, replace=True)
¶
Extracts an archive to a directory.
Supports formats: zip, tar, gztar, bztar, and xztar.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
archive_file
|
PathLike
|
The path to the archive. |
required |
dest_dir
|
PathLike
|
The destination directory to extract the archive to. |
required |
replace
|
bool
|
If True, the destination directory will be deleted if it already exists. Defaults to True. |
True
|
Example
Extract an archive to a new directory:
Output:Extract and replace an existing directory:
Output:Source code in opencrate/core/utils/io/system.py
get_file_extension(file_path)
¶
Returns the extension of a file from its path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
PathLike
|
The path to the file. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The extension of the file (without the dot). |
Example
Get the extension of a file:
Output:Source code in opencrate/core/utils/io/system.py
get_file_name(file_path)
¶
Returns the name of a file from its path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
PathLike
|
The path to the file. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The name of the file. |
Example
Get the name of a file:
Output:Source code in opencrate/core/utils/io/system.py
get_parent_dir(path)
¶
Returns the parent directory of a file or directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
PathLike
|
The path to the file or directory. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Path |
Path
|
The path to the parent directory. |
Example
Get the parent directory:
Output:Source code in opencrate/core/utils/io/system.py
get_size(path, unit=None)
¶
Returns the size of a file or directory in human-readable format.
This function calculates the total size of a file or directory (including all subdirectories and files recursively) and returns it in a human-readable format with appropriate units (Bytes, KB, MB, GB, TB). By default, it automatically selects the most suitable unit, but you can specify a particular unit if needed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
PathLike
|
The path to the file or directory. |
required |
unit
|
Optional[str]
|
The unit to use for the size. Valid values are 'Bytes', 'KB', 'MB', 'GB', 'TB'. If None, automatically selects the most suitable unit. Defaults to None. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The size in the specified or auto-selected unit, formatted with up to 2 decimal places (e.g., '323 Bytes', '12.52 GB', '53.45 MB'). |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the path does not exist. |
ValueError
|
If an invalid unit is specified. |
Example
Get the size with automatic unit selection:
Output:Get the size of a directory:
Output:Get the size in a specific unit:
Output:Get the size in bytes:
Output:Source code in opencrate/core/utils/io/system.py
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 | |
handle_replace(path, replace)
¶
Handles the replacement of a file or directory if it exists.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
PathLike
|
The path to the file or directory. |
required |
replace
|
bool
|
If True, the file or directory will be deleted if it already exists. |
required |
Raises:
| Type | Description |
|---|---|
FileExistsError
|
If the file or directory already exists and |
Example
Replace an existing file:
Output:Replace an existing directory:
Output:Raise an error if the path already exists and replace is False:
Output:Source code in opencrate/core/utils/io/system.py
list_dir(dir, extension=None, recursive=True)
¶
Recursively lists all files in a directory tree.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dir
|
str
|
The path to the directory. |
required |
extension
|
Optional[List[str] | str]
|
The file extension(s) to filter by. Can be a single extension as a string or a list of extensions. Defaults to None. |
None
|
Returns:
| Type | Description |
|---|---|
List[str]
|
List[str]: A list of file paths. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the directory does not exist. |
Example
List all files:
Output:List only files with a specific extension:
Output:List files with multiple extensions:
Output:Source code in opencrate/core/utils/io/system.py
move_dir(src, dst, replace=False)
¶
Moves a directory from the source to the destination.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
src
|
PathLike
|
The source directory path. |
required |
dst
|
PathLike
|
The destination directory path. |
required |
replace
|
bool
|
If True, the destination directory will be deleted if it already exists. Defaults to False. |
False
|
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the source directory does not exist. |
FileExistsError
|
If the destination directory already exists and
|
Example
Move a directory:
Output:Replace an existing destination:
Output:Source code in opencrate/core/utils/io/system.py
path_exists(path)
¶
Checks if a path exists (file or directory).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
PathLike
|
The path to check. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if the path exists, False otherwise. |
Example
Check if a file exists:
Output:Check if a directory exists:
Output:Source code in opencrate/core/utils/io/system.py
rename(src, dst, replace=False)
¶
Renames a file or directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
src
|
PathLike
|
The current path to the file or directory. |
required |
dst
|
PathLike
|
The new path for the file or directory. |
required |
replace
|
bool
|
If True, the destination will be overwritten if it already exists. Defaults to False. |
False
|
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the source file or directory does not exist. |
FileExistsError
|
If the destination already exists and |
Example
Rename a file:
Output:Replace an existing file with rename:
Output:Source code in opencrate/core/utils/io/system.py
show_files_in_dir(directory, extensions=None, depth=2, verbose=False)
¶
Displays all files in a directory tree using Rich Tree structure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directory
|
PathLike
|
The path to the directory. |
required |
extensions
|
Optional[Union[str, List[str]]]
|
File extensions to filter by. |
None
|
depth
|
Optional[int]
|
Maximum depth to display. Defaults to 2. |
2
|
verbose
|
bool
|
If True, displays file modification time and size. Defaults to False. |
False
|
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the directory does not exist. |
Example
Show all files with default depth:
Show only Python files with custom depth:
Show files with multiple extensions and unlimited depth:
Show files with verbose information:
Source code in opencrate/core/utils/io/system.py
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 | |
audio
¶
load(path, lib='librosa', **kwargs)
¶
Loads an audio file and returns its data and metadata.
This function provides a unified interface for loading audio using different libraries, returning a standardized dictionary containing the audio waveform and key properties.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
The file path to the audio file. |
required |
lib
|
str
|
The library to use for loading. Supported: "librosa", "pydub", "scipy", "soundfile", "torchaudio". Defaults to "librosa". |
'librosa'
|
**kwargs
|
Any
|
Additional keyword arguments passed to the loading function of the
selected library (e.g., |
{}
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
A dictionary with the following keys: |
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the specified file path does not exist. |
ValueError
|
If an unsupported library is specified. |
ImportError
|
If the required audio library is not installed. |
Examples:
Load an audio file using librosa (default):¶
import opencrate as oc
audio_info = oc.io.audio.load("speech.wav")
print(f"Sample Rate: {audio_info['sample_rate']}")
print(f"Duration: {audio_info['duration']:.2f}s")
Load an audio file using pydub:¶
import opencrate as oc
audio_info = oc.io.audio.load("music.mp3", lib="pydub")
# The returned data is always a NumPy array for consistency
print(f"Waveform shape: {audio_info['data'].shape}")
Load a WAV file using scipy (fast for .wav):¶
import opencrate as oc
audio_info = oc.io.audio.load("speech.wav", lib="scipy")
print(f"Loaded {audio_info['duration']:.2f}s of audio.")
Load an audio file using torchaudio:¶
import opencrate as oc
audio_info = oc.io.audio.load("music.wav", lib="torchaudio")
print(f"Channels: {audio_info['channels']}")
Source code in opencrate/core/utils/io/audio.py
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 | |
save(data, path, sample_rate, lib='soundfile', **kwargs)
¶
Saves a NumPy array as an audio file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
ndarray
|
The audio waveform to save. Must be a NumPy array. |
required |
path
|
str
|
The destination file path for the audio file. |
required |
sample_rate
|
int
|
The sample rate of the audio data. |
required |
lib
|
str
|
The library to use for saving. Supported: "soundfile", "scipy", "librosa", "torchaudio". Defaults to "soundfile". |
'soundfile'
|
**kwargs
|
Any
|
Additional keyword arguments to pass to the saving function. |
{}
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the data is not a NumPy array or an unsupported library is specified. |
ImportError
|
If the required audio library is not installed. |
IOError
|
If there is an error writing the file. |
Examples:
Generate a sine wave and save it as a WAV file:¶
import opencrate as oc
import numpy as np
sr = 22050
duration = 5
frequency = 440.0
t = np.linspace(0., duration, int(sr * duration))
amplitude = np.iinfo(np.int16).max * 0.5
data = (amplitude * np.sin(2. * np.pi * frequency * t)).astype(np.int16)
oc.io.audio.save(data, "sine_wave.wav", sr, lib="soundfile")
Save using torchaudio:¶
import opencrate as oc
import numpy as np
# Generate some audio data
data = np.random.randn(22050) # 1 second of random audio
oc.io.audio.save(data, "output.wav", 22050, lib="torchaudio")
Source code in opencrate/core/utils/io/audio.py
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 | |
checkpoint
¶
load(path, **kwargs)
¶
Loads a model, state dict, or pipeline, inferring the format.
This function acts as a universal loader, automatically selecting the
correct loading mechanism based on the file extension. Required libraries
are imported on-the-fly. For ONNX files, it returns an
onnxruntime.InferenceSession ready for execution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
The source file path. The extension determines the format. |
required |
**kwargs
|
Any
|
Additional keyword arguments to be passed to the
underlying load function (e.g., |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
Any |
Any
|
The loaded object (e.g., a |
Raises:
| Type | Description |
|---|---|
ImportError
|
If the required library for the specified format is not installed. |
ValueError
|
If the file extension is not a supported format. |
FileNotFoundError
|
If the specified path does not exist. |
Examples:
Loading PyTorch model checkpoint:
import torch.nn as nn
# First, save a checkpoint: save(model.state_dict(), "model.pt")
model = nn.Linear(10, 2)
state_dict = load("model.pt", map_location="cpu")
model.load_state_dict(state_dict)
Loading safetensors checkpoint:
import torch.nn as nn
# First, save a checkpoint: save(model.state_dict(), "model.safetensors")
model = nn.Linear(10, 2)
state_dict = load("model.safetensors", device="cpu")
model.load_state_dict(state_dict)
Loading Scikit-Learn pipeline checkpoint:
# First, save a checkpoint: save(fitted_pipe, "model.joblib")
loaded_pipeline = load("model.joblib")
# loaded_pipeline is now ready to .predict()
Loading TensorFlow/Keras model checkpoint:
# First, save a checkpoint: save(keras_model, "model.keras")
loaded_keras_model = load("model.keras")
# loaded_keras_model is now a compiled, ready-to-use model
Loading an ONNX model for inference:
import numpy as np
# First, export the model: save(pytorch_model, "model.onnx", args=...)
inference_session = load("model.onnx")
input_name = inference_session.get_inputs()[0].name
dummy_data = np.random.randn(1, 10).astype(np.float32)
result = inference_session.run(None, {input_name: dummy_data})
Source code in opencrate/core/utils/io/checkpoint.py
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 | |
save(obj, path, **kwargs)
¶
Saves a model, state dict, or pipeline, inferring the format.
This function acts as a universal saver, automatically selecting the correct saving mechanism based on the file extension of the provided path. Required libraries are imported on-the-fly.
For ONNX export, you must provide a tuple of dummy inputs via the args
keyword argument (e.g., args=(dummy_tensor,)).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
Any
|
The object to save (e.g., PyTorch model |
required |
path
|
str
|
The destination file path. The extension determines the
saving format (e.g., |
required |
**kwargs
|
Any
|
Additional keyword arguments to be passed to the
underlying save function. For ONNX, this must include |
{}
|
Raises:
| Type | Description |
|---|---|
ImportError
|
If the required library for the specified format is not installed. |
ValueError
|
If the file extension is not supported or if required
arguments for a specific format (like |
Examples:
Saving PyTorch model checkpoint:
import torch.nn as nn
pytorch_model = nn.Linear(10, 2)
oc.io.save(pytorch_model.state_dict(), "model.pt")
import torch.nn as nn
pytorch_model = nn.Linear(10, 2)
oc.io.save(pytorch_model.state_dict(), "model.safetensors")
Saving Scikit-Learn pipeline checkpoint:
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
pipe = Pipeline([("scaler", StandardScaler()), ("svc", LogisticRegression())])
oc.io.save(pipe, "model.joblib")
Saving TensorFlow/Keras model checkpoint:
import tensorflow as tf
keras_model = tf.keras.Sequential([tf.keras.layers.Dense(5)])
oc.io.save(keras_model, "model.keras")
---
Saving PyTorch model to ONNX checkpoint:
```python
import torch
import torch.nn as nn
model = nn.Linear(10, 2)
model.eval()
dummy_input = torch.randn(1, 10)
oc.io.save(
model,
"model.onnx",
args=(dummy_input,),
input_names=["input"],
output_names=["output"],
opset_version=11,
) # here you can add any other argument supported by torch.onnx.export
Source code in opencrate/core/utils/io/checkpoint.py
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 | |
csv
¶
load(path, lib='pandas', **kwargs)
¶
Loads data from a CSV file using different libraries.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
The path to the CSV file. |
required |
lib
|
str
|
The library to use for loading. Defaults to "csv". - "csv": Uses Python's built-in csv module. Returns a list of lists. - "numpy": Uses NumPy to load data. Returns a NumPy array. - "pandas": Uses pandas to load data. Returns a pandas DataFrame. |
'pandas'
|
**kwargs
|
Any
|
Additional keyword arguments passed to the loading function. |
{}
|
Returns:
| Type | Description |
|---|---|
CsvDataType
|
Union[List[list], "np.ndarray", "pd.DataFrame"]: The loaded data. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the file does not exist. |
ValueError
|
If an unsupported library is specified. |
ImportError
|
If the required library (NumPy or pandas) is not installed. |
IOError
|
If there is an issue reading the file. |
Examples:
# Load with csv library (default)
data_csv = load("data.csv")
# Returns: [['col1', 'col2'], ['1', '2'], ['3', '4']]
# Load with numpy
data_numpy = load("data.csv", lib="numpy", skiprows=1)
# Returns: numpy array with numeric data
# Load with pandas
data_pandas = load("data.csv", lib="pandas")
# Returns: pandas DataFrame
Source code in opencrate/core/utils/io/csv.py
save(data, path, lib=None, **kwargs)
¶
Saves data to a CSV file using different libraries.
The library can be specified explicitly or inferred from the data type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
The path where the CSV file will be saved. |
required |
data
|
CsvDataType
|
The data to save. Can be a list of lists, a NumPy array, or a pandas DataFrame. |
required |
lib
|
str
|
The library to use for saving. If None, it's inferred from the data type. Defaults to None. - "csv": Saves a list of lists. - "numpy": Saves a NumPy array. - "pandas": Saves a pandas DataFrame. |
None
|
**kwargs
|
Any
|
Additional keyword arguments passed to the saving function. |
{}
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the library is not specified and cannot be inferred, or if an unsupported library is specified. |
ImportError
|
If the required library (NumPy or pandas) is not installed. |
IOError
|
If there is an issue writing the file. |
Examples:
# 1. Save a list of lists using 'csv'
list_data = [["col1", "col2"], [1, 2], [3, 4]]
save("list.csv", list_data)
print(os.path.exists("list.csv"))
# True
# 2. Save a NumPy array
numpy_data = np.array([[1, 2], [3, 4]])
save("numpy.csv", numpy_data, lib="numpy", fmt="%d")
print(os.path.exists("numpy.csv"))
# True
# 3. Save a pandas DataFrame
df_data = pd.DataFrame({"A": [1, 2], "B": [3, 4]})
save("pandas.csv", df_data, index=False)
print(os.path.exists("pandas.csv"))
# True
Source code in opencrate/core/utils/io/csv.py
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 | |
gif
¶
dir_to_gif(src_dir, output_path, fps=10)
¶
Converts all images in a directory to a GIF.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
src_dir
|
str
|
Directory containing image files |
required |
output_path
|
str
|
Path where the GIF will be saved |
required |
fps
|
int
|
Frames per second for the output GIF |
10
|
Source code in opencrate/core/utils/io/gif.py
images_to_gif(images, output_path, fps=10)
¶
Converts a list of images to a GIF.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
images
|
List[Union[NDArray[Any], Image]]
|
List of images (supports numpy arrays and PIL images) |
required |
output_path
|
str
|
Path where the GIF will be saved |
required |
fps
|
int
|
Frames per second for the output GIF |
10
|
Source code in opencrate/core/utils/io/gif.py
image
¶
load(path, lib='pil', **kwargs)
¶
Load an image from a file path using either PIL or OpenCV.
This function provides a unified interface for loading images using different backends (PIL or OpenCV) while handling common image formats.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to the image file to load. |
required |
lib
|
str
|
Library to use for loading. Defaults to "pil". - "pil": Use PIL/Pillow library - "cv2": Use OpenCV library |
'pil'
|
Returns:
| Type | Description |
|---|---|
Union[NDArray[Any], Image]
|
Union[np.ndarray, Image.Image]: Loaded image. - When using PIL: Returns PIL Image object - When using OpenCV: Returns numpy array |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the specified file path does not exist. |
ValueError
|
If an unsupported library is specified or image cannot be loaded. |
IOError
|
If there's an error during the image loading process. |
Examples:
Load an image using PIL (default):
Load an image using OpenCV:
Source code in opencrate/core/utils/io/image.py
json
¶
CustomJSONEncoder
¶
Bases: JSONEncoder
Custom JSON encoder to handle additional data types. - datetime.datetime and datetime.date: converted to ISO 8601 strings. - pathlib.Path: converted to strings. - set: converted to lists.
Source code in opencrate/core/utils/io/json.py
load(path, encoding='utf-8', **kwargs)
¶
Loads data from a JSON file.
This function deserializes a JSON file into a Python object. It is a
wrapper around the standard json.load function.
Note
This function does not automatically convert strings back into complex
types like datetime or Path. If you need to deserialize these,
you can pass a custom object_hook in **kwargs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str or Path
|
The path to the JSON file to load. |
required |
encoding
|
str
|
The file encoding to use. Defaults to "utf-8". |
'utf-8'
|
**kwargs
|
Any
|
Additional keyword arguments to pass to |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
Any |
Any
|
The deserialized Python object from the JSON file. This can be a dict, list, str, int, float, bool, or None depending on the JSON content. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the specified file path does not exist. |
JSONDecodeError
|
If the file contains invalid JSON. |
OSError
|
If there is an issue reading from the file path. |
Example
Load a standard JSON file:¶
import opencrate as oc
# Assuming 'user.json' contains: {"name": "John Doe"}
user_data = oc.io.json.load("user.json")
print(user_data)
# Output: {'name': 'John Doe'}
Handle a file that does not exist:¶
Custom arguments that will be passed on to the json.loads internally¶
import opencrate as oc
from datetime import datetime
import re
def datetime_parser(dct):
# A simple object_hook to find and convert ISO date strings
for k, v in dct.items():
if isinstance(v, str) and re.match(r'^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d+$', v):
try:
dct[k] = datetime.fromisoformat(v)
except (ValueError, TypeError):
pass # Ignore if conversion fails
return dct
report_data = oc.io.json.load("report.json", object_hook=datetime_parser)
print(type(report_data.get("timestamp")))
# Output: <class 'datetime.datetime'>
Source code in opencrate/core/utils/io/json.py
save(data, path, encoder=None, **kwargs)
¶
Saves data to a JSON file with extended support for additional types.
This function serializes a Python object to a JSON-formatted file. It extends
the standard json.dump with a custom encoder that can handle datetime,
pathlib.Path, and set objects.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str or Path
|
The file path where the JSON data will be saved. The directory will be created if it does not exist. |
required |
data
|
Any
|
The Python object to serialize. |
required |
**kwargs
|
Any
|
Additional keyword arguments to pass to |
{}
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If the data contains an object that cannot be serialized. |
OSError
|
If there is an issue writing to the file path. |
Example
Save a simple dictionary:¶
import opencrate as oc
user_data = {"name": "John Doe", "email": "john.doe@example.com"}
oc.io.json.save(user_data, "user.json", indent=4)
Save data containing datetime and other types:¶
Source code in opencrate/core/utils/io/json.py
text
¶
load(path, encoding='utf-8', default=None)
¶
Load text content from a file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Union[str, Path]
|
Path to the input file |
required |
encoding
|
str
|
File encoding (default: utf-8) |
'utf-8'
|
default
|
Optional[Any]
|
Default value if file doesn't exist or can't be read |
None
|
Returns:
| Type | Description |
|---|---|
str
|
The text content from the file, or default value if specified |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If file doesn't exist and no default provided |
Examples:
>>> content = load("input.txt")
>>> content = load(Path("data/file.txt"))
>>> content = load("missing.txt", default="")
>>> content = load("file.txt", encoding="latin-1")
Source code in opencrate/core/utils/io/text.py
save(data, path, encoding='utf-8')
¶
Save data content to a file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Any
|
The data content to save |
required |
path
|
Union[str, Path]
|
Path to the output file |
required |
encoding
|
str
|
File encoding (default: utf-8) |
'utf-8'
|
Examples:
>>> save("Hello world", "output.txt")
>>> save("Content", Path("data/file.txt"))
>>> save("UTF-8 data", "file.txt", encoding="utf-8")
Source code in opencrate/core/utils/io/text.py
video
¶
load(path, lib='cv2', **kwargs)
¶
Loads a video file and returns its frames, audio, and metadata.
This function provides a unified interface for loading videos using different libraries, returning a standardized dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
The file path to the video file. |
required |
lib
|
str
|
The library to use for loading. Supported: "cv2", "moviepy", "torchvision", "av". Defaults to "cv2". |
'cv2'
|
**kwargs
|
Any
|
Additional keyword arguments passed to the loading function of the selected library. |
{}
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
A dictionary with the following keys: |
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the specified file path does not exist. |
ValueError
|
If an unsupported library is specified. |
ImportError
|
If the required video library is not installed. |
Examples:
Load a video using OpenCV (cv2):¶
import opencrate as oc
video_info = oc.io.video.load("my_video.mp4", lib="cv2")
print(f"Loaded {video_info['frame_count']} frames at {video_info['fps']:.2f} FPS.")
# Note: 'cv2' does not load audio.
Load a video with audio using moviepy:¶
import opencrate as oc
video_info = oc.io.video.load("my_video.mp4", lib="moviepy")
if video_info['audio'] is not None:
print(f"Audio loaded with sample rate: {video_info['audio_fps']}")
Load a video using torchvision (efficient):¶
import opencrate as oc
video_info = oc.io.video.load("my_video.mp4", lib="torchvision")
print(f"Loaded video of size {video_info['width']}x{video_info['height']}.")
Source code in opencrate/core/utils/io/video.py
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 | |
save(frames, path, fps, lib='cv2', audio=None, audio_fps=None, **kwargs)
¶
Saves a sequence of frames as a video file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frames
|
Iterable[ndarray] or ndarray
|
An iterable of frames (H, W, C) or a single NumPy array of shape (T, H, W, C). Frames should be in RGB format. |
required |
path
|
str
|
The destination file path for the video file. |
required |
fps
|
float
|
The frames per second for the output video. |
required |
lib
|
str
|
The library to use for saving. Supported: "cv2", "moviepy", "torchvision". Defaults to "cv2". |
'cv2'
|
audio
|
ndarray
|
An optional audio track to add to the video. |
None
|
audio_fps
|
int
|
The sample rate of the audio track. Required if
|
None
|
**kwargs
|
Any
|
Additional keyword arguments passed to the saving function.
For 'cv2', |
{}
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If input parameters are invalid or an unsupported library is specified. |
ImportError
|
If the required video library is not installed. |
IOError
|
If there is an error writing the file. |
Source code in opencrate/core/utils/io/video.py
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 | |