shani67 commited on
Commit
e353274
·
verified ·
1 Parent(s): 9c8f2ac

Upload 4 files

Browse files
Files changed (4) hide show
  1. app.py +164 -0
  2. generate.py +249 -0
  3. requirements.txt +11 -0
  4. settings.py +253 -0
app.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from PIL import Image
3
+
4
+
5
+ from settings import (
6
+ PAGE_TITLE,
7
+ PAGE_ICON,
8
+ LAYOUT,
9
+ DEFAULT_PROMPT,
10
+ DEFAULT_NEGATIVE_PROMPT,
11
+ DEFAULT_WIDTH,
12
+ DEFAULT_HEIGHT,
13
+ DEFAULT_STEPS,
14
+ DEFAULT_GUIDANCE_SCALE,
15
+ DEFAULT_SEED,
16
+ DEFAULT_NUM_IMAGES,
17
+ MIN_WIDTH,
18
+ MAX_WIDTH,
19
+ MIN_HEIGHT,
20
+ MAX_HEIGHT,
21
+ MIN_STEPS,
22
+ MAX_STEPS,
23
+ MIN_GUIDANCE,
24
+ MAX_GUIDANCE,
25
+ MAX_IMAGES,
26
+ )
27
+
28
+ from generate import generate_images
29
+
30
+
31
+ # Streamlit Config
32
+
33
+
34
+ st.set_page_config(
35
+ page_title=PAGE_TITLE,
36
+ page_icon=PAGE_ICON,
37
+ layout=LAYOUT,
38
+ )
39
+
40
+ st.title("Generative AI Image Generator")
41
+ # st.markdown("Generate high-quality AI images using **Stable Diffusion XL**.")
42
+
43
+
44
+ # Device Info
45
+
46
+ device = "Pollinations AI ☁️"
47
+
48
+ st.sidebar.success(f"Running on: **{device}**")
49
+
50
+ # Sidebar Settings
51
+
52
+
53
+ st.sidebar.header("Generation Settings")
54
+
55
+ width = st.sidebar.slider(
56
+ "Width",
57
+ MIN_WIDTH,
58
+ MAX_WIDTH,
59
+ DEFAULT_WIDTH,
60
+ step=64,
61
+ )
62
+
63
+ height = st.sidebar.slider(
64
+ "Height",
65
+ MIN_HEIGHT,
66
+ MAX_HEIGHT,
67
+ DEFAULT_HEIGHT,
68
+ step=64,
69
+ )
70
+
71
+ steps = st.sidebar.slider(
72
+ "Inference Steps",
73
+ MIN_STEPS,
74
+ MAX_STEPS,
75
+ DEFAULT_STEPS,
76
+ )
77
+
78
+ guidance = st.sidebar.slider(
79
+ "Guidance Scale",
80
+ float(MIN_GUIDANCE),
81
+ float(MAX_GUIDANCE),
82
+ float(DEFAULT_GUIDANCE_SCALE),
83
+ )
84
+
85
+ seed = st.sidebar.number_input(
86
+ "Seed (-1 = Random)",
87
+ value=DEFAULT_SEED,
88
+ )
89
+
90
+ num_images = st.sidebar.slider(
91
+ "Number of Images",
92
+ 1,
93
+ MAX_IMAGES,
94
+ DEFAULT_NUM_IMAGES,
95
+ )
96
+
97
+
98
+ # Prompt Inputs
99
+
100
+
101
+ prompt = st.text_area(
102
+ "Prompt",
103
+ value=DEFAULT_PROMPT,
104
+ height=120,
105
+ )
106
+
107
+ negative_prompt = st.text_area(
108
+ "Negative Prompt",
109
+ value=DEFAULT_NEGATIVE_PROMPT,
110
+ height=100,
111
+ )
112
+
113
+
114
+ # Generate Button
115
+
116
+
117
+ if st.button("✨ Generate Image", use_container_width=True):
118
+
119
+ if prompt.strip() == "":
120
+ st.error("Prompt cannot be empty.")
121
+ st.stop()
122
+
123
+ with st.spinner("Generating Image..."):
124
+
125
+ images, files, used_seed = generate_images(
126
+ prompt=prompt,
127
+ negative_prompt=negative_prompt,
128
+ width=width,
129
+ height=height,
130
+ steps=steps,
131
+ guidance_scale=guidance,
132
+ seed=int(seed),
133
+ num_images=num_images,
134
+ )
135
+
136
+ st.success(f"Generation Complete! (Seed: {used_seed})")
137
+
138
+ cols = st.columns(min(len(images), 2))
139
+
140
+ for i, image in enumerate(images):
141
+
142
+ with cols[i % 2]:
143
+
144
+ st.image(
145
+ image,
146
+ use_container_width=True,
147
+ )
148
+
149
+ with open(files[i], "rb") as f:
150
+ st.download_button(
151
+ label="⬇ Download",
152
+ data=f,
153
+ file_name=files[i].split("/")[-1],
154
+ mime="image/png",
155
+ key=i,
156
+ )
157
+
158
+
159
+ # Footer
160
+
161
+ st.markdown("---")
162
+ st.caption(
163
+ "Built using Streamlit "
164
+ )
generate.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # """
2
+ # generate.py
3
+
4
+ # Stable Diffusion XL Image Generation Module
5
+ # """
6
+
7
+ # import os
8
+ # import random
9
+ # from datetime import datetime
10
+
11
+ # import torch
12
+ # from diffusers import StableDiffusionXLPipeline
13
+
14
+ # from settings import (
15
+ # MODEL_ID,
16
+ # DEVICE,
17
+ # DTYPE,
18
+ # CACHE_DIR,
19
+ # OUTPUT_DIR,
20
+ # ENABLE_ATTENTION_SLICING,
21
+ # ENABLE_CPU_OFFLOAD,
22
+ # ENABLE_XFORMERS,
23
+ # ENABLE_SAFETY_CHECKER,
24
+ # IMAGE_PREFIX,
25
+ # IMAGE_EXTENSION,
26
+ # )
27
+
28
+ # # ==========================================================
29
+ # # Load Model
30
+ # # ==========================================================
31
+
32
+ # _pipeline = None
33
+
34
+
35
+ # def load_pipeline():
36
+ # """
37
+ # Loads the Stable Diffusion XL pipeline only once.
38
+ # """
39
+
40
+ # global _pipeline
41
+
42
+ # if _pipeline is not None:
43
+ # return _pipeline
44
+
45
+ # print("Loading Stable Diffusion XL...")
46
+
47
+ # pipe = StableDiffusionXLPipeline.from_pretrained(
48
+ # MODEL_ID,
49
+ # torch_dtype=DTYPE,
50
+ # cache_dir=CACHE_DIR,
51
+ # use_safetensors=True,
52
+ # )
53
+
54
+ # if not ENABLE_SAFETY_CHECKER:
55
+ # pipe.safety_checker = None
56
+
57
+ # if DEVICE == "cuda":
58
+ # pipe.to("cuda")
59
+
60
+ # if ENABLE_ATTENTION_SLICING:
61
+ # pipe.enable_attention_slicing()
62
+
63
+ # if ENABLE_CPU_OFFLOAD:
64
+ # pipe.enable_model_cpu_offload()
65
+
66
+ # if ENABLE_XFORMERS:
67
+ # try:
68
+ # pipe.enable_xformers_memory_efficient_attention()
69
+ # except Exception:
70
+ # print("xFormers not installed.")
71
+
72
+ # else:
73
+ # pipe.to("cpu")
74
+
75
+ # _pipeline = pipe
76
+
77
+ # print("Model Loaded Successfully!")
78
+
79
+ # return pipe
80
+
81
+
82
+ # # ==========================================================
83
+ # # Seed Generator
84
+ # # ==========================================================
85
+
86
+ # def get_generator(seed: int):
87
+ # """
88
+ # Returns a torch.Generator with the given seed.
89
+ # """
90
+
91
+ # if seed == -1:
92
+ # seed = random.randint(0, 2**32 - 1)
93
+
94
+ # generator = torch.Generator(device=DEVICE)
95
+
96
+ # generator.manual_seed(seed)
97
+
98
+ # return generator, seed
99
+
100
+
101
+ # # ==========================================================
102
+ # # Save Image
103
+ # # ==========================================================
104
+
105
+ # def save_image(image):
106
+ # """
107
+ # Saves image to outputs directory.
108
+ # """
109
+
110
+ # timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
111
+
112
+ # filename = f"{IMAGE_PREFIX}_{timestamp}{IMAGE_EXTENSION}"
113
+
114
+ # filepath = os.path.join(OUTPUT_DIR, filename)
115
+
116
+ # image.save(filepath)
117
+
118
+ # return filepath
119
+
120
+
121
+ # # ==========================================================
122
+ # # Image Generation
123
+ # # ==========================================================
124
+
125
+ # def generate_images(
126
+ # prompt: str,
127
+ # negative_prompt: str = "",
128
+ # width: int = 1024,
129
+ # height: int = 1024,
130
+ # steps: int = 30,
131
+ # guidance_scale: float = 7.5,
132
+ # seed: int = -1,
133
+ # num_images: int = 1,
134
+ # ):
135
+ # """
136
+ # Generates images from text prompts.
137
+
138
+ # Returns:
139
+ # images
140
+ # file_paths
141
+ # used_seed
142
+ # """
143
+
144
+ # pipe = load_pipeline()
145
+
146
+ # generator, used_seed = get_generator(seed)
147
+
148
+ # result = pipe(
149
+ # prompt=prompt,
150
+ # negative_prompt=negative_prompt,
151
+ # width=width,
152
+ # height=height,
153
+ # num_inference_steps=steps,
154
+ # guidance_scale=guidance_scale,
155
+ # num_images_per_prompt=num_images,
156
+ # generator=generator,
157
+ # )
158
+
159
+ # images = result.images
160
+
161
+ # saved_files = []
162
+
163
+ # for image in images:
164
+ # path = save_image(image)
165
+ # saved_files.append(path)
166
+
167
+ # return images, saved_files, used_seed
168
+
169
+
170
+ # # ==========================================================
171
+ # # Example
172
+ # # ==========================================================
173
+
174
+ # if __name__ == "__main__":
175
+
176
+ # images, files, seed = generate_images(
177
+ # prompt="A futuristic city at sunset",
178
+ # negative_prompt="low quality, blurry",
179
+ # width=1024,
180
+ # height=1024,
181
+ # steps=30,
182
+ # guidance_scale=7.5,
183
+ # seed=-1,
184
+ # num_images=1,
185
+ # )
186
+
187
+ # print(f"Seed Used : {seed}")
188
+
189
+ # for file in files:
190
+ # print(file)
191
+
192
+ import os
193
+ from io import BytesIO
194
+ from datetime import datetime
195
+ from urllib.parse import quote
196
+
197
+ import requests
198
+ from PIL import Image
199
+
200
+ OUTPUT_DIR = "outputs"
201
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
202
+
203
+
204
+ def generate_images(
205
+ prompt,
206
+ negative_prompt="",
207
+ width=1024,
208
+ height=1024,
209
+ steps=30,
210
+ guidance_scale=7.5,
211
+ seed=-1,
212
+ num_images=1,
213
+ ):
214
+ images = []
215
+ files = []
216
+
217
+ if seed == -1:
218
+ seed = int(datetime.now().timestamp())
219
+
220
+ for i in range(num_images):
221
+ full_prompt = prompt
222
+ if negative_prompt:
223
+ full_prompt += f", avoid: {negative_prompt}"
224
+
225
+ url = (
226
+ f"https://image.pollinations.ai/prompt/"
227
+ f"{quote(full_prompt)}"
228
+ f"?width={width}"
229
+ f"&height={height}"
230
+ f"&seed={seed+i}"
231
+ f"&nologo=true"
232
+ )
233
+
234
+ response = requests.get(url, timeout=120)
235
+ response.raise_for_status()
236
+
237
+ image = Image.open(BytesIO(response.content))
238
+
239
+ filename = (
240
+ f"generated_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{i}.png"
241
+ )
242
+ filepath = os.path.join(OUTPUT_DIR, filename)
243
+
244
+ image.save(filepath)
245
+
246
+ images.append(image)
247
+ files.append(filepath)
248
+
249
+ return images, files, seed
requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ streamlit
2
+ torch
3
+ torchvision
4
+ diffusers
5
+ transformers
6
+ accelerate
7
+ safetensors
8
+ Pillow
9
+ huggingface_hub
10
+ sentencepiece
11
+ protobuf
settings.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # """
2
+ # config.py
3
+
4
+ # Configuration file for the Text-to-Image Generator.
5
+ # Stores model settings, default generation parameters,
6
+ # and directory paths.
7
+ # """
8
+
9
+ # import os
10
+ # import torch
11
+
12
+ # # ==========================================================
13
+ # # Hugging Face Model
14
+ # # ==========================================================
15
+
16
+ # MODEL_ID = "stabilityai/stable-diffusion-xl-base-1.0"
17
+
18
+ # # Alternative models
19
+ # # MODEL_ID = "runwayml/stable-diffusion-v1-5"
20
+ # # MODEL_ID = "segmind/SSD-1B"
21
+
22
+ # # ==========================================================
23
+ # # Device Configuration
24
+ # # ==========================================================
25
+
26
+ # DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
27
+
28
+ # DTYPE = (
29
+ # torch.float16
30
+ # if torch.cuda.is_available()
31
+ # else torch.float32
32
+ # )
33
+
34
+ # # ==========================================================
35
+ # # Generation Defaults
36
+ # # ==========================================================
37
+
38
+ # DEFAULT_PROMPT = "A futuristic cyberpunk city at sunset"
39
+
40
+ # DEFAULT_NEGATIVE_PROMPT = (
41
+ # "low quality, blurry, distorted, watermark, text, "
42
+ # "extra fingers, deformed, ugly"
43
+ # )
44
+
45
+ # DEFAULT_HEIGHT = 1024
46
+ # DEFAULT_WIDTH = 1024
47
+
48
+ # DEFAULT_STEPS = 30
49
+
50
+ # DEFAULT_GUIDANCE_SCALE = 7.5
51
+
52
+ # DEFAULT_SEED = -1
53
+
54
+ # DEFAULT_NUM_IMAGES = 1
55
+
56
+ # # ==========================================================
57
+ # # Image Limits
58
+ # # ==========================================================
59
+
60
+ # MIN_HEIGHT = 512
61
+ # MAX_HEIGHT = 1024
62
+
63
+ # MIN_WIDTH = 512
64
+ # MAX_WIDTH = 1024
65
+
66
+ # MIN_STEPS = 10
67
+ # MAX_STEPS = 100
68
+
69
+ # MIN_GUIDANCE = 1.0
70
+ # MAX_GUIDANCE = 20.0
71
+
72
+ # MAX_IMAGES = 4
73
+
74
+ # # ==========================================================
75
+ # # Output Settings
76
+ # # ==========================================================
77
+
78
+ # OUTPUT_DIR = "outputs"
79
+
80
+ # os.makedirs(OUTPUT_DIR, exist_ok=True)
81
+
82
+ # # ==========================================================
83
+ # # Hugging Face Cache
84
+ # # ==========================================================
85
+
86
+ # CACHE_DIR = "models"
87
+
88
+ # os.makedirs(CACHE_DIR, exist_ok=True)
89
+
90
+ # # ==========================================================
91
+ # # Streamlit
92
+ # # ==========================================================
93
+
94
+ # PAGE_TITLE = "AI Text-to-Image Generator"
95
+
96
+ # PAGE_ICON = "🎨"
97
+
98
+ # LAYOUT = "wide"
99
+
100
+ # # ==========================================================
101
+ # # Generation Settings
102
+ # # ==========================================================
103
+
104
+ # ENABLE_ATTENTION_SLICING = True
105
+
106
+ # ENABLE_CPU_OFFLOAD = False
107
+
108
+ # ENABLE_XFORMERS = False
109
+
110
+ # ENABLE_SAFETY_CHECKER = False
111
+
112
+ # # ==========================================================
113
+ # # File Names
114
+ # # ==========================================================
115
+
116
+ # IMAGE_PREFIX = "generated"
117
+
118
+ # IMAGE_EXTENSION = ".png"
119
+
120
+ # # ==========================================================
121
+ # # Supported Formats
122
+ # # ==========================================================
123
+
124
+ # SUPPORTED_FORMATS = [
125
+ # "PNG",
126
+ # "JPEG",
127
+ # ]
128
+
129
+ # # ==========================================================
130
+ # # Random Seed Range
131
+ # # ==========================================================
132
+
133
+ # MAX_SEED = 2**32 - 1
134
+
135
+
136
+
137
+
138
+
139
+
140
+
141
+
142
+
143
+
144
+ """
145
+ config.py
146
+
147
+ Configuration settings for the AI Text-to-Image Generator.
148
+ """
149
+
150
+ from pathlib import Path
151
+ import torch
152
+
153
+ # ==========================================================
154
+ # Project Directories
155
+ # ==========================================================
156
+
157
+ BASE_DIR = Path(__file__).resolve().parent
158
+
159
+ OUTPUT_DIR = BASE_DIR / "outputs"
160
+ CACHE_DIR = BASE_DIR / "models"
161
+
162
+ OUTPUT_DIR.mkdir(exist_ok=True)
163
+ CACHE_DIR.mkdir(exist_ok=True)
164
+
165
+ # ==========================================================
166
+ # Hugging Face Model
167
+ # ==========================================================
168
+
169
+ # MODEL_ID = "stabilityai/stable-diffusion-xl-base-1.0"
170
+ MODEL_ID = "segmind/SSD-1B"
171
+
172
+ # Alternative models
173
+ # MODEL_ID = "runwayml/stable-diffusion-v1-5"
174
+ # MODEL_ID = "segmind/SSD-1B"
175
+
176
+ # ==========================================================
177
+ # Device
178
+ # ==========================================================
179
+
180
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
181
+
182
+ DTYPE = torch.float16 if DEVICE == "cuda" else torch.float32
183
+
184
+ # ==========================================================
185
+ # Streamlit Page
186
+ # ==========================================================
187
+
188
+ PAGE_TITLE = "AI Text-to-Image Generator"
189
+ PAGE_ICON = "🎨"
190
+ LAYOUT = "wide"
191
+
192
+ # ==========================================================
193
+ # Default Generation Parameters
194
+ # ==========================================================
195
+
196
+ DEFAULT_PROMPT = "A futuristic cyberpunk city at sunset"
197
+
198
+ DEFAULT_NEGATIVE_PROMPT = (
199
+ "low quality, blurry, distorted, watermark, text, "
200
+ "extra fingers, deformed, ugly"
201
+ )
202
+
203
+ DEFAULT_WIDTH = 1024
204
+ DEFAULT_HEIGHT = 1024
205
+ DEFAULT_STEPS = 30
206
+ DEFAULT_GUIDANCE_SCALE = 7.5
207
+ DEFAULT_SEED = -1
208
+ DEFAULT_NUM_IMAGES = 1
209
+
210
+ # ==========================================================
211
+ # Limits
212
+ # ==========================================================
213
+
214
+ MIN_WIDTH = 512
215
+ MAX_WIDTH = 1024
216
+
217
+ MIN_HEIGHT = 512
218
+ MAX_HEIGHT = 1024
219
+
220
+ MIN_STEPS = 10
221
+ MAX_STEPS = 100
222
+
223
+ MIN_GUIDANCE = 1.0
224
+ MAX_GUIDANCE = 20.0
225
+
226
+ MAX_IMAGES = 4
227
+
228
+ # ==========================================================
229
+ # Performance Options
230
+ # ==========================================================
231
+
232
+ ENABLE_ATTENTION_SLICING = True
233
+ ENABLE_CPU_OFFLOAD = False
234
+ ENABLE_XFORMERS = False
235
+ ENABLE_SAFETY_CHECKER = False
236
+
237
+ # ==========================================================
238
+ # Output Files
239
+ # ==========================================================
240
+
241
+ IMAGE_PREFIX = "generated"
242
+ IMAGE_EXTENSION = ".png"
243
+
244
+ SUPPORTED_FORMATS = [
245
+ "PNG",
246
+ "JPEG",
247
+ ]
248
+
249
+ # ==========================================================
250
+ # Random Seed
251
+ # ==========================================================
252
+
253
+ MAX_SEED = 2**32 - 1