Skip to content

Commit 218b6d0

Browse files
committed
Apply black
1 parent 2183dba commit 218b6d0

File tree

148 files changed

+5473
-6283
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

148 files changed

+5473
-6283
lines changed

.dev_scripts/diff_images.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,13 +20,13 @@ def calc_images_mean_L1(image1_path, image2_path):
2020

2121
def parse_args():
2222
parser = argparse.ArgumentParser()
23-
parser.add_argument('image1_path')
24-
parser.add_argument('image2_path')
23+
parser.add_argument("image1_path")
24+
parser.add_argument("image2_path")
2525
args = parser.parse_args()
2626
return args
2727

2828

29-
if __name__ == '__main__':
29+
if __name__ == "__main__":
3030
args = parse_args()
3131
mean_L1 = calc_images_mean_L1(args.image1_path, args.image2_path)
3232
print(mean_L1)

installer/lib/installer.py

Lines changed: 26 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -141,15 +141,16 @@ def app_venv(self, path: str = None):
141141

142142
# upgrade pip in Python 3.9 environments
143143
if int(platform.python_version_tuple()[1]) == 9:
144-
145144
from plumbum import FG, local
146145

147146
pip = local[get_pip_from_venv(venv_dir)]
148-
pip[ "install", "--upgrade", "pip"] & FG
147+
pip["install", "--upgrade", "pip"] & FG
149148

150149
return venv_dir
151150

152-
def install(self, root: str = "~/invokeai-3", version: str = "latest", yes_to_all=False, find_links: Path = None) -> None:
151+
def install(
152+
self, root: str = "~/invokeai-3", version: str = "latest", yes_to_all=False, find_links: Path = None
153+
) -> None:
153154
"""
154155
Install the InvokeAI application into the given runtime path
155156
@@ -175,7 +176,7 @@ def install(self, root: str = "~/invokeai-3", version: str = "latest", yes_to_al
175176
self.instance = InvokeAiInstance(runtime=self.dest, venv=self.venv, version=version)
176177

177178
# install dependencies and the InvokeAI application
178-
(extra_index_url,optional_modules) = get_torch_source() if not yes_to_all else (None,None)
179+
(extra_index_url, optional_modules) = get_torch_source() if not yes_to_all else (None, None)
179180
self.instance.install(
180181
extra_index_url,
181182
optional_modules,
@@ -188,6 +189,7 @@ def install(self, root: str = "~/invokeai-3", version: str = "latest", yes_to_al
188189
# run through the configuration flow
189190
self.instance.configure()
190191

192+
191193
class InvokeAiInstance:
192194
"""
193195
Manages an installed instance of InvokeAI, comprising a virtual environment and a runtime directory.
@@ -196,7 +198,6 @@ class InvokeAiInstance:
196198
"""
197199

198200
def __init__(self, runtime: Path, venv: Path, version: str) -> None:
199-
200201
self.runtime = runtime
201202
self.venv = venv
202203
self.pip = get_pip_from_venv(venv)
@@ -312,7 +313,7 @@ def install_app(self, extra_index_url=None, optional_modules=None, find_links=No
312313
"install",
313314
"--require-virtualenv",
314315
"--use-pep517",
315-
str(src)+(optional_modules if optional_modules else ''),
316+
str(src) + (optional_modules if optional_modules else ""),
316317
"--find-links" if find_links is not None else None,
317318
find_links,
318319
"--extra-index-url" if extra_index_url is not None else None,
@@ -329,15 +330,15 @@ def configure(self):
329330

330331
# set sys.argv to a consistent state
331332
new_argv = [sys.argv[0]]
332-
for i in range(1,len(sys.argv)):
333+
for i in range(1, len(sys.argv)):
333334
el = sys.argv[i]
334-
if el in ['-r','--root']:
335+
if el in ["-r", "--root"]:
335336
new_argv.append(el)
336-
new_argv.append(sys.argv[i+1])
337-
elif el in ['-y','--yes','--yes-to-all']:
337+
new_argv.append(sys.argv[i + 1])
338+
elif el in ["-y", "--yes", "--yes-to-all"]:
338339
new_argv.append(el)
339340
sys.argv = new_argv
340-
341+
341342
import requests # to catch download exceptions
342343
from messages import introduction
343344

@@ -353,16 +354,16 @@ def configure(self):
353354
invokeai_configure()
354355
succeeded = True
355356
except requests.exceptions.ConnectionError as e:
356-
print(f'\nA network error was encountered during configuration and download: {str(e)}')
357+
print(f"\nA network error was encountered during configuration and download: {str(e)}")
357358
except OSError as e:
358-
print(f'\nAn OS error was encountered during configuration and download: {str(e)}')
359+
print(f"\nAn OS error was encountered during configuration and download: {str(e)}")
359360
except Exception as e:
360-
print(f'\nA problem was encountered during the configuration and download steps: {str(e)}')
361+
print(f"\nA problem was encountered during the configuration and download steps: {str(e)}")
361362
finally:
362363
if not succeeded:
363364
print('To try again, find the "invokeai" directory, run the script "invoke.sh" or "invoke.bat"')
364-
print('and choose option 7 to fix a broken install, optionally followed by option 5 to install models.')
365-
print('Alternatively you can relaunch the installer.')
365+
print("and choose option 7 to fix a broken install, optionally followed by option 5 to install models.")
366+
print("Alternatively you can relaunch the installer.")
366367

367368
def install_user_scripts(self):
368369
"""
@@ -371,11 +372,11 @@ def install_user_scripts(self):
371372

