InvokeAI/ldm/invoke/patchmatch.py
Lincoln Stein cca8d14c79
defer patchmatch loading (#2039)
* defer patchmatch loading

Because of the way that patchmatch was loaded early at import time, it
was impossible to turn off the attempted loading with --no-patchmatch.

In addition, the patchmatch loading messages appear early on during
initialization, interfering with ability to print out the version
cleanly when --version provided to invoke script.

This commit creates a thin wrapper class for patch_match that is only
loaded when needed, solving both problems.

* create a singleton patchmatch object for use in inpainting

This creates a thin wrapper to patchmatch which loads the module
on demand, respecting the global "trypatchmatch" option.

* address 2d round of issues in PR 2039 comments

* Patchmatch->PatchMatch and misc cleanup
2022-12-20 15:32:35 -08:00

45 lines
1.3 KiB
Python

'''
This module defines a singleton object, "patchmatch" that
wraps the actual patchmatch object. It respects the global
"try_patchmatch" attribute, so that patchmatch loading can
be suppressed or deferred
'''
from ldm.invoke.globals import Globals
import numpy as np
class PatchMatch:
'''
Thin class wrapper around the patchmatch function.
'''
patch_match = None
tried_load:bool = False
def __init__(self):
super().__init__()
@classmethod
def _load_patch_match(self):
if self.tried_load:
return
if Globals.try_patchmatch:
from patchmatch import patch_match as pm
if pm.patchmatch_available:
print('>> Patchmatch initialized')
else:
print('>> Patchmatch not loaded (nonfatal)')
self.patch_match = pm
else:
print('>> Patchmatch loading disabled')
self.tried_load = True
@classmethod
def patchmatch_available(self)->bool:
self._load_patch_match()
return self.patch_match and self.patch_match.patchmatch_available
@classmethod
def inpaint(self,*args,**kwargs)->np.ndarray:
if self.patchmatch_available():
return self.patch_match.inpaint(*args,**kwargs)