ajsbsd commited on
Commit
2695e7b
·
verified ·
1 Parent(s): 376a4ff

Upload generate.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. generate.py +167 -0
generate.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # === Standard Library ===
2
+ import requests
3
+ import os
4
+ from datetime import datetime
5
+ import random
6
+ import time
7
+ import base64
8
+
9
+ # === Third-Party Libraries ===
10
+ import torch
11
+ from PIL import Image, PngImagePlugin
12
+ from diffusers import StableDiffusionPipeline
13
+
14
+ # === Configuration ===
15
+ model_id = "runwayml/stable-diffusion-v1-5"
16
+ output_dir = "generated_images"
17
+ os.makedirs(output_dir, exist_ok=True)
18
+ ROTATIONS = 32
19
+
20
+ base_prompt = "antiwar"
21
+ negative_prompt = (
22
+ "(nsfw:1.5), (easynegative:1.3) (bad_prompt:1.3) badhandv4 bad-hands-5 (negative_hand-neg) "
23
+ "(bad-picture-chill-75v), (worst quality:1.3), (low quality:1.3), (bad quality:1.3), "
24
+ "(a shadow on skin:1.3), (a shaded skin:1.3), (a dark skin:1.3), (blush:1.3), "
25
+ "(signature, watermark, username, letter, copyright name, copyright, chinese text, artist name, name tag, "
26
+ "company name, name tag, text, error:1.5), (bad anatomy:1.5), (low quality hand:1.5), (worst quality hand:1.5)"
27
+ )
28
+
29
+ generation_config = {
30
+ "vae": "vae-ft-mse-840000",
31
+ "sampler": "Euler a",
32
+ "steps": 25,
33
+ "guidance_scale": 7.0
34
+ }
35
+
36
+ GIST_LOG_FILE = "gist_log.md"
37
+
38
+ # === Initialize Model ===
39
+ device = "cuda" if torch.cuda.is_available() else "cpu"
40
+ print(f"Using device: {device}")
41
+ pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to(device)
42
+
43
+ # === Functions ===
44
+
45
+ def add_metadata_and_save(image: Image.Image, filepath: str, prompt: str, negative_prompt: str, seed: int):
46
+ """Embed generation metadata into a PNG and save it."""
47
+ meta = PngImagePlugin.PngInfo()
48
+ meta.add_text("Prompt", prompt)
49
+ meta.add_text("NegativePrompt", negative_prompt)
50
+ meta.add_text("Model", model_id)
51
+ meta.add_text("VAE", generation_config["vae"])
52
+ meta.add_text("Sampler", generation_config["sampler"])
53
+ meta.add_text("Steps", str(generation_config["steps"]))
54
+ meta.add_text("Seed", str(seed))
55
+ meta.add_text("Date", datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
56
+
57
+ image.save(filepath, "PNG", pnginfo=meta)
58
+
59
+
60
+ def upload_to_gist(image_path, prompt, negative_prompt, seed, model_id):
61
+ """
62
+ Uploads an image and metadata to GitHub Gist using Base64 encoding.
63
+ Returns Gist URL if successful.
64
+ """
65
+ # HF_SECRET INSERT HERE
66
+ USERNAME = "ajsbsd"
67
+
68
+ headers = {
69
+ "Authorization": f"token {GITHUB_TOKEN}",
70
+ "Accept": "application/vnd.github+json"
71
+ }
72
+
73
+ try:
74
+ with open(image_path, "rb") as img_file:
75
+ image_bytes = img_file.read()
76
+ image_data = base64.b64encode(image_bytes).decode("utf-8")
77
+ print(f"✅ Image encoded. Length: {len(image_data)} characters")
78
+ except Exception as e:
79
+ print(f"❌ Failed to read image: {e}")
80
+ return None
81
+
82
+ # Build metadata
83
+ metadata = (
84
+ f"Prompt: {prompt}\n"
85
+ f"Negative Prompt: {negative_prompt}\n"
86
+ f"Seed: {seed}\n"
87
+ f"Model: {model_id}\n"
88
+ f"VAE: {generation_config['vae']}\n"
89
+ f"Sampler: {generation_config['sampler']}\n"
90
+ f"Steps: {generation_config['steps']}\n"
91
+ f"Guidance Scale: {generation_config['guidance_scale']}\n"
92
+ f"Date: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
93
+ )
94
+
95
+ print(f"README.md content preview: {f'![Generated Image](data:image/png;base64,{image_data})'[:200]}...")
96
+ readme_content = f"![Generated Image](data:image/png;base64,{image_data})"
97
+
98
+ print("README.md content length:", len(readme_content)) # Optional debug
99
+ print("README.md sample:", readme_content[:200]) # Optional debug
100
+
101
+
102
+ payload = {
103
+ "description": "Stable Diffusion Generated Image",
104
+ "public": True,
105
+ "files": {
106
+ os.path.basename(image_path): {
107
+ "content": image_data,
108
+ "encoding": "base64"
109
+ },
110
+ "metadata.txt": {
111
+ "content": metadata
112
+ },
113
+ "README.md": {
114
+ "content": readme_content
115
+ }
116
+ }
117
+ }
118
+
119
+ response = requests.post("https://api.github.com/gists", headers=headers, json=payload)
120
+
121
+ if response.status_code == 201:
122
+ gist_url = response.json()["html_url"]
123
+ print(f"✅ Uploaded to GitHub Gist: {gist_url}")
124
+ return gist_url
125
+ else:
126
+ print(f"❌ Failed to create Gist: {response.status_code} - {response.text[:200]}")
127
+ return None
128
+
129
+
130
+ def generate_and_process_images(num_images: int = 1):
131
+ """Generate images with metadata and upload to GitHub Gist."""
132
+ for i in range(num_images):
133
+ variation = ", vibrant colors, neon lights" if i % 2 == 0 else ", soft pastel tones, morning light"
134
+ prompt = base_prompt + variation
135
+ seed = random.randint(10000000, 99999999)
136
+ generator = torch.Generator(device=device).manual_seed(seed)
137
+
138
+ print(f"Generating image {i + 1} with seed {seed}...")
139
+
140
+ result = pipe(
141
+ prompt=prompt,
142
+ negative_prompt=negative_prompt,
143
+ num_inference_steps=generation_config["steps"],
144
+ guidance_scale=generation_config["guidance_scale"],
145
+ generator=generator,
146
+ )
147
+
148
+ image = result.images[0]
149
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
150
+ filename = f"{output_dir}/image_{timestamp}_{i}.png"
151
+
152
+ add_metadata_and_save(image, filename, prompt, negative_prompt, seed)
153
+ print(f"Saved: {filename}")
154
+
155
+ # Upload to GitHub Gist
156
+ #gist_url = upload_to_gist(filename, prompt, negative_prompt, seed, model_id)
157
+ #if gist_url:
158
+ # with open(GIST_LOG_FILE, "a") as f:
159
+ # f.write(f"- [{prompt}]({gist_url})\n")
160
+ # print(f"📌 Gist created: {gist_url}")
161
+
162
+
163
+ # === Execution ===
164
+ if __name__ == "__main__":
165
+ generate_and_process_images(num_images=ROTATIONS)
166
+ del pipe
167
+ torch.cuda.empty_cache()