372373
ext = "bat" if OS == "Windows" else "sh"
373374

374-
#scripts = ['invoke', 'update']
375-
scripts = ['invoke']
376-
375+
# scripts = ['invoke', 'update']
376+
scripts = ["invoke"]
377+
377378
for script in scripts:
378-
src = Path(__file__).parent / '..' / "templates" / f"{script}.{ext}.in"
379+
src = Path(__file__).parent / ".." / "templates" / f"{script}.{ext}.in"
379380
dest = self.runtime / f"{script}.{ext}"
380381
shutil.copy(src, dest)
381382
os.chmod(dest, 0o0755)
@@ -420,11 +421,7 @@ def set_sys_path(venv_path: Path) -> None:
420421
# filter out any paths in sys.path that may be system- or user-wide
421422
# but leave the temporary bootstrap virtualenv as it contains packages we
422423
# temporarily need at install time
423-
sys.path = list(filter(
424-
lambda p: not p.endswith("-packages")
425-
or p.find(BOOTSTRAP_VENV_PREFIX) != -1,
426-
sys.path
427-
))
424+
sys.path = list(filter(lambda p: not p.endswith("-packages") or p.find(BOOTSTRAP_VENV_PREFIX) != -1, sys.path))
428425

429426
# determine site-packages/lib directory location for the venv
430427
lib = "Lib" if OS == "Windows" else f"lib/python{sys.version_info.major}.{sys.version_info.minor}"
@@ -433,7 +430,7 @@ def set_sys_path(venv_path: Path) -> None:
433430
sys.path.append(str(Path(venv_path, lib, "site-packages").expanduser().resolve()))
434431

435432

