File size: 5,707 Bytes
e353274
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
# """
# generate.py

# Stable Diffusion XL Image Generation Module
# """

# import os
# import random
# from datetime import datetime

# import torch
# from diffusers import StableDiffusionXLPipeline

# from settings import (
#     MODEL_ID,
#     DEVICE,
#     DTYPE,
#     CACHE_DIR,
#     OUTPUT_DIR,
#     ENABLE_ATTENTION_SLICING,
#     ENABLE_CPU_OFFLOAD,
#     ENABLE_XFORMERS,
#     ENABLE_SAFETY_CHECKER,
#     IMAGE_PREFIX,
#     IMAGE_EXTENSION,
# )

# # ==========================================================
# # Load Model
# # ==========================================================

# _pipeline = None


# def load_pipeline():
#     """
#     Loads the Stable Diffusion XL pipeline only once.
#     """

#     global _pipeline

#     if _pipeline is not None:
#         return _pipeline

#     print("Loading Stable Diffusion XL...")

#     pipe = StableDiffusionXLPipeline.from_pretrained(
#         MODEL_ID,
#         torch_dtype=DTYPE,
#         cache_dir=CACHE_DIR,
#         use_safetensors=True,
#     )

#     if not ENABLE_SAFETY_CHECKER:
#         pipe.safety_checker = None

#     if DEVICE == "cuda":
#         pipe.to("cuda")

#         if ENABLE_ATTENTION_SLICING:
#             pipe.enable_attention_slicing()

#         if ENABLE_CPU_OFFLOAD:
#             pipe.enable_model_cpu_offload()

#         if ENABLE_XFORMERS:
#             try:
#                 pipe.enable_xformers_memory_efficient_attention()
#             except Exception:
#                 print("xFormers not installed.")

#     else:
#         pipe.to("cpu")

#     _pipeline = pipe

#     print("Model Loaded Successfully!")

#     return pipe


# # ==========================================================
# # Seed Generator
# # ==========================================================

# def get_generator(seed: int):
#     """
#     Returns a torch.Generator with the given seed.
#     """

#     if seed == -1:
#         seed = random.randint(0, 2**32 - 1)

#     generator = torch.Generator(device=DEVICE)

#     generator.manual_seed(seed)

#     return generator, seed


# # ==========================================================
# # Save Image
# # ==========================================================

# def save_image(image):
#     """
#     Saves image to outputs directory.
#     """

#     timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")

#     filename = f"{IMAGE_PREFIX}_{timestamp}{IMAGE_EXTENSION}"

#     filepath = os.path.join(OUTPUT_DIR, filename)

#     image.save(filepath)

#     return filepath


# # ==========================================================
# # Image Generation
# # ==========================================================

# def generate_images(
#     prompt: str,
#     negative_prompt: str = "",
#     width: int = 1024,
#     height: int = 1024,
#     steps: int = 30,
#     guidance_scale: float = 7.5,
#     seed: int = -1,
#     num_images: int = 1,
# ):
#     """
#     Generates images from text prompts.

#     Returns:
#         images
#         file_paths
#         used_seed
#     """

#     pipe = load_pipeline()

#     generator, used_seed = get_generator(seed)

#     result = pipe(
#         prompt=prompt,
#         negative_prompt=negative_prompt,
#         width=width,
#         height=height,
#         num_inference_steps=steps,
#         guidance_scale=guidance_scale,
#         num_images_per_prompt=num_images,
#         generator=generator,
#     )

#     images = result.images

#     saved_files = []

#     for image in images:
#         path = save_image(image)
#         saved_files.append(path)

#     return images, saved_files, used_seed


# # ==========================================================
# # Example
# # ==========================================================

# if __name__ == "__main__":

#     images, files, seed = generate_images(
#         prompt="A futuristic city at sunset",
#         negative_prompt="low quality, blurry",
#         width=1024,
#         height=1024,
#         steps=30,
#         guidance_scale=7.5,
#         seed=-1,
#         num_images=1,
#     )

#     print(f"Seed Used : {seed}")

#     for file in files:
#         print(file)

import os
from io import BytesIO
from datetime import datetime
from urllib.parse import quote

import requests
from PIL import Image

OUTPUT_DIR = "outputs"
os.makedirs(OUTPUT_DIR, exist_ok=True)


def generate_images(

    prompt,

    negative_prompt="",

    width=1024,

    height=1024,

    steps=30,

    guidance_scale=7.5,

    seed=-1,

    num_images=1,

):
    images = []
    files = []

    if seed == -1:
        seed = int(datetime.now().timestamp())

    for i in range(num_images):
        full_prompt = prompt
        if negative_prompt:
            full_prompt += f", avoid: {negative_prompt}"

        url = (
            f"https://image.pollinations.ai/prompt/"
            f"{quote(full_prompt)}"
            f"?width={width}"
            f"&height={height}"
            f"&seed={seed+i}"
            f"&nologo=true"
        )

        response = requests.get(url, timeout=120)
        response.raise_for_status()

        image = Image.open(BytesIO(response.content))

        filename = (
            f"generated_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{i}.png"
        )
        filepath = os.path.join(OUTPUT_DIR, filename)

        image.save(filepath)

        images.append(image)
        files.append(filepath)

    return images, files, seed