Commit
·
5b3b260
1
Parent(s):
1fd3a94
Create script.py
Browse files
script.py
ADDED
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import sys
|
2 |
+
import subprocess
|
3 |
+
from safetensors.torch import load_file
|
4 |
+
from diffusers import AutoPipelineForText2Image
|
5 |
+
import torch
|
6 |
+
import re
|
7 |
+
|
8 |
+
def do_train(script_args):
|
9 |
+
# Pass all arguments to script.py
|
10 |
+
subprocess.run(['python', 'script.py'] + script_args)
|
11 |
+
|
12 |
+
def do_inference(dataset_name, output_dir, num_tokens):
|
13 |
+
dataset = load_dataset(dataset_name)
|
14 |
+
pipe = AutoPipelineForText2Image.from_pretrained(
|
15 |
+
"stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
|
16 |
+
)
|
17 |
+
pipe = pipe.to("cuda")
|
18 |
+
pipe.load_lora_weights(f'{output_dir}/pytorch_lora_weights.safetensors')
|
19 |
+
|
20 |
+
prompts = dataset["train"]["prompt"]
|
21 |
+
card_string = ''
|
22 |
+
if(num_tokens > 0):
|
23 |
+
tokens_sequence = ''.join(f'<s{i}>' for i in range(num_tokens))
|
24 |
+
tokens_list = tokens_sequence.split('>')
|
25 |
+
state_dict = load_file(f"{output_dir}/embeddings.safetensors")
|
26 |
+
pipeline.load_textual_inversion(state_dict["clip_l"], token=tokens_list, text_encoder=pipeline.text_encoder, tokenizer=pipeline.tokenizer)
|
27 |
+
pipeline.load_textual_inversion(state_dict["clip_g"], token=tokens_list, text_encoder=pipeline.text_encoder_2, tokenizer=pipeline.tokenizer_2)
|
28 |
+
|
29 |
+
prompts = [prompt.replace("TOK", tokens_sequence) for prompt in prompts]
|
30 |
+
for i, prompt in enumerate(prompts):
|
31 |
+
image = pipe(prompt, num_inference_steps=25, guidance_scale=7.5).images[0]
|
32 |
+
filename = f"image-{i}.png"
|
33 |
+
image.save(f"{output_dir}/filename")
|
34 |
+
card_string += f"""
|
35 |
+
- text: '{prompt}'
|
36 |
+
output:
|
37 |
+
url:
|
38 |
+
'{filename}'"""
|
39 |
+
with open(f'{output_dir}/README.md', 'r') as file:
|
40 |
+
readme_content = file.read()
|
41 |
+
|
42 |
+
updated_readme_content = re.sub(r'(widget:\n)(.*?)(?=\n\S+:)', f'\\1{card_string}', readme_content, flags=re.DOTALL)
|
43 |
+
|
44 |
+
with open('README.md', 'w') as file:
|
45 |
+
file.write(updated_readme_content)
|
46 |
+
from huggingface_hub import HfApi
|
47 |
+
api = HfApi()
|
48 |
+
username = api.whoami()["name"]
|
49 |
+
api.upload_folder(
|
50 |
+
folder_path=output_dir,
|
51 |
+
repo_id=f"{username}/{output_dir}",
|
52 |
+
repo_type="model",
|
53 |
+
)
|
54 |
+
def main():
|
55 |
+
# Capture all arguments except the script name
|
56 |
+
script_args = sys.argv[1:]
|
57 |
+
|
58 |
+
# Extract dataset_name argument
|
59 |
+
dataset_name = None
|
60 |
+
output_dir = None
|
61 |
+
for arg in script_args:
|
62 |
+
if arg.startswith('--dataset_name='):
|
63 |
+
dataset_name = arg.split('=')[1]
|
64 |
+
break
|
65 |
+
if arg.startswith('--output_dir='):
|
66 |
+
output_dir = arg.split('=')[1]
|
67 |
+
break
|
68 |
+
if args.startswith('--train_text_encoder_ti'):
|
69 |
+
num_tokens = 0
|
70 |
+
elif args.startswith('--num_new_tokens_per_abstraction='):
|
71 |
+
num_tokens = arg.split('=')[1]
|
72 |
+
if dataset_name is None or output_dir is None:
|
73 |
+
raise ValueError("Dataset name not provided.")
|
74 |
+
|
75 |
+
do_train(script_args)
|
76 |
+
do_inference(dataset_name, output_dir, num_tokens)
|
77 |
+
|
78 |
+
if __name__ == "__main__":
|
79 |
+
main()
|