Skip to content

Commit

Permalink
Apply black
Browse files Browse the repository at this point in the history
  • Loading branch information
lillekemiker committed Jul 26, 2023
1 parent 0b002b8 commit f24f053
Show file tree
Hide file tree
Showing 141 changed files with 6,136 additions and 5,510 deletions.
6 changes: 3 additions & 3 deletions .dev_scripts/diff_images.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,13 @@ def calc_images_mean_L1(image1_path, image2_path):

def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('image1_path')
parser.add_argument('image2_path')
parser.add_argument("image1_path")
parser.add_argument("image2_path")
args = parser.parse_args()
return args


if __name__ == '__main__':
if __name__ == "__main__":
args = parse_args()
mean_L1 = calc_images_mean_L1(args.image1_path, args.image2_path)
print(mean_L1)
79 changes: 47 additions & 32 deletions installer/lib/installer.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,9 @@ def __init__(self) -> None:
self.reqs = INSTALLER_REQS
self.preflight()
if os.getenv("VIRTUAL_ENV") is not None:
print("A virtual environment is already activated. Please 'deactivate' before installation.")
print(
"A virtual environment is already activated. Please 'deactivate' before installation."
)
sys.exit(-1)
self.bootstrap()

Expand Down Expand Up @@ -141,15 +143,20 @@ def app_venv(self, path: str = None):

# upgrade pip in Python 3.9 environments
if int(platform.python_version_tuple()[1]) == 9:

from plumbum import FG, local

pip = local[get_pip_from_venv(venv_dir)]
pip[ "install", "--upgrade", "pip"] & FG
pip["install", "--upgrade", "pip"] & FG

return venv_dir

def install(self, root: str = "~/invokeai-3", version: str = "latest", yes_to_all=False, find_links: Path = None) -> None:
def install(
self,
root: str = "~/invokeai-3",
version: str = "latest",
yes_to_all=False,
find_links: Path = None,
) -> None:
"""
Install the InvokeAI application into the given runtime path
Expand All @@ -175,7 +182,7 @@ def install(self, root: str = "~/invokeai-3", version: str = "latest", yes_to_al
self.instance = InvokeAiInstance(runtime=self.dest, venv=self.venv, version=version)

# install dependencies and the InvokeAI application
(extra_index_url,optional_modules) = get_torch_source() if not yes_to_all else (None,None)
(extra_index_url, optional_modules) = get_torch_source() if not yes_to_all else (None, None)
self.instance.install(
extra_index_url,
optional_modules,
Expand All @@ -188,6 +195,7 @@ def install(self, root: str = "~/invokeai-3", version: str = "latest", yes_to_al
# run through the configuration flow
self.instance.configure()


class InvokeAiInstance:
"""
Manages an installed instance of InvokeAI, comprising a virtual environment and a runtime directory.
Expand All @@ -196,7 +204,6 @@ class InvokeAiInstance:
"""

def __init__(self, runtime: Path, venv: Path, version: str) -> None:

self.runtime = runtime
self.venv = venv
self.pip = get_pip_from_venv(venv)
Expand Down Expand Up @@ -312,7 +319,7 @@ def install_app(self, extra_index_url=None, optional_modules=None, find_links=No
"install",
"--require-virtualenv",
"--use-pep517",
str(src)+(optional_modules if optional_modules else ''),
str(src) + (optional_modules if optional_modules else ""),
"--find-links" if find_links is not None else None,
find_links,
"--extra-index-url" if extra_index_url is not None else None,
Expand All @@ -329,15 +336,15 @@ def configure(self):

# set sys.argv to a consistent state
new_argv = [sys.argv[0]]
for i in range(1,len(sys.argv)):
for i in range(1, len(sys.argv)):
el = sys.argv[i]
if el in ['-r','--root']:
if el in ["-r", "--root"]:
new_argv.append(el)
new_argv.append(sys.argv[i+1])
elif el in ['-y','--yes','--yes-to-all']:
new_argv.append(sys.argv[i + 1])
elif el in ["-y", "--yes", "--yes-to-all"]:
new_argv.append(el)
sys.argv = new_argv

import requests # to catch download exceptions
from messages import introduction

Expand All @@ -353,16 +360,22 @@ def configure(self):
invokeai_configure()
succeeded = True
except requests.exceptions.ConnectionError as e:
print(f'\nA network error was encountered during configuration and download: {str(e)}')
print(f"\nA network error was encountered during configuration and download: {str(e)}")
except OSError as e:
print(f'\nAn OS error was encountered during configuration and download: {str(e)}')
print(f"\nAn OS error was encountered during configuration and download: {str(e)}")
except Exception as e:
print(f'\nA problem was encountered during the configuration and download steps: {str(e)}')
print(
f"\nA problem was encountered during the configuration and download steps: {str(e)}"
)
finally:
if not succeeded:
print('To try again, find the "invokeai" directory, run the script "invoke.sh" or "invoke.bat"')
print('and choose option 7 to fix a broken install, optionally followed by option 5 to install models.')
print('Alternatively you can relaunch the installer.')
print(
'To try again, find the "invokeai" directory, run the script "invoke.sh" or "invoke.bat"'
)
print(
"and choose option 7 to fix a broken install, optionally followed by option 5 to install models."
)
print("Alternatively you can relaunch the installer.")

def install_user_scripts(self):
"""
Expand All @@ -371,11 +384,11 @@ def install_user_scripts(self):

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