436-
def get_torch_source() -> (Union[str, None],str):
433+
def get_torch_source() -> (Union[str, None], str):
437434
"""
438435
Determine the extra index URL for pip to use for torch installation.
439436
This depends on the OS and the graphics accelerator in use.
@@ -461,9 +458,9 @@ def get_torch_source() -> (Union[str, None],str):
461458
elif device == "cpu":
462459
url = "https://download.pytorch.org/whl/cpu"
463460

464-
if device == 'cuda':
465-
url = 'https://download.pytorch.org/whl/cu117'
466-
optional_modules = '[xformers]'
461+
if device == "cuda":
462+
url = "https://download.pytorch.org/whl/cu117"
463+
optional_modules = "[xformers]"
467464

468465
# in all other cases, Torch wheels should be coming from PyPi as of Torch 1.13
469466

installer/lib/main.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@
4141
type=Path,
4242
default=None,
4343
)
44-
44+
4545
args = parser.parse_args()
4646

4747
inst = Installer()

installer/lib/messages.py

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -36,13 +36,15 @@
3636

3737

3838
def welcome():
39-
4039
@group()
4140
def text():
4241
if (platform_specific := _platform_specific_help()) != "":
4342
yield platform_specific
4443
yield ""
45-
yield Text.from_markup("Some of the installation steps take a long time to run. Please be patient. If the script appears to hang for more than 10 minutes, please interrupt with [i]Control-C[/] and retry.", justify="center")
44+
yield Text.from_markup(
45+
"Some of the installation steps take a long time to run. Please be patient. If the script appears to hang for more than 10 minutes, please interrupt with [i]Control-C[/] and retry.",
46+
justify="center",
47+
)
4648

4749
console.rule()
4850
print(
@@ -58,6 +60,7 @@ def text():
5860
)
5961
console.line()
6062

63+
6164
def confirm_install(dest: Path) -> bool:
6265
if dest.exists():
6366
print(f":exclamation: Directory {dest} already exists :exclamation:")
@@ -92,7 +95,6 @@ def dest_path(dest=None) -> Path:
9295
dest_confirmed = confirm_install(dest)
9396

9497
while not dest_confirmed:
95-
9698
# if the given destination already exists, the starting point for browsing is its parent directory.
9799
# the user may have made a typo, or otherwise wants to place the root dir next to an existing one.
98100
# if the destination dir does NOT exist, then the user must have changed their mind about the selection.
@@ -300,15 +302,20 @@ def introduction() -> None:
300302
)
301303
console.line(2)
302304

303-
def _platform_specific_help()->str:
305+
306+
def _platform_specific_help() -> str:
304307
if OS == "Darwin":
305-
text = Text.from_markup("""[b wheat1]macOS Users![/]\n\nPlease be sure you have the [b wheat1]Xcode command-line tools[/] installed before continuing.\nIf not, cancel with [i]Control-C[/] and follow the Xcode install instructions at [deep_sky_blue1]https://www.freecodecamp.org/news/install-xcode-command-line-tools/[/].""")
308+
text = Text.from_markup(
309+
"""[b wheat1]macOS Users![/]\n\nPlease be sure you have the [b wheat1]Xcode command-line tools[/] installed before continuing.\nIf not, cancel with [i]Control-C[/] and follow the Xcode install instructions at [deep_sky_blue1]https://www.freecodecamp.org/news/install-xcode-command-line-tools/[/]."""
310+
)
306311
elif OS == "Windows":
307-
text = Text.from_markup("""[b wheat1]Windows Users![/]\n\nBefore you start, please do the following:
312+
text = Text.from_markup(
313+
"""[b wheat1]Windows Users![/]\n\nBefore you start, please do the following:
308314
1. Double-click on the file [b wheat1]WinLongPathsEnabled.reg[/] in order to
309315
enable long path support on your system.
310316
2. Make sure you have the [b wheat1]Visual C++ core libraries[/] installed. If not, install from
311-
[deep_sky_blue1]https://learn.microsoft.com/en-US/cpp/windows/latest-supported-vc-redist?view=msvc-170[/]""")
317+
[deep_sky_blue1]https://learn.microsoft.com/en-US/cpp/windows/latest-supported-vc-redist?view=msvc-170[/]"""
318+
)
312319
else:
313320
text = ""
314321
return text

