# """ # 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