Skip to content

Commit 400471f

Browse files
mashb1tmidareashisteveyourcreativepeople
committed
feat: add config for temp path and temp path cleanup on launch (lllyasviel#1992)
* Added options to set the Gradio cache path and clear cache on launch. * Renamed cache to temp * clear temp * feat: do not delete temp folder but only clean content also use fallback to system temp dir see https://github.com/gradio-app/gradio/blob/6683ab2589f9d8658e1f51acc1b7526edce988d3/gradio/utils.py#L1151 * refactor: code cleanup * feat: unify arg --temp-path and new temp_path config value * feat: change default temp dir from gradio to fooocus * refactor: move temp path method definition and configs * feat: rename get_temp_path to init_temp_path --------- Co-authored-by: Magee <koshms3@gmail.com> Co-authored-by: steveyourcreativepeople <steve@yourcreativepeople.com> Co-authored-by: Manuel Schmid <manuel.schmid@odt.net>
1 parent db7d201 commit 400471f

File tree

5 files changed

+67
-15
lines changed

5 files changed

+67
-15
lines changed

args_manager.py

-3
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,4 @@
4949
if args_parser.args.disable_in_browser:
5050
args_parser.args.in_browser = False
5151

52-
if args_parser.args.temp_path is None:
53-
args_parser.args.temp_path = os.path.join(gettempdir(), 'Fooocus')
54-
5552
args = args_parser.args

launch.py

+14-7
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import os
2-
import sys
32
import ssl
3+
import sys
44

55
print('[System ARGV] ' + str(sys.argv))
66

@@ -15,15 +15,13 @@
1515

1616
ssl._create_default_https_context = ssl._create_unverified_context
1717

18-
1918
import platform
2019
import fooocus_version
2120

2221
from build_launcher import build_launcher
23-
from modules.launch_util import is_installed, run, python, run_pip, requirements_met
22+
from modules.launch_util import is_installed, run, python, run_pip, requirements_met, delete_folder_content
2423
from modules.model_loader import load_file_from_url
2524

26-
2725
REINSTALL_ALL = False
2826
TRY_INSTALL_XFORMERS = False
2927

@@ -68,6 +66,7 @@ def prepare_environment():
6866
'https://huggingface.co/lllyasviel/misc/resolve/main/xl-to-v1_interposer-v3.1.safetensors')
6967
]
7068

69+
7170
def ini_args():
7271
from args_manager import args
7372
return args
@@ -77,14 +76,23 @@ def ini_args():
7776
build_launcher()
7877
args = ini_args()
7978

80-
8179
if args.gpu_device_id is not None:
8280
os.environ['CUDA_VISIBLE_DEVICES'] = str(args.gpu_device_id)
8381
print("Set device to:", args.gpu_device_id)
8482

85-
8683
from modules import config
8784

85+
os.environ['GRADIO_TEMP_DIR'] = config.temp_path
86+
87+
if config.temp_path_cleanup_on_launch:
88+
print(f'[Cleanup] Attempting to delete content of temp dir {config.temp_path}')
89+
result = delete_folder_content(config.temp_path, '[Cleanup] ')
90+
if result:
91+
print("[Cleanup] Cleanup successful")
92+
else:
93+
print(f"[Cleanup] Failed to delete content of temp dir.")
94+
95+
8896
def download_models():
8997
for file_name, url in vae_approx_filenames:
9098
load_file_from_url(url=url, model_dir=config.path_vae_approx, file_name=file_name)
@@ -123,5 +131,4 @@ def download_models():
123131

124132
download_models()
125133

126-
127134
from webui import *

modules/config.py

+35-1
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,15 @@
33
import math
44
import numbers
55
import args_manager
6+
import tempfile
67
import modules.flags
78
import modules.sdxl_styles
89

910
from modules.model_loader import load_file_from_url
1011
from modules.util import get_files_from_folder, makedirs_with_log
1112
from modules.flags import OutputFormat, Performance, MetadataScheme
1213

14+
1315
def get_config_path(key, default_value):
1416
env = os.getenv(key)
1517
if env is not None and isinstance(env, str):
@@ -18,6 +20,7 @@ def get_config_path(key, default_value):
1820
else:
1921
return os.path.abspath(default_value)
2022

