ohcaidek commited on
Commit
50dbbcf
·
verified ·
1 Parent(s): d74e70e

Upload folder_paths.py

Browse files
Files changed (1) hide show
  1. folder_paths.py +267 -0
folder_paths.py ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ import logging
4
+
5
+ supported_pt_extensions = set(['.ckpt', '.pt', '.bin', '.pth', '.safetensors'])
6
+
7
+ folder_names_and_paths = {}
8
+
9
+ base_path = os.path.dirname(os.path.realpath(__file__))
10
+ models_dir = os.path.join(base_path, "models")
11
+ folder_names_and_paths["checkpoints"] = ([os.path.join(models_dir, "checkpoints")], supported_pt_extensions)
12
+ folder_names_and_paths["configs"] = ([os.path.join(models_dir, "configs")], [".yaml"])
13
+
14
+ folder_names_and_paths["loras"] = ([os.path.join(models_dir, "loras")], supported_pt_extensions)
15
+ folder_names_and_paths["vae"] = ([os.path.join(models_dir, "vae")], supported_pt_extensions)
16
+ folder_names_and_paths["clip"] = ([os.path.join(models_dir, "clip")], supported_pt_extensions)
17
+ folder_names_and_paths["unet"] = ([os.path.join(models_dir, "unet")], supported_pt_extensions)
18
+ folder_names_and_paths["clip_vision"] = ([os.path.join(models_dir, "clip_vision")], supported_pt_extensions)
19
+ folder_names_and_paths["style_models"] = ([os.path.join(models_dir, "style_models")], supported_pt_extensions)
20
+ folder_names_and_paths["embeddings"] = ([os.path.join(models_dir, "embeddings")], supported_pt_extensions)
21
+ folder_names_and_paths["diffusers"] = ([os.path.join(models_dir, "diffusers")], ["folder"])
22
+ folder_names_and_paths["vae_approx"] = ([os.path.join(models_dir, "vae_approx")], supported_pt_extensions)
23
+
24
+ folder_names_and_paths["controlnet"] = ([os.path.join(models_dir, "controlnet"), os.path.join(models_dir, "t2i_adapter")], supported_pt_extensions)
25
+ folder_names_and_paths["gligen"] = ([os.path.join(models_dir, "gligen")], supported_pt_extensions)
26
+
27
+ folder_names_and_paths["upscale_models"] = ([os.path.join(models_dir, "upscale_models")], supported_pt_extensions)
28
+
29
+ folder_names_and_paths["custom_nodes"] = ([os.path.join(base_path, "custom_nodes")], [])
30
+
31
+ folder_names_and_paths["hypernetworks"] = ([os.path.join(models_dir, "hypernetworks")], supported_pt_extensions)
32
+
33
+ folder_names_and_paths["photomaker"] = ([os.path.join(models_dir, "photomaker")], supported_pt_extensions)
34
+
35
+ folder_names_and_paths["classifiers"] = ([os.path.join(models_dir, "classifiers")],
36
+
37
+ folder_names_and_paths["ipadapter"] = ([os.path.join(models_dir, "ipadapter")], ["folder"])
38
+
39
+ output_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), "output")
40
+ temp_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), "temp")
41
+ input_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), "input")
42
+ user_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), "user")
43
+
44
+ filename_list_cache = {}
45
+
46
+ if not os.path.exists(input_directory):
47
+ try:
48
+ os.makedirs(input_directory)
49
+ except:
50
+ logging.error("Failed to create input directory")
51
+
52
+ def set_output_directory(output_dir):
53
+ global output_directory
54
+ output_directory = output_dir
55
+
56
+ def set_temp_directory(temp_dir):
57
+ global temp_directory
58
+ temp_directory = temp_dir
59
+
60
+ def set_input_directory(input_dir):
61
+ global input_directory
62
+ input_directory = input_dir
63
+
64
+ def get_output_directory():
65
+ global output_directory
66
+ return output_directory
67
+
68
+ def get_temp_directory():
69
+ global temp_directory
70
+ return temp_directory
71
+
72
+ def get_input_directory():
73
+ global input_directory
74
+ return input_directory
75
+
76
+
77
+ #NOTE: used in http server so don't put folders that should not be accessed remotely
78
+ def get_directory_by_type(type_name):
79
+ if type_name == "output":
80
+ return get_output_directory()
81
+ if type_name == "temp":
82
+ return get_temp_directory()
83
+ if type_name == "input":
84
+ return get_input_directory()
85
+ return None
86
+
87
+
88
+ # determine base_dir rely on annotation if name is 'filename.ext [annotation]' format
89
+ # otherwise use default_path as base_dir
90
+ def annotated_filepath(name):
91
+ if name.endswith("[output]"):
92
+ base_dir = get_output_directory()
93
+ name = name[:-9]
94
+ elif name.endswith("[input]"):
95
+ base_dir = get_input_directory()
96
+ name = name[:-8]
97
+ elif name.endswith("[temp]"):
98
+ base_dir = get_temp_directory()
99
+ name = name[:-7]
100
+ else:
101
+ return name, None
102
+
103
+ return name, base_dir
104
+
105
+
106
+ def get_annotated_filepath(name, default_dir=None):
107
+ name, base_dir = annotated_filepath(name)
108
+
109
+ if base_dir is None:
110
+ if default_dir is not None:
111
+ base_dir = default_dir
112
+ else:
113
+ base_dir = get_input_directory() # fallback path
114
+
115
+ return os.path.join(base_dir, name)
116
+
117
+
118
+ def exists_annotated_filepath(name):
119
+ name, base_dir = annotated_filepath(name)
120
+
121
+ if base_dir is None:
122
+ base_dir = get_input_directory() # fallback path
123
+
124
+ filepath = os.path.join(base_dir, name)
125
+ return os.path.exists(filepath)
126
+
127
+
128
+ def add_model_folder_path(folder_name, full_folder_path):
129
+ global folder_names_and_paths
130
+ if folder_name in folder_names_and_paths:
131
+ folder_names_and_paths[folder_name][0].append(full_folder_path)
132
+ else:
133
+ folder_names_and_paths[folder_name] = ([full_folder_path], set())
134
+
135
+ def get_folder_paths(folder_name):
136
+ return folder_names_and_paths[folder_name][0][:]
137
+
138
+ def recursive_search(directory, excluded_dir_names=None):
139
+ if not os.path.isdir(directory):
140
+ return [], {}
141
+
142
+ if excluded_dir_names is None:
143
+ excluded_dir_names = []
144
+
145
+ result = []
146
+ dirs = {}
147
+
148
+ # Attempt to add the initial directory to dirs with error handling
149
+ try:
150
+ dirs[directory] = os.path.getmtime(directory)
151
+ except FileNotFoundError:
152
+ logging.warning(f"Warning: Unable to access {directory}. Skipping this path.")
153
+
154
+ logging.debug("recursive file list on directory {}".format(directory))
155
+ for dirpath, subdirs, filenames in os.walk(directory, followlinks=True, topdown=True):
156
+ subdirs[:] = [d for d in subdirs if d not in excluded_dir_names]
157
+ for file_name in filenames:
158
+ relative_path = os.path.relpath(os.path.join(dirpath, file_name), directory)
159
+ result.append(relative_path)
160
+
161
+ for d in subdirs:
162
+ path = os.path.join(dirpath, d)
163
+ try:
164
+ dirs[path] = os.path.getmtime(path)
165
+ except FileNotFoundError:
166
+ logging.warning(f"Warning: Unable to access {path}. Skipping this path.")
167
+ continue
168
+ logging.debug("found {} files".format(len(result)))
169
+ return result, dirs
170
+
171
+ def filter_files_extensions(files, extensions):
172
+ return sorted(list(filter(lambda a: os.path.splitext(a)[-1].lower() in extensions or len(extensions) == 0, files)))
173
+
174
+
175
+
176
+ def get_full_path(folder_name, filename):
177
+ global folder_names_and_paths
178
+ if folder_name not in folder_names_and_paths:
179
+ return None
180
+ folders = folder_names_and_paths[folder_name]
181
+ filename = os.path.relpath(os.path.join("/", filename), "/")
182
+ for x in folders[0]:
183
+ full_path = os.path.join(x, filename)
184
+ if os.path.isfile(full_path):
185
+ return full_path
186
+
187
+ return None
188
+
189
+ def get_filename_list_(folder_name):
190
+ global folder_names_and_paths
191
+ output_list = set()
192
+ folders = folder_names_and_paths[folder_name]
193
+ output_folders = {}
194
+ for x in folders[0]:
195
+ files, folders_all = recursive_search(x, excluded_dir_names=[".git"])
196
+ output_list.update(filter_files_extensions(files, folders[1]))
197
+ output_folders = {**output_folders, **folders_all}
198
+
199
+ return (sorted(list(output_list)), output_folders, time.perf_counter())
200
+
201
+ def cached_filename_list_(folder_name):
202
+ global filename_list_cache
203
+ global folder_names_and_paths
204
+ if folder_name not in filename_list_cache:
205
+ return None
206
+ out = filename_list_cache[folder_name]
207
+
208
+ for x in out[1]:
209
+ time_modified = out[1][x]
210
+ folder = x
211
+ if os.path.getmtime(folder) != time_modified:
212
+ return None
213
+
214
+ folders = folder_names_and_paths[folder_name]
215
+ for x in folders[0]:
216
+ if os.path.isdir(x):
217
+ if x not in out[1]:
218
+ return None
219
+
220
+ return out
221
+
222
+ def get_filename_list(folder_name):
223
+ out = cached_filename_list_(folder_name)
224
+ if out is None:
225
+ out = get_filename_list_(folder_name)
226
+ global filename_list_cache
227
+ filename_list_cache[folder_name] = out
228
+ return list(out[0])
229
+
230
+ def get_save_image_path(filename_prefix, output_dir, image_width=0, image_height=0):
231
+ def map_filename(filename):
232
+ prefix_len = len(os.path.basename(filename_prefix))
233
+ prefix = filename[:prefix_len + 1]
234
+ try:
235
+ digits = int(filename[prefix_len + 1:].split('_')[0])
236
+ except:
237
+ digits = 0
238
+ return (digits, prefix)
239
+
240
+ def compute_vars(input, image_width, image_height):
241
+ input = input.replace("%width%", str(image_width))
242
+ input = input.replace("%height%", str(image_height))
243
+ return input
244
+
245
+ filename_prefix = compute_vars(filename_prefix, image_width, image_height)
246
+
247
+ subfolder = os.path.dirname(os.path.normpath(filename_prefix))
248
+ filename = os.path.basename(os.path.normpath(filename_prefix))
249
+
250
+ full_output_folder = os.path.join(output_dir, subfolder)
251
+
252
+ if os.path.commonpath((output_dir, os.path.abspath(full_output_folder))) != output_dir:
253
+ err = "**** ERROR: Saving image outside the output folder is not allowed." + \
254
+ "\n full_output_folder: " + os.path.abspath(full_output_folder) + \
255
+ "\n output_dir: " + output_dir + \
256
+ "\n commonpath: " + os.path.commonpath((output_dir, os.path.abspath(full_output_folder)))
257
+ logging.error(err)
258
+ raise Exception(err)
259
+
260
+ try:
261
+ counter = max(filter(lambda a: a[1][:-1] == filename and a[1][-1] == "_", map(map_filename, os.listdir(full_output_folder))))[0] + 1
262
+ except ValueError:
263
+ counter = 1
264
+ except FileNotFoundError:
265
+ os.makedirs(full_output_folder, exist_ok=True)
266
+ counter = 1
267
+ return full_output_folder, filename, counter, subfolder, filename_prefix