#scripts = ['invoke', 'update']
scripts = ['invoke']
# scripts = ['invoke', 'update']
scripts = ["invoke"]

for script in scripts:
src = Path(__file__).parent / '..' / "templates" / f"{script}.{ext}.in"
src = Path(__file__).parent / ".." / "templates" / f"{script}.{ext}.in"
dest = self.runtime / f"{script}.{ext}"
shutil.copy(src, dest)
os.chmod(dest, 0o0755)
Expand Down Expand Up @@ -420,20 +433,22 @@ def set_sys_path(venv_path: Path) -> None:
# filter out any paths in sys.path that may be system- or user-wide
# but leave the temporary bootstrap virtualenv as it contains packages we
# temporarily need at install time
sys.path = list(filter(
lambda p: not p.endswith("-packages")
or p.find(BOOTSTRAP_VENV_PREFIX) != -1,
sys.path
))
sys.path = list(
filter(
lambda p: not p.endswith("-packages") or p.find(BOOTSTRAP_VENV_PREFIX) != -1, sys.path
)
)

# determine site-packages/lib directory location for the venv
lib = "Lib" if OS == "Windows" else f"lib/python{sys.version_info.major}.{sys.version_info.minor}"
lib = (
"Lib" if OS == "Windows" else f"lib/python{sys.version_info.major}.{sys.version_info.minor}"
)

# add the site-packages location to the venv
sys.path.append(str(Path(venv_path, lib, "site-packages").expanduser().resolve()))


def get_torch_source() -> (Union[str, None],str):
def get_torch_source() -> (Union[str, None], str):
"""
Determine the extra index URL for pip to use for torch installation.
This depends on the OS and the graphics accelerator in use.
Expand Down Expand Up @@ -461,9 +476,9 @@ def get_torch_source() -> (Union[str, None],str):
elif device == "cpu":
url = "https://download.pytorch.org/whl/cpu"

if device == 'cuda':
url = 'https://download.pytorch.org/whl/cu117'
optional_modules = '[xformers]'
if device == "cuda":
url = "https://download.pytorch.org/whl/cu117"
optional_modules = "[xformers]"

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

Expand Down
2 changes: 1 addition & 1 deletion installer/lib/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
type=Path,
default=None,
)

args = parser.parse_args()

inst = Installer()
Expand Down
48 changes: 35 additions & 13 deletions installer/lib/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,15 @@


def welcome():

@group()
def text():
if (platform_specific := _platform_specific_help()) != "":
yield platform_specific
yield ""
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")
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",
)

console.rule()
print(
Expand All @@ -58,6 +60,7 @@ def text():
)
console.line()


def confirm_install(dest: Path) -> bool:
if dest.exists():
print(f":exclamation: Directory {dest} already exists :exclamation:")
Expand All @@ -67,7 +70,9 @@ def confirm_install(dest: Path) -> bool:
)
else:
print(f"InvokeAI will be installed in {dest}")
dest_confirmed = not Confirm.ask(f"Would you like to pick a different location?", default=False)
dest_confirmed = not Confirm.ask(
f"Would you like to pick a different location?", default=False
)
console.line()

return dest_confirmed
Expand All @@ -92,12 +97,13 @@ def dest_path(dest=None) -> Path:
dest_confirmed = confirm_install(dest)

while not dest_confirmed:

# if the given destination already exists, the starting point for browsing is its parent directory.
# the user may have made a typo, or otherwise wants to place the root dir next to an existing one.
# if the destination dir does NOT exist, then the user must have changed their mind about the selection.
# since we can't read their mind, start browsing at Path.cwd().
browse_start = (prev_dest.parent if prev_dest.exists() else Path.cwd()).expanduser().resolve()
browse_start = (
(prev_dest.parent if prev_dest.exists() else Path.cwd()).expanduser().resolve()
)

path_completer = PathCompleter(
only_directories=True,
Expand All @@ -107,7 +113,9 @@ def dest_path(dest=None) -> Path:
)

console.line()
print(f"[orange3]Please select the destination directory for the installation:[/] \[{browse_start}]: ")
print(
f"[orange3]Please select the destination directory for the installation:[/] \[{browse_start}]: "
)
selected = prompt(
f">>> ",
complete_in_thread=True,
Expand Down Expand Up @@ -187,7 +195,9 @@ def graphical_accelerator():
# future CoreML?

if len(options) == 1:
print(f'Your platform [gold1]{OS}-{ARCH}[/] only supports the "{options[0][1]}" driver. Proceeding with that.')
print(
f'Your platform [gold1]{OS}-{ARCH}[/] only supports the "{options[0][1]}" driver. Proceeding with that.'
)
return options[0][1]

# "I don't know" is always added the last option
Expand All @@ -211,7 +221,12 @@ def graphical_accelerator():
"",
"Please select the type of GPU installed in your computer.",
Panel(
"\n".join([f"[dark_goldenrod b i]{i}[/] [dark_red]🢒[/]{opt[0]}" for (i, opt) in options.items()]),
"\n".join(
[
f"[dark_goldenrod b i]{i}[/] [dark_red]🢒[/]{opt[0]}"
for (i, opt) in options.items()
]
),
box=box.MINIMAL,
),
),
Expand Down Expand Up @@ -251,7 +266,9 @@ def windows_long_paths_registry() -> None:
Display a message about applying the Windows long paths registry fix
"""

with open(str(Path(__file__).parent / "WinLongPathsEnabled.reg"), "r", encoding="utf-16le") as code:
with open(
str(Path(__file__).parent / "WinLongPathsEnabled.reg"), "r", encoding="utf-16le"
) as code:
syntax = Syntax(code.read(), line_numbers=True)

console.print(
Expand Down Expand Up @@ -300,15 +317,20 @@ def introduction() -> None:
)
console.line(2)

def _platform_specific_help()->str:

def _platform_specific_help() -> str:
if OS == "Darwin":
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/[/].""")
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/[/]."""
)
elif OS == "Windows":
text = Text.from_markup("""[b wheat1]Windows Users![/]\n\nBefore you start, please do the following:
text = Text.from_markup(
"""[b wheat1]Windows Users![/]\n\nBefore you start, please do the following:
1. Double-click on the file [b wheat1]WinLongPathsEnabled.reg[/] in order to
enable long path support on your system.
2. Make sure you have the [b wheat1]Visual C++ core libraries[/] installed. If not, install from
[deep_sky_blue1]https://learn.microsoft.com/en-US/cpp/windows/latest-supported-vc-redist?view=msvc-170[/]""")
[deep_sky_blue1]https://learn.microsoft.com/en-US/cpp/windows/latest-supported-vc-redist?view=msvc-170[/]"""
)
else:
text = ""
return text
4 changes: 1 addition & 3 deletions invokeai/app/api/dependencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,7 @@ def initialize(config: InvokeAIAppConfig, event_handler_id: int, logger: Logger
image_record_storage = SqliteImageRecordStorage(db_location)
image_file_storage = DiskImageFileStorage(f"{output_folder}/images")
names = SimpleNameService()
latents = ForwardCacheLatentsStorage(
DiskLatentsStorage(f"{output_folder}/latents")
)
latents = ForwardCacheLatentsStorage(DiskLatentsStorage(f"{output_folder}/latents"))

board_record_storage = SqliteBoardRecordStorage(db_location)
board_image_record_storage = SqliteBoardImageRecordStorage(db_location)
Expand Down

0 comments on commit f24f053

Please sign in to comment.