AparnaVelvet commited on
Commit
1f1cd25
·
verified ·
1 Parent(s): 663ba5c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +150 -98
app.py CHANGED
@@ -9,7 +9,7 @@ from diffusers import DiffusionPipeline
9
  MODEL_ID = "Tongyi-MAI/Z-Image-Turbo"
10
 
11
  # ==========================================
12
- # 1. Load the Model at Startup
13
  # ==========================================
14
  print("Loading Z-Image-Turbo pipeline...")
15
  pipe = DiffusionPipeline.from_pretrained(
@@ -21,11 +21,10 @@ pipe.to("cuda")
21
  print("Pipeline loaded successfully!")
22
 
23
  # ==========================================
24
- # 2. Core Generation Function (The Worker)
25
  # ==========================================
26
  @spaces.GPU(duration=30)
27
  def generate_single_image(prompt, seed):
28
- """Generates a single image and returns it."""
29
  generator = torch.Generator("cuda").manual_seed(int(seed))
30
  image = pipe(
31
  prompt=prompt,
@@ -36,11 +35,11 @@ def generate_single_image(prompt, seed):
36
  return image
37
 
38
  # ==========================================
39
- # 3. Single Image Logic
40
  # ==========================================
41
  def generate_one_ui(prompt, randomize_seed, manual_seed):
42
  if not prompt.strip():
43
- return None, "⚠️ Please enter a prompt."
44
 
45
  if randomize_seed:
46
  seed = torch.randint(0, 2**32 - 1, (1,)).item()
@@ -48,20 +47,19 @@ def generate_one_ui(prompt, randomize_seed, manual_seed):
48
  seed = int(manual_seed)
49
 
50
  image = generate_single_image(prompt, seed)
51
- return image, f"✅ Success! (Seed used: {seed})"
52
 
53
  # ==========================================
54
- # 4. Batch Processing Logic
55
  # ==========================================
56
  def batch_process(txt_file, randomize_seed, progress=gr.Progress()):
57
  if txt_file is None:
58
- return None, "⚠️ Please upload a TXT file first."
59
 
60
  with open(txt_file.name, "r", encoding="utf-8") as f:
61
  content = f.read()
62
 
63
  raw_prompts = content.split('*')
64
-
65
  prompts = []
66
  for p in raw_prompts:
67
  cleaned = p.replace('\n', ' ').replace('\r', ' ').strip()
@@ -69,14 +67,14 @@ def batch_process(txt_file, randomize_seed, progress=gr.Progress()):
69
  prompts.append(cleaned)
70
 
71
  if not prompts:
72
- return None, "⚠️ No valid prompts found. Make sure to wrap them in *asterisks*."
73
 
74
  total = len(prompts)
75
  temp_dir = tempfile.mkdtemp()
76
  generated_files = []
77
 
78
  for i, prompt in enumerate(prompts):
79
- progress((i, total), desc=f"Hacking the mainframe... Generating {i+1} of {total}...")
80
 
81
  if randomize_seed:
82
  seed = torch.randint(0, 2**32 - 1, (1,)).item()
@@ -96,125 +94,179 @@ def batch_process(txt_file, randomize_seed, progress=gr.Progress()):
96
  zipf.write(filepath, arcname=os.path.basename(filepath))
97
  zipf.write(txt_file.name, arcname="original_prompts.txt")
98
 
99
- return zip_path, f"✅ Success! Generated {total} images and packed them into a ZIP."
100
 
101
  # ==========================================
102
- # 5. Custom Maroon Hacker Glassmorphism CSS
103
  # ==========================================
104
  custom_css = """
 
105
  body, .gradio-container {
106
- background: radial-gradient(circle at top left, #2b0000, #000000) !important;
107
- color: #ffcccc !important;
 
 
 
 
 
108
  font-family: 'Courier New', Courier, monospace !important;
109
  }
 
 
110
  .glass-panel {
111
- background: rgba(60, 0, 0, 0.4) !important;
112
- backdrop-filter: blur(12px) !important;
113
- -webkit-backdrop-filter: blur(12px) !important;
114
- border: 1px solid rgba(255, 0, 60, 0.3) !important;
115
- box-shadow: 0 8px 32px 0 rgba(255, 0, 60, 0.15) !important;
116
- border-radius: 15px !important;
117
- padding: 20px !important;
118
- margin-bottom: 20px !important;
119
  }
120
- .gr-button-primary {
121
- background: linear-gradient(45deg, #800000, #ff003c) !important;
 
 
 
 
 
 
 
 
 
 
122
  border: none !important;
123
- color: white !important;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
  box-shadow: 0 0 10px #ff003c !important;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
  font-weight: bold !important;
126
  text-transform: uppercase !important;
127
  letter-spacing: 2px !important;
128
- transition: all 0.3s ease !important;
129
  }
130
  .gr-button-primary:hover {
131
- box-shadow: 0 0 20px #ff003c, 0 0 40px #ff003c !important;
 
132
  transform: scale(1.02) !important;
133
  }
134
- textarea, input[type="text"] {
135
- background: rgba(0, 0, 0, 0.7) !important;
136
- border: 1px solid #800000 !important;
137
- color: #00ffcc !important;
138
- font-family: monospace !important;
139
- }
140
  .file-preview {
141
- background: rgba(0, 0, 0, 0.5) !important;
142
  border: 1px dashed #ff003c !important;
 
143
  }
144
  """
145
 
146
  # ==========================================
147
- # 6. Gradio User Interface
148
  # ==========================================
149
- with gr.Blocks(css=custom_css, title="Aparna's Batch Image Generator") as demo:
150
 
151
  with gr.Column(elem_classes="glass-panel"):
152
  gr.Markdown(
153
  """
154
- # 🖤 Aparna's Image Generator 🖤
155
- *System Status: Online. Awaiting input.*
156
-
157
- Use the **Single Image** tab for quick creations, or the **Batch Generate** tab to process massive lists!
158
  """
159
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
160
 
161
- with gr.Tabs():
162
- # ----------------------------------
163
- # TAB 1: SINGLE IMAGE
164
- # ----------------------------------
165
- with gr.Tab("🖼️ Single Image"):
166
- with gr.Row():
167
- with gr.Column(scale=1, elem_classes="glass-panel"):
168
- single_prompt = gr.Textbox(
169
- label="Prompt",
170
- placeholder="Describe your image here...",
171
- lines=4
172
- )
173
- with gr.Accordion("Advanced Settings", open=False):
174
- single_randomize = gr.Checkbox(label="Randomize Seed", value=True)
175
- single_seed = gr.Number(label="Manual Seed", value=42, precision=0)
176
-
177
- single_btn = gr.Button("⚡ Generate Image", variant="primary")
178
-
179
- with gr.Column(scale=1, elem_classes="glass-panel"):
180
- single_output_img = gr.Image(label="Result", interactive=False)
181
- single_status = gr.Textbox(label="Status", interactive=False)
182
-
183
- # Connect Single Tab
184
- single_btn.click(
185
- fn=generate_one_ui,
186
- inputs=[single_prompt, single_randomize, single_seed],
187
- outputs=[single_output_img, single_status]
188
- )
189
-
190
- # ----------------------------------
191
- # TAB 2: BATCH GENERATE
192
- # ----------------------------------
193
- with gr.Tab("📦 Batch Generate"):
194
- with gr.Row():
195
- with gr.Column(scale=1, elem_classes="glass-panel"):
196
- gr.Markdown(
197
- """
198
- ### 🛠️ How to Use Batch:
199
- 1. Wrap **each prompt** in asterisks.
200
- *(Example: `*A cyberpunk city* *A dragon*`)*
201
- 2. Save as a `.txt` file and upload.
202
- """
203
- )
204
- txt_input = gr.File(label="📁 Upload Prompts (.txt)", file_types=[".txt"])
205
- randomize_cb = gr.Checkbox(label="🎲 Randomize Seed", value=True)
206
- run_btn = gr.Button("⚡ Initialize Batch", variant="primary")
207
-
208
- with gr.Column(scale=1, elem_classes="glass-panel"):
209
- status_text = gr.Textbox(label="System Log", interactive=False, lines=3)
210
- zip_output = gr.File(label="📦 Download Data (ZIP)", interactive=False)
211
-
212
- # Connect Batch Tab
213
- run_btn.click(
214
- fn=batch_process,
215
- inputs=[txt_input, randomize_cb],
216
- outputs=[zip_output, status_text]
217
- )
218
 
219
  if __name__ == "__main__":
220
  demo.launch()
 
9
  MODEL_ID = "Tongyi-MAI/Z-Image-Turbo"
10
 
11
  # ==========================================
12
+ # 1. Load the Model
13
  # ==========================================
14
  print("Loading Z-Image-Turbo pipeline...")
15
  pipe = DiffusionPipeline.from_pretrained(
 
21
  print("Pipeline loaded successfully!")
22
 
23
  # ==========================================
24
+ # 2. Core Generation Function
25
  # ==========================================
26
  @spaces.GPU(duration=30)
27
  def generate_single_image(prompt, seed):
 
28
  generator = torch.Generator("cuda").manual_seed(int(seed))
29
  image = pipe(
30
  prompt=prompt,
 
35
  return image
36
 
37
  # ==========================================
38
+ # 3. Logic for Single Mode
39
  # ==========================================
40
  def generate_one_ui(prompt, randomize_seed, manual_seed):
41
  if not prompt.strip():
42
+ return None, "⚠️ ERROR: INPUT REQUIRED."
43
 
44
  if randomize_seed:
45
  seed = torch.randint(0, 2**32 - 1, (1,)).item()
 
47
  seed = int(manual_seed)
48
 
49
  image = generate_single_image(prompt, seed)
50
+ return image, f"✅ EXECUTION COMPLETE. SEED: {seed}"
51
 
52
  # ==========================================
53
+ # 4. Logic for Batch Mode
54
  # ==========================================
55
  def batch_process(txt_file, randomize_seed, progress=gr.Progress()):
56
  if txt_file is None:
57
+ return None, "⚠️ ERROR: NO DATA FILE UPLOADED."
58
 
59
  with open(txt_file.name, "r", encoding="utf-8") as f:
60
  content = f.read()
61
 
62
  raw_prompts = content.split('*')
 
63
  prompts = []
64
  for p in raw_prompts:
65
  cleaned = p.replace('\n', ' ').replace('\r', ' ').strip()
 
67
  prompts.append(cleaned)
68
 
69
  if not prompts:
70
+ return None, "⚠️ ERROR: INVALID FORMAT. USE *PROMPT*."
71
 
72
  total = len(prompts)
73
  temp_dir = tempfile.mkdtemp()
74
  generated_files = []
75
 
76
  for i, prompt in enumerate(prompts):
77
+ progress((i, total), desc=f"PROCESSING {i+1} OF {total}...")
78
 
79
  if randomize_seed:
80
  seed = torch.randint(0, 2**32 - 1, (1,)).item()
 
94
  zipf.write(filepath, arcname=os.path.basename(filepath))
95
  zipf.write(txt_file.name, arcname="original_prompts.txt")
96
 
97
+ return zip_path, f"✅ BATCH COMPLETE. {total} FILES SECURED."
98
 
99
  # ==========================================
100
+ # 5. Cyberpunk HUD CSS
101
  # ==========================================
102
  custom_css = """
103
+ /* Main Background */
104
  body, .gradio-container {
105
+ background-color: #050505 !important;
106
+ background-image:
107
+ linear-gradient(rgba(255, 0, 60, 0.03) 1px, transparent 1px),
108
+ linear-gradient(90deg, rgba(255, 0, 60, 0.03) 1px, transparent 1px),
109
+ radial-gradient(circle at 50% 0%, #2a0000 0%, #050505 60%) !important;
110
+ background-size: 30px 30px, 30px 30px, 100% 100% !important;
111
+ color: #ff3333 !important;
112
  font-family: 'Courier New', Courier, monospace !important;
113
  }
114
+
115
+ /* Glass Panels */
116
  .glass-panel {
117
+ background: rgba(10, 0, 0, 0.6) !important;
118
+ backdrop-filter: blur(10px) !important;
119
+ -webkit-backdrop-filter: blur(10px) !important;
120
+ border: 1px solid rgba(255, 0, 60, 0.4) !important;
121
+ box-shadow: 0 0 15px rgba(255, 0, 60, 0.1), inset 0 0 20px rgba(255, 0, 60, 0.05) !important;
122
+ border-radius: 4px !important;
123
+ padding: 15px !important;
 
124
  }
125
+
126
+ /* Header Text */
127
+ h1, h2, h3 {
128
+ color: #ff003c !important;
129
+ text-transform: uppercase !important;
130
+ letter-spacing: 2px !important;
131
+ text-shadow: 0 0 8px rgba(255, 0, 60, 0.5) !important;
132
+ }
133
+
134
+ /* Radio Buttons (The Selection Menu) */
135
+ .gr-radio-group {
136
+ background: transparent !important;
137
  border: none !important;
138
+ display: flex !important;
139
+ justify-content: center !important;
140
+ gap: 15px !important;
141
+ }
142
+ .gr-radio-group label {
143
+ background: rgba(20, 0, 0, 0.8) !important;
144
+ border: 1px solid rgba(255, 0, 60, 0.5) !important;
145
+ color: #ff6666 !important;
146
+ padding: 10px 20px !important;
147
+ border-radius: 4px !important;
148
+ cursor: pointer !important;
149
+ transition: all 0.3s !important;
150
+ font-weight: bold !important;
151
+ }
152
+ .gr-radio-group label.selected {
153
+ background: rgba(255, 0, 60, 0.2) !important;
154
+ border-color: #ff003c !important;
155
+ color: #ffffff !important;
156
  box-shadow: 0 0 10px #ff003c !important;
157
+ }
158
+
159
+ /* Inputs */
160
+ textarea, input[type="text"], input[type="number"] {
161
+ background: rgba(0, 0, 0, 0.8) !important;
162
+ border: 1px solid #550000 !important;
163
+ color: #ff003c !important;
164
+ font-family: monospace !important;
165
+ box-shadow: inset 0 0 5px rgba(255,0,0,0.2) !important;
166
+ }
167
+ textarea:focus, input:focus {
168
+ border-color: #ff003c !important;
169
+ box-shadow: 0 0 10px #ff003c !important;
170
+ }
171
+
172
+ /* Primary Button */
173
+ .gr-button-primary {
174
+ background: linear-gradient(90deg, #800000, #ff003c, #800000) !important;
175
+ background-size: 200% auto !important;
176
+ border: 1px solid #ff003c !important;
177
+ color: white !important;
178
+ box-shadow: 0 0 15px rgba(255, 0, 60, 0.4) !important;
179
  font-weight: bold !important;
180
  text-transform: uppercase !important;
181
  letter-spacing: 2px !important;
182
+ transition: 0.5s !important;
183
  }
184
  .gr-button-primary:hover {
185
+ background-position: right center !important;
186
+ box-shadow: 0 0 25px #ff003c !important;
187
  transform: scale(1.02) !important;
188
  }
189
+
190
+ /* File Upload */
 
 
 
 
191
  .file-preview {
192
+ background: rgba(10, 0, 0, 0.5) !important;
193
  border: 1px dashed #ff003c !important;
194
+ color: #ff3333 !important;
195
  }
196
  """
197
 
198
  # ==========================================
199
+ # 6. Gradio UI Construction
200
  # ==========================================
201
+ with gr.Blocks(css=custom_css, title="Aparna's Image Generator") as demo:
202
 
203
  with gr.Column(elem_classes="glass-panel"):
204
  gr.Markdown(
205
  """
206
+ # ⎔ APARNA'S IMAGE GENERATOR ⎔
207
+ *SYSTEM STATUS: ONLINE // AWAITING INPUT*
 
 
208
  """
209
  )
210
+
211
+ # This Radio acts as our clean mobile-friendly navigation
212
+ mode_selector = gr.Radio(
213
+ choices=["🖼️ SINGLE IMAGE", "📦 BATCH GENERATE"],
214
+ value="🖼️ SINGLE IMAGE",
215
+ label="SELECT OPERATION MODE",
216
+ interactive=True
217
+ )
218
+
219
+ # --- SINGLE MODE VIEW ---
220
+ with gr.Column(visible=True, elem_classes="glass-panel") as single_view:
221
+ with gr.Row():
222
+ with gr.Column(scale=1):
223
+ single_prompt = gr.Textbox(label="PROMPT INPUT", placeholder="Enter target description...", lines=4)
224
+ with gr.Accordion("⚙️ SYSTEM PARAMETERS", open=False):
225
+ single_randomize = gr.Checkbox(label="RANDOMIZE SEED", value=True)
226
+ single_seed = gr.Number(label="MANUAL SEED", value=42, precision=0)
227
+ single_btn = gr.Button("⚡ INITIALIZE GENERATION", variant="primary")
228
+
229
+ with gr.Column(scale=1):
230
+ single_output_img = gr.Image(label="VISUAL OUTPUT", interactive=False)
231
+ single_status = gr.Textbox(label="SYSTEM LOG", interactive=False)
232
+
233
+ single_btn.click(
234
+ fn=generate_one_ui,
235
+ inputs=[single_prompt, single_randomize, single_seed],
236
+ outputs=[single_output_img, single_status]
237
+ )
238
+
239
+ # --- BATCH MODE VIEW ---
240
+ with gr.Column(visible=False, elem_classes="glass-panel") as batch_view:
241
+ with gr.Row():
242
+ with gr.Column(scale=1):
243
+ gr.Markdown("### 📁 DATA INGESTION\nFormat: `*prompt 1* *prompt 2*`")
244
+ txt_input = gr.File(label="UPLOAD TXT FILE", file_types=[".txt"])
245
+ randomize_cb = gr.Checkbox(label="RANDOMIZE SEED", value=True)
246
+ run_btn = gr.Button("⚡ EXECUTE BATCH SEQUENCE", variant="primary")
247
+
248
+ with gr.Column(scale=1):
249
+ status_text = gr.Textbox(label="SYSTEM LOG", interactive=False, lines=3)
250
+ zip_output = gr.File(label="DOWNLOAD SECURE ARCHIVE (.ZIP)", interactive=False)
251
+
252
+ run_btn.click(
253
+ fn=batch_process,
254
+ inputs=[txt_input, randomize_cb],
255
+ outputs=[zip_output, status_text]
256
+ )
257
+
258
+ # --- THE MAGIC SWITCH LOGIC ---
259
+ def toggle_view(mode):
260
+ if mode == "🖼️ SINGLE IMAGE":
261
+ return gr.update(visible=True), gr.update(visible=False)
262
+ else:
263
+ return gr.update(visible=False), gr.update(visible=True)
264
 
265
+ mode_selector.change(
266
+ fn=toggle_view,
267
+ inputs=[mode_selector],
268
+ outputs=[single_view, batch_view]
269
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
270
 
271
  if __name__ == "__main__":
272
  demo.launch()