Diff of /utils/filemanager.py [000000] .. [6fe801]

Switch to unified view

a b/utils/filemanager.py
1
import os
2
import sys
3
import pandas as pd
4
from glob import glob
5
from .logger import logger
6
import re
7
8
def extract_parameter(text):
9
    '''
10
    Extract the parameter number from the text.
11
12
    Args:
13
        text ('str'): Text to search for the parameter number.
14
15
    Returns:
16
        parameter_number ('str'): Parameter number.
17
    '''
18
    match = re.search(r'Par(\w+)', text)
19
    if match:
20
        return 'Par' + match.group(1)
21
    else:
22
        return None
23
24
25
26
def get_points_paths(base_path, suffix, num_occurrences = 2):
27
    '''
28
    Get the paths of the transformed points.
29
30
    Args:
31
        args ('argparse.Namespace'): Command line arguments.
32
        suffix ('str'): Suffix of the file name.
33
        num_occurrences ('int'): Number of occurrences of the suffix in the path.
34
35
    Returns:
36
        paths ('list'): List of paths.
37
    '''
38
    paths = [path.replace('\\', '/') for path in sorted(glob(os.path.join(base_path, *["***"] * num_occurrences , f"*{suffix}.txt"), recursive=True))]
39
    return paths
40
41
def get_paths(args, suffix):
42
    '''
43
    Get the paths of the volumes and segmentations.
44
45
    Args:
46
        args ('argparse.Namespace'): Command line arguments.
47
        suffix ('str'): Suffix of the file name.
48
49
    Returns:
50
        paths ('list'): List of paths.
51
    '''
52
    paths = [path.replace('\\', '/') for path in sorted(glob(os.path.join(args.dataset_path, "***" , f"*{suffix}.nii.gz"), recursive=True))]
53
    return paths
54
55
def check_paths(args, paths, message):
56
    '''
57
    Check if the paths exist.
58
59
    Args:
60
        args ('argparse.Namespace'): Command line arguments.
61
        paths ('list'): List of paths.
62
        message ('str'): Message to display in the logger.
63
64
    Returns:
65
        None
66
    '''
67
    if len(paths) == 0:
68
        logger.error(f"No {message} found in {args.dataset_path} directory.")
69
        sys.exit(1)
70
71
72
def create_directory_if_not_exists(path):
73
    '''
74
    Create a directory if it does not exist.
75
76
    Args:
77
        path ('str'): Directory path.
78
    '''
79
    if not os.path.exists(path):
80
        os.makedirs(path)
81
82
def replace_text_in_file(file_path, search_text, replacement_text):
83
        '''
84
        Replace text in a text file.
85
86
        Args:
87
            file_path ('str'): Path to the text file.
88
            search_text ('str'): Text to search for in the file.
89
            replacement_text ('str'): Text to replace the searched text with.
90
        '''
91
        try:
92
            # Read the file
93
            with open(file_path, 'r') as file:
94
                content = file.read()
95
96
            # Replace the search_text with replacement_text
97
            modified_content = content.replace(search_text, replacement_text)
98
99
            # Write the modified content back to the file
100
            with open(file_path, 'w') as file:
101
                file.write(modified_content)
102
103
            # print(f"Text replaced in {file_path} and saved.")
104
        except FileNotFoundError:
105
            print(f"File not found: {file_path}")
106
        # except Exception as e:
107
        #     print(f"An error occurred: {e}")
108
109
def add_and_delete_rows(file_path, row1, row2):
110
    # Add two rows at the beginning of the file
111
    with open(file_path, 'r+') as file:
112
        content = file.read()
113
        file.seek(0, 0)
114
        file.write(row1 + '\n' + row2 + '\n' + content)
115
116
def delete_added_rows(file_path):
117
    # Delete the first two rows from the file
118
    with open(file_path, 'r') as file:
119
        lines = file.readlines()
120
121
    # Handle different newline characters when writing back to the file
122
    with open(file_path, 'w', newline=os.linesep) as file:
123
        file.writelines(lines[2:])
124
125