23+
2124
config_path = get_config_path('config_path', "./config.txt")
2225
config_example_path = get_config_path('config_example_path', "config_modification_tutorial.txt")
2326
config_dict = {}
@@ -117,7 +120,7 @@ def get_path_output() -> str:
117120
global config_dict
118121
path_output = get_dir_or_set_default('path_outputs', '../outputs/', make_directory=True)
119122
if args_manager.args.output_path:
120-
print(f'[CONFIG] Overriding config value path_outputs with {args_manager.args.output_path}')
123+
print(f'Overriding config value path_outputs with {args_manager.args.output_path}')
121124
config_dict['path_outputs'] = path_output = args_manager.args.output_path
122125
return path_output
123126

@@ -178,6 +181,7 @@ def get_dir_or_set_default(key, default_value, as_array=False, make_directory=Fa
178181
path_fooocus_expansion = get_dir_or_set_default('path_fooocus_expansion', '../models/prompt_expansion/fooocus_expansion')
179182
path_outputs = get_path_output()
180183

184+
181185
def get_config_item_or_set_default(key, default_value, validator, disable_empty_as_none=False):
182186
global config_dict, visited_keys
183187

@@ -206,6 +210,36 @@ def get_config_item_or_set_default(key, default_value, validator, disable_empty_
206210
return default_value
207211

208212

213+
def init_temp_path(path: str | None, default_path: str) -> str:
214+
if args_manager.args.temp_path:
215+
path = args_manager.args.temp_path
216+
217+
if path != '' and path != default_path:
218+
try:
219+
if not os.path.isabs(path):
220+
path = os.path.abspath(path)
221+
os.makedirs(path, exist_ok=True)
222+
print(f'Using temp path {path}')
223+
return path
224+
except Exception as e:
225+
print(f'Could not create temp path {path}. Reason: {e}')
226+
print(f'Using default temp path {default_path} instead.')
227+
228+
os.makedirs(default_path, exist_ok=True)
229+
return default_path
230+
231+
232+
default_temp_path = os.path.join(tempfile.gettempdir(), 'fooocus')
233+
temp_path = init_temp_path(get_config_item_or_set_default(
234+
key='temp_path',
235+
default_value=default_temp_path,
236+
validator=lambda x: isinstance(x, str),
237+
), default_temp_path)
238+
temp_path_cleanup_on_launch = get_config_item_or_set_default(
239+
key='temp_path_cleanup_on_launch',
240+
default_value=True,
241+
validator=lambda x: isinstance(x, bool)
242+
)
209243
default_base_model_name = get_config_item_or_set_default(
210244
key='default_model',
211245
default_value='model.safetensors',

modules/launch_util.py

+17-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import os
22
import importlib
33
import importlib.util
4+
import shutil
45
import subprocess
56
import sys
67
import re
@@ -9,9 +10,6 @@
910
import packaging.version
1011
from packaging.requirements import Requirement
1112

12-
13-
14-
1513
logging.getLogger("torch.distributed.nn").setLevel(logging.ERROR) # sshh...
1614
logging.getLogger("xformers").addFilter(lambda record: 'A matching Triton is not available' not in record.getMessage())
1715

@@ -101,3 +99,19 @@ def requirements_met(requirements_file):
10199

102100
return True
103101

102+
103+
def delete_folder_content(folder, prefix=None):
104+
result = True
105+
106+
for filename in os.listdir(folder):
107+
file_path = os.path.join(folder, filename)
108+
try:
109+
if os.path.isfile(file_path) or os.path.islink(file_path):
110+
os.unlink(file_path)
111+
elif os.path.isdir(file_path):
112+
shutil.rmtree(file_path)
113+
except Exception as e:
114+
print(f'{prefix}Failed to delete {file_path}. Reason: {e}')
115+
result = False
116+
117+
return result

modules/private_logger.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ def get_current_html_path(output_format=None):
2222

2323

2424
def log(img, metadata, metadata_parser: MetadataParser | None = None, output_format=None) -> str:
25-
path_outputs = args_manager.args.temp_path if args_manager.args.disable_image_log else modules.config.path_outputs
25+
path_outputs = modules.config.temp_path if args_manager.args.disable_image_log else modules.config.path_outputs
2626
output_format = output_format if output_format else modules.config.default_output_format
2727
date_string, local_temp_filename, only_name = generate_temp_filename(folder=path_outputs, extension=output_format)
2828
os.makedirs(os.path.dirname(local_temp_filename), exist_ok=True)

0 commit comments

Comments
 (0)