Skip to content

Conversation

sourcery-ai[bot]
Copy link

@sourcery-ai sourcery-ai bot commented Oct 12, 2022

Branch main refactored by Sourcery.

If you're happy with these changes, merge this Pull Request using the Squash and merge strategy.

See our documentation here.

Run Sourcery locally

Reduce the feedback loop during development by using the Sourcery editor plugin:

Review changes via command line

To manually merge these changes, make sure you're on the main branch, then run:

git fetch origin sourcery/main
git merge --ff-only FETCH_HEAD
git reset HEAD^

Help us improve this pull request!

@sourcery-ai sourcery-ai bot requested a review from GraGroo October 12, 2022 17:54
Copy link
Author

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Due to GitHub API limits, only the first 60 comments can be shown.

Comment on lines -102 to +104
default=list(),
default=[],
)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function get_parser refactored with the following changes:

Comment on lines -258 to +259
self.dataset_configs = dict()
self.dataset_configs = {}
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function DataModuleFromConfig.__init__ refactored with the following changes:

Comment on lines -286 to +291
self.datasets = dict(
(k, instantiate_from_config(self.dataset_configs[k]))
self.datasets = {
k: instantiate_from_config(self.dataset_configs[k])
for k in self.dataset_configs
)
}

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function DataModuleFromConfig.setup refactored with the following changes:

Comment on lines -306 to +308
shuffle=False if is_iterable_dataset else True,
shuffle=not is_iterable_dataset,
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function DataModuleFromConfig._train_dataloader refactored with the following changes:

Comment on lines -388 to +420
if 'callbacks' in self.lightning_config:
if (
'metrics_over_trainsteps_checkpoint'
in self.lightning_config['callbacks']
):
os.makedirs(
os.path.join(self.ckptdir, 'trainstep_checkpoints'),
exist_ok=True,
)
if 'callbacks' in self.lightning_config and (
'metrics_over_trainsteps_checkpoint'
in self.lightning_config['callbacks']
):
os.makedirs(
os.path.join(self.ckptdir, 'trainstep_checkpoints'),
exist_ok=True,
)
print('Project config')
print(OmegaConf.to_yaml(self.config))
OmegaConf.save(
self.config,
os.path.join(self.cfgdir, '{}-project.yaml'.format(self.now)),
self.config, os.path.join(self.cfgdir, f'{self.now}-project.yaml')
)


print('Lightning config')
print(OmegaConf.to_yaml(self.lightning_config))
OmegaConf.save(
OmegaConf.create({'lightning': self.lightning_config}),
os.path.join(
self.cfgdir, '{}-lightning.yaml'.format(self.now)
),
os.path.join(self.cfgdir, f'{self.now}-lightning.yaml'),
)

else:
# ModelCheckpoint callback created log directory --- remove it
if not self.resume and os.path.exists(self.logdir):
dst, name = os.path.split(self.logdir)
dst = os.path.join(dst, 'child_runs', name)
os.makedirs(os.path.split(dst)[0], exist_ok=True)
try:
os.rename(self.logdir, dst)
except FileNotFoundError:
pass

elif not self.resume and os.path.exists(self.logdir):
dst, name = os.path.split(self.logdir)
dst = os.path.join(dst, 'child_runs', name)
os.makedirs(os.path.split(dst)[0], exist_ok=True)
try:
os.rename(self.logdir, dst)
except FileNotFoundError:
pass
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function SetupCallback.on_pretrain_routine_start refactored with the following changes:

This removes the following comments ( why? ):

# ModelCheckpoint callback created log directory --- remove it

additional_allowed_origins = (
opt.cors if opt.cors else []
) # additional CORS allowed origins
additional_allowed_origins = opt.cors or []
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 55-57 refactored with the following changes:

This removes the following comments ( why? ):

# additional CORS allowed origins

Comment on lines -93 to +92
logger = True if verbose else False
engineio_logger = True if verbose else False
logger = bool(verbose)
engineio_logger = bool(verbose)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 93-136 refactored with the following changes:

This removes the following comments ( why? ):