invokeai/app/api/dependencies.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -78,9 +78,7 @@ def initialize(config: InvokeAIAppConfig, event_handler_id: int, logger: Logger
7878
image_record_storage = SqliteImageRecordStorage(db_location)
7979
image_file_storage = DiskImageFileStorage(f"{output_folder}/images")
8080
names = SimpleNameService()
81-
latents = ForwardCacheLatentsStorage(
82-
DiskLatentsStorage(f"{output_folder}/latents")
83-
)
81+
latents = ForwardCacheLatentsStorage(DiskLatentsStorage(f"{output_folder}/latents"))
8482

8583
board_record_storage = SqliteBoardRecordStorage(db_location)
8684
board_image_record_storage = SqliteBoardImageRecordStorage(db_location)
@@ -125,9 +123,7 @@ def initialize(config: InvokeAIAppConfig, event_handler_id: int, logger: Logger
125123
boards=boards,
126124
board_images=board_images,
127125
queue=MemoryInvocationQueue(),
128-
graph_library=SqliteItemStorage[LibraryGraph](
129-
filename=db_location, table_name="graphs"
130-
),
126+
graph_library=SqliteItemStorage[LibraryGraph](filename=db_location, table_name="graphs"),
131127
graph_execution_manager=graph_execution_manager,
132128
processor=DefaultInvocationProcessor(),
133129
configuration=config,

invokeai/app/api/routers/app_info.py

Lines changed: 21 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
from ..dependencies import ApiDependencies
1616
from invokeai.backend.util.logging import logging
1717

18+
1819
class LogLevel(int, Enum):
1920
NotSet = logging.NOTSET
2021
Debug = logging.DEBUG
@@ -23,10 +24,12 @@ class LogLevel(int, Enum):
2324
Error = logging.ERROR
2425
Critical = logging.CRITICAL
2526

27+
2628
class Upscaler(BaseModel):
2729
upscaling_method: str = Field(description="Name of upscaling method")
2830
upscaling_models: list[str] = Field(description="List of upscaling models for this method")
29-
31+
32+
3033
app_router = APIRouter(prefix="/v1/app", tags=["app"])
3134

3235

@@ -45,64 +48,57 @@ class AppConfig(BaseModel):
4548
watermarking_methods: list[str] = Field(description="List of invisible watermark methods")
4649

4750

48-
@app_router.get(
49-
"/version", operation_id="app_version", status_code=200, response_model=AppVersion
50-
)
51+
@app_router.get("/version", operation_id="app_version", status_code=200, response_model=AppVersion)
5152
async def get_version() -> AppVersion:
5253
return AppVersion(version=__version__)
5354

5455

55-
@app_router.get(
56-
"/config", operation_id="get_config", status_code=200, response_model=AppConfig
57-
)
56+
@app_router.get("/config", operation_id="get_config", status_code=200, response_model=AppConfig)
5857
async def get_config() -> AppConfig:
59-
infill_methods = ['tile']
58+
infill_methods = ["tile"]
6059
if PatchMatch.patchmatch_available():
61-
infill_methods.append('patchmatch')
62-
60+
infill_methods.append("patchmatch")
6361

6462
upscaling_models = []
6563
for model in typing.get_args(ESRGAN_MODELS):
6664
upscaling_models.append(str(Path(model).stem))
67-
upscaler = Upscaler(
68-
upscaling_method = 'esrgan',
69-
upscaling_models = upscaling_models
70-
)
71-
65+
upscaler = Upscaler(upscaling_method="esrgan", upscaling_models=upscaling_models)
66+
7267
nsfw_methods = []
7368
if SafetyChecker.safety_checker_available():
74-
nsfw_methods.append('nsfw_checker')
69+
nsfw_methods.append("nsfw_checker")
7570

7671
watermarking_methods = []
7772
if InvisibleWatermark.invisible_watermark_available():
78-
watermarking_methods.append('invisible_watermark')
79-
73+
watermarking_methods.append("invisible_watermark")
74+
8075
return AppConfig(
8176
infill_methods=infill_methods,
8277
upscaling_methods=[upscaler],
8378
nsfw_methods=nsfw_methods,
8479
watermarking_methods=watermarking_methods,
8580
)
8681

82+
8783
@app_router.get(
8884
"/logging",
8985
operation_id="get_log_level",
90-
responses={200: {"description" : "The operation was successful"}},
91-
response_model = LogLevel,
86+
responses={200: {"description": "The operation was successful"}},
87+
response_model=LogLevel,
9288
)
93-
async def get_log_level(
94-
) -> LogLevel:
89+
async def get_log_level() -> LogLevel:
9590
"""Returns the log level"""
9691
return LogLevel(ApiDependencies.invoker.services.logger.level)
9792

93+
9894
@app_router.post(
9995
"/logging",
10096
operation_id="set_log_level",
101-
responses={200: {"description" : "The operation was successful"}},
102-
response_model = LogLevel,
97+
responses={200: {"description": "The operation was successful"}},
98+
response_model=LogLevel,
10399
)
104100
async def set_log_level(
105-
level: LogLevel = Body(description="New log verbosity level"),
101+
level: LogLevel = Body(description="New log verbosity level"),
106102
) -> LogLevel:
107103
"""Sets the log verbosity level"""
108104
ApiDependencies.invoker.services.logger.setLevel(level)

invokeai/app/api/routers/board_images.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,4 +52,3 @@ async def remove_board_image(
5252
return result
5353
except Exception as e:
5454
raise HTTPException(status_code=500, detail="Failed to update board")
55-

0 commit comments

Comments
 (0)