-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions.py
More file actions
64 lines (56 loc) · 2.19 KB
/
functions.py
File metadata and controls
64 lines (56 loc) · 2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
from diffusers import EulerAncestralDiscreteScheduler
from diffusers import StableDiffusionXLPipeline
from transformers import BertTokenizer , utils
from rich import print
import torch , uuid , os
class Utils:
def generate_filename(self):
return f'{uuid.uuid4()}.png'
class Tokenizer:
tokenzier_repo_url = 'bert-base-uncased'
def tokenize_prompt(self , prompt:str , length:int):
tokenizer = BertTokenizer.from_pretrained(self.tokenzier_repo_url)
tokens = tokenizer.tokenize(prompt)
if len(tokens) > length:
print(f"Prompt too long. Truncating from {len(tokens)} tokens to {length} tokens.")
tokens = tokens[:length]
return tokenizer.convert_tokens_to_string(tokens)
class Pipeline:
repo_url:str
pipe:StableDiffusionXLPipeline
def __init__(self , repo_url:str) -> None:
# utils.move_cache()
torch.backends.cudnn.benchmark = True
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cuda.matmul.allow_fp16_reduced_precision_reduction = True
self.repo_url = repo_url
def pipeline(self):
self.pipe = StableDiffusionXLPipeline.from_pretrained(
self.repo_url ,
torch_dtype=torch.float16 ,
use_safetensors=True,
device_map="balanced"
)
self.pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(self.pipe.scheduler.config)
self.pipe.enable_xformers_memory_efficient_attention()
class Generator:
def generate(self , diffuser:Pipeline , propmt:str , negative:str , dimensions:tuple , guidance:int , steps:int):
torch.cuda.empty_cache()
result = diffuser.pipe(
prompt=propmt,
negative_prompt=negative,
width=dimensions[0],
heigth=dimensions[1],
guidance_scale=guidance,
num_inference_steps=steps,
num_images_per_prompt=1
).images[0]
filename = os.path.join('output' , Utils().generate_filename())
try:
os.mkdir('output')
except Exception:
...
finally:
result.save(filename)
torch.cuda.empty_cache()
return filename