# coreformer.process(self, image, strength, device, seed=None, fidelity=0.75)

Comment on lines -188 to +184
print(f">> System config requested")
print(">> System config requested")
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function handle_request_capabilities refactored with the following changes:

Comment on lines -198 to +194
print(f">> Latest images requested")
print(">> Latest images requested")
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function handle_request_images refactored with the following changes:

Comment on lines -392 to +388
print(f">> Cancel processing requested")
print(">> Cancel processing requested")
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function handle_cancel refactored with the following changes:

Comment on lines -523 to +519
rfc_dict["postprocessing"] = postprocessing if len(postprocessing) > 0 else None
rfc_dict["postprocessing"] = postprocessing or None
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function parameters_to_generated_image_metadata refactored with the following changes:

Comment on lines -585 to -602
if "image" in metadata:
if "seed" in metadata["image"]:
seed = metadata["image"]["seed"]
if "image" in metadata and "seed" in metadata["image"]:
seed = metadata["image"]["seed"]

filename = f"{prefix}.{seed}"

if step_index:
filename += f".{step_index}"
if postprocessing:
filename += f".postprocessed"
filename += ".postprocessed"

filename += ".png"

path = pngwriter.save_image_and_prompt_to_png(
return pngwriter.save_image_and_prompt_to_png(
image=image, dream_prompt=command, metadata=metadata, name=filename
)

return path
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function save_image refactored with the following changes:

"""

switches = list()
switches = []
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function parameters_to_command refactored with the following changes:

Comment on lines -36 to +40
if not seed >= 0:
if seed < 0:
return False

# Weight must be between 0 and 1
if not (weight >= 0 and weight <= 1):
if weight < 0 or weight > 1:
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function parse_seed_weights refactored with the following changes:

  • Simplify logical expression using De Morgan identities [×2] (de-morgan)

hires_fix = False,
**args,
): # eat up additional cruft
): # eat up additional cruft
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Generate.prompt2image refactored with the following changes:

Comment on lines -85 to -89
interval = 0
for cl in self.cum_cycles[1:]:
for interval, cl in enumerate(self.cum_cycles[1:]):
if n <= cl:
return interval
interval += 1
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function LambdaWarmUpCosineScheduler2.find_in_interval refactored with the following changes:

Comment on lines -94 to -105
if self.verbosity_interval > 0:
if n % self.verbosity_interval == 0:
print(
f'current step: {n}, recent lr-multiplier: {self.last_f}, '
f'current cycle {cycle}'
)
if self.verbosity_interval > 0 and n % self.verbosity_interval == 0:
print(
f'current step: {n}, recent lr-multiplier: {self.last_f}, '
f'current cycle {cycle}'
)
if n < self.lr_warm_up_steps[cycle]:
f = (
self.f_max[cycle] - self.f_start[cycle]
) / self.lr_warm_up_steps[cycle] * n + self.f_start[cycle]
self.last_f = f
return f
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function LambdaWarmUpCosineScheduler2.schedule refactored with the following changes:

Comment on lines -125 to +135
if self.verbosity_interval > 0:
if n % self.verbosity_interval == 0:
print(
f'current step: {n}, recent lr-multiplier: {self.last_f}, '
f'current cycle {cycle}'
)
if self.verbosity_interval > 0 and n % self.verbosity_interval == 0:
print(
f'current step: {n}, recent lr-multiplier: {self.last_f}, '
f'current cycle {cycle}'
)

if n < self.lr_warm_up_steps[cycle]:
f = (
self.f_max[cycle] - self.f_start[cycle]
) / self.lr_warm_up_steps[cycle] * n + self.f_start[cycle]
self.last_f = f
return f
else:
f = self.f_min[cycle] + (self.f_max[cycle] - self.f_min[cycle]) * (
self.cycle_lengths[cycle] - n
) / (self.cycle_lengths[cycle])
self.last_f = f
return f

self.last_f = f
return f
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function LambdaLinearScheduler.schedule refactored with the following changes:

Comment on lines -12 to +15
print(f'>> The ldm.simplet2i module is deprecated. Use ldm.generate instead. It is a drop-in replacement.')
print(
'>> The ldm.simplet2i module is deprecated. Use ldm.generate instead. It is a drop-in replacement.'
)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function T2I.__init__ refactored with the following changes:

# xc a list of captions to plot
b = len(xc)
txts = list()
txts = []
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function log_txt_as_img refactored with the following changes:

Comment on lines -45 to +49
if not isinstance(x, torch.Tensor):
return False
return (len(x.shape) == 4) and (x.shape[1] > 3)
return (
(len(x.shape) == 4) and (x.shape[1] > 3)
if isinstance(x, torch.Tensor)
else False
)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ismap refactored with the following changes:

Comment on lines -51 to +57
if not isinstance(x, torch.Tensor):
return False
return (len(x.shape) == 4) and (x.shape[1] == 3 or x.shape[1] == 1)
return (
len(x.shape) == 4 and x.shape[1] in [3, 1]
if isinstance(x, torch.Tensor)
else False
)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function isimage refactored with the following changes:

Comment on lines -107 to +111
if idx_to_fn:
res = func(data, worker_id=idx)
else:
res = func(data)
res = func(data, worker_id=idx) if idx_to_fn else func(data)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _do_parallel_data_prefetch refactored with the following changes:

Comment on lines -132 to +137
f'WARNING:"data" argument passed to parallel_data_prefetch is a dict: Using only its values and disregarding keys.'
'WARNING:"data" argument passed to parallel_data_prefetch is a dict: Using only its values and disregarding keys.'
)

data = list(data.values())
if target_data_type == 'ndarray':
data = np.asarray(data)
else:
data = list(data)
data = np.asarray(data) if target_data_type == 'ndarray' else list(data)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function parallel_data_prefetch refactored with the following changes:

This removes the following comments ( why? ):

# order outputs

with open(path_to_yaml) as f:
di2s = yaml.load(f)
return dict((v, k) for k, v in di2s.items())
return {v: k for k, v in di2s.items()}
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function synset2idx refactored with the following changes:

Comment on lines -43 to +46
example = dict((k, self.labels[k][i]) for k in self.labels)
example = {k: self.labels[k][i] for k in self.labels}
image = Image.open(example['file_path_'])
if not image.mode == 'RGB':
if image.mode != 'RGB':
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function LSUNBase.__getitem__ refactored with the following changes:

Comment on lines -156 to +158
example = {}
image = Image.open(self.image_paths[i % self.num_images])

if not image.mode == 'RGB':
if image.mode != 'RGB':
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function PersonalizedBase.__getitem__ refactored with the following changes:

Comment on lines -129 to +131
example = {}
image = Image.open(self.image_paths[i % self.num_images])

if not image.mode == 'RGB':
if image.mode != 'RGB':
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function PersonalizedBase.__getitem__ refactored with the following changes:

Comment on lines -129 to -137
# if no optionals or positionals are available, usage is just prog
elif usage is None and not actions:
elif not actions:
usage = 'invoke>'
elif usage is None:
else:
prog='invoke>'
# build full usage string
action_usage = self._format_actions_usage(actions, groups) # NEW
usage = ' '.join([s for s in [prog, action_usage] if s])
# omit the long line wrapping code
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ArgFormatter._format_usage refactored with the following changes:

This removes the following comments ( why? ):

# if no optionals or positionals are available, usage is just prog
# omit the long line wrapping code

Comment on lines -190 to +188
switches[0] = switches[0][: len(switches[0]) - 1]
switches[0] = switches[0][:-1]
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Args.parse_cmd refactored with the following changes:

@sourcery-ai
Copy link
Author

sourcery-ai bot commented Oct 12, 2022

Sourcery Code Quality Report

✅  Merging this PR will increase code quality in the affected files by 0.33%.

Quality metrics Before After Change
Complexity 18.38 😞 17.85 🙂 -0.53 👍
Method Length 101.18 🙂 100.37 🙂 -0.81 👍
Working memory 10.76 😞 10.67 😞 -0.09 👍
Quality 51.19% 🙂 51.52% 🙂 0.33% 👍
Other metrics Before After Change
Lines 21031 20815 -216
Changed files Quality Before Quality After Quality Change
main.py 65.85% 🙂 66.40% 🙂 0.55% 👍
.dev_scripts/diff_images.py 93.29% ⭐ 94.52% ⭐ 1.23% 👍
backend/invoke_ai_web_server.py 39.28% 😞 39.57% 😞 0.29% 👍
backend/server.py 48.05% 😞 48.29% 😞 0.24% 👍
backend/modules/parameters.py 32.85% 😞 32.92% 😞 0.07% 👍
backend/modules/parse_seed_weights.py 62.16% 🙂 62.42% 🙂 0.26% 👍
ldm/generate.py 50.70% 🙂 50.91% 🙂 0.21% 👍
ldm/lr_scheduler.py 66.66% 🙂 69.17% 🙂 2.51% 👍
ldm/simplet2i.py 98.17% ⭐ 98.33% ⭐ 0.16% 👍
ldm/util.py 49.75% 😞 48.97% 😞 -0.78% 👎
ldm/data/imagenet.py 55.13% 🙂 55.99% 🙂 0.86% 👍
ldm/data/lsun.py 73.20% 🙂 73.39% 🙂 0.19% 👍
ldm/data/personalized.py 50.44% 🙂 51.54% 🙂 1.10% 👍
ldm/data/personalized_style.py 53.74% 🙂 54.94% 🙂 1.20% 👍
ldm/invoke/args.py 59.35% 🙂 60.06% 🙂 0.71% 👍
ldm/invoke/conditioning.py 57.48% 🙂 57.52% 🙂 0.04% 👍
ldm/invoke/devices.py 88.43% ⭐ 87.59% ⭐ -0.84% 👎
ldm/invoke/image_util.py 63.03% 🙂 63.46% 🙂 0.43% 👍
ldm/invoke/log.py 77.15% ⭐ 78.27% ⭐ 1.12% 👍
ldm/invoke/readline.py 70.32% 🙂 70.24% 🙂 -0.08% 👎
ldm/invoke/server.py 21.80% ⛔ 21.79% ⛔ -0.01% 👎
ldm/invoke/generator/base.py 60.86% 🙂 60.86% 🙂 0.00%
ldm/invoke/generator/embiggen.py 4.41% ⛔ 4.47% ⛔ 0.06% 👍
ldm/invoke/generator/inpaint.py 63.32% 🙂 63.40% 🙂 0.08% 👍
ldm/invoke/generator/txt2img2img.py 55.45% 🙂 55.45% 🙂 0.00%
ldm/invoke/restoration/codeformer.py 43.25% 😞 43.23% 😞 -0.02% 👎
ldm/invoke/restoration/codeformer_arch.py 56.89% 🙂 57.35% 🙂 0.46% 👍
ldm/invoke/restoration/gfpgan.py 59.80% 🙂 59.82% 🙂 0.02% 👍
ldm/invoke/restoration/outcrop.py 77.35% ⭐ 77.35% ⭐ 0.00%
ldm/invoke/restoration/outpaint.py 51.52% 🙂 51.52% 🙂 0.00%
ldm/invoke/restoration/realesrgan.py 64.27% 🙂 63.26% 🙂 -1.01% 👎
ldm/invoke/restoration/vqgan_arch.py 59.93% 🙂 59.97% 🙂 0.04% 👍
ldm/models/autoencoder.py 70.04% 🙂 69.36% 🙂 -0.68% 👎
ldm/models/diffusion/classifier.py 68.07% 🙂 68.26% 🙂 0.19% 👍
ldm/models/diffusion/ddpm.py 43.27% 😞 44.61% 😞 1.34% 👍
ldm/models/diffusion/ksampler.py 66.23% 🙂 66.01% 🙂 -0.22% 👎
ldm/models/diffusion/sampler.py 48.65% 😞 47.81% 😞 -0.84% 👎
ldm/modules/attention.py 75.07% ⭐ 75.23% ⭐ 0.16% 👍
ldm/modules/ema.py 70.87% 🙂 70.95% 🙂 0.08% 👍
ldm/modules/embedding_manager.py 62.38% 🙂 61.98% 🙂 -0.40% 👎
ldm/modules/x_transformer.py 48.30% 😞 48.73% 😞 0.43% 👍
ldm/modules/diffusionmodules/model.py 50.28% 🙂 50.40% 🙂 0.12% 👍
ldm/modules/diffusionmodules/openaimodel.py 44.42% 😞 44.40% 😞 -0.02% 👎
ldm/modules/diffusionmodules/util.py 75.95% ⭐ 75.85% ⭐ -0.10% 👎
ldm/modules/distributions/distributions.py 78.05% ⭐ 80.27% ⭐ 2.22% 👍
ldm/modules/encoders/modules.py 62.27% 🙂 61.34% 🙂 -0.93% 👎
ldm/modules/image_degradation/bsrgan.py 47.95% 😞 50.89% 🙂 2.94% 👍
ldm/modules/image_degradation/bsrgan_light.py 53.78% 🙂 54.15% 🙂 0.37% 👍
ldm/modules/image_degradation/utils_image.py 60.04% 🙂 60.20% 🙂 0.16% 👍
ldm/modules/losses/contperceptual.py 35.04% 😞 35.39% 😞 0.35% 👍
ldm/modules/losses/vqperceptual.py 43.43% 😞 44.01% 😞 0.58% 👍
notebooks/notebook_helpers.py 52.41% 🙂 53.92% 🙂 1.51% 👍
scripts/invoke.py 26.60% 😞 26.10% 😞 -0.50% 👎
scripts/merge_embeddings.py 54.93% 🙂 51.90% 🙂 -3.03% 👎
scripts/orig_scripts/img2img.py 32.42% 😞 32.54% 😞 0.12% 👍
scripts/orig_scripts/knn2img.py 41.94% 😞 42.96% 😞 1.02% 👍
scripts/orig_scripts/sample_diffusion.py 54.87% 🙂 54.66% 🙂 -0.21% 👎
scripts/orig_scripts/train_searcher.py 48.98% 😞 49.53% 😞 0.55% 👍
scripts/orig_scripts/txt2img.py 17.46% ⛔ 18.79% ⛔ 1.33% 👍
server/models.py 69.08% 🙂 68.94% 🙂 -0.14% 👎
server/services.py 65.85% 🙂 67.27% 🙂 1.42% 👍
server/views.py 88.63% ⭐ 88.57% ⭐ -0.06% 👎

Here are some functions in these files that still need a tune-up:

File Function Complexity Length Working Memory Quality Recommendation
ldm/invoke/generator/embiggen.py Embiggen.get_make_image 279 ⛔ 2101 ⛔ 0.00% ⛔ Refactor to reduce nesting. Try splitting into smaller methods
scripts/invoke.py main_loop 114 ⛔ 1086 ⛔ 0.11% ⛔ Refactor to reduce nesting. Try splitting into smaller methods
ldm/modules/diffusionmodules/openaimodel.py UNetModel.__init__ 77 ⛔ 832 ⛔ 36 ⛔ 1.01% ⛔ Refactor to reduce nesting. Try splitting into smaller methods. Extract out complex expressions
ldm/generate.py Generate.prompt2image 42 ⛔ 700 ⛔ 41 ⛔ 5.18% ⛔ Refactor to reduce nesting. Try splitting into smaller methods. Extract out complex expressions
scripts/orig_scripts/txt2img.py main 42 ⛔ 1149 ⛔ 22 ⛔ 8.01% ⛔ Refactor to reduce nesting. Try splitting into smaller methods. Extract out complex expressions

Legend and Explanation

The emojis denote the absolute quality of the code:

  • ⭐ excellent
  • 🙂 good
  • 😞 poor
  • ⛔ very poor

The 👍 and 👎 indicate whether the quality has improved or gotten worse with this pull request.


Please see our documentation here for details on how these metrics are calculated.

We are actively working on this report - lots more documentation and extra metrics to come!

Help us improve this quality report!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

0 participants