MySafeCode commited on
Commit
9908c7d
·
verified ·
1 Parent(s): 24656d8

Update a.py

Browse files
Files changed (1) hide show
  1. a.py +300 -47
a.py CHANGED
@@ -12,6 +12,11 @@ headers = {
12
  'Content-Type': 'application/json'
13
  }
14
 
 
 
 
 
 
15
  def get_models():
16
  """Fetch and display available models"""
17
  try:
@@ -47,59 +52,273 @@ def get_models():
47
  except Exception as e:
48
  return f"❌ Error: {str(e)}", "No data"
49
 
50
- def get_outputs():
51
- """Fetch and display recent outputs"""
 
52
  try:
53
  url = f'{API_HOST}/v1/image/generation/outputs'
54
  response = requests.get(url, headers=headers, timeout=10)
55
 
56
  if response.status_code == 200:
57
  data = response.json()
58
- outputs = data.get('outputs', [])
59
- total = data.get('total_count', 0)
60
- next_cursor = data.get('next', 'None')
61
-
62
- # Format display
63
- display_text = f"📊 Total outputs: {total}\n"
64
- display_text += f"📋 Showing: {len(outputs)} outputs\n"
65
- display_text += f"⏭️ Next cursor: {next_cursor}\n"
66
- display_text += f"⏰ {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
 
68
- for i, output in enumerate(outputs, 1):
69
- output_id = output.get('id', 'N/A')[:8] + '...'
70
- created_at = output.get('created_at', 'N/A')
71
- status = output.get('status', 'unknown')
72
- model_name = output.get('model_name', 'Unknown')
73
-
74
- # Format timestamp
75
- if created_at != 'N/A':
76
- try:
77
- dt = datetime.fromisoformat(created_at.replace('Z', '+00:00'))
78
- created_at = dt.strftime('%Y-%m-%d %H:%M')
79
- except:
80
- pass
81
-
82
- display_text += f"{i}. 🔹 **Output {output_id}**\n"
83
- display_text += f" 🕒 Created: {created_at}\n"
84
- display_text += f" 📊 Status: {status}\n"
85
- display_text += f" 🤖 Model: {model_name}\n"
86
-
87
- # Show image URLs if available
88
- images = output.get('image_urls', [])
89
- if images:
90
- display_text += f" 🖼️ Images: {len(images)}\n"
91
- for img_url in images[:2]: # Show first 2 URLs
92
- display_text += f" 🔗 {img_url[:50]}...\n"
93
-
94
- display_text += "─" * 40 + "\n"
95
 
96
- return display_text, str(data)
97
 
 
 
 
 
 
 
 
 
 
 
 
 
98
  else:
99
- return f"❌ Error {response.status_code}", f"Error: {response.text}"
100
-
101
- except Exception as e:
102
- return f"❌ Error: {str(e)}", "No data"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
 
104
  # Create Gradio interface
105
  with gr.Blocks(title="StableCog Dashboard") as demo:
@@ -116,11 +335,45 @@ with gr.Blocks(title="StableCog Dashboard") as demo:
116
 
117
  with gr.Tab("🖼️ Outputs"):
118
  with gr.Row():
119
- outputs_display = gr.Textbox(label="Recent Outputs", lines=25)
120
- outputs_raw = gr.Code(label="Raw JSON", language="json", lines=25)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121
 
122
- check_outputs_btn = gr.Button("🔄 Refresh Outputs", variant="primary")
123
- check_outputs_btn.click(get_outputs, outputs=[outputs_display, outputs_raw])
 
 
124
 
125
  if __name__ == "__main__":
126
  demo.launch()
 
12
  'Content-Type': 'application/json'
13
  }
14
 
15
+ # Global state for pagination
16
+ current_outputs = []
17
+ current_page = 0
18
+ page_size = 10
19
+
20
  def get_models():
21
  """Fetch and display available models"""
22
  try:
 
52
  except Exception as e:
53
  return f"❌ Error: {str(e)}", "No data"
54
 
55
+ def fetch_outputs():
56
+ """Fetch outputs from API"""
57
+ global current_outputs
58
  try:
59
  url = f'{API_HOST}/v1/image/generation/outputs'
60
  response = requests.get(url, headers=headers, timeout=10)
61
 
62
  if response.status_code == 200:
63
  data = response.json()
64
+ current_outputs = data.get('outputs', [])
65
+ return data
66
+ else:
67
+ return None
68
+ except:
69
+ return None
70
+
71
+ def update_outputs_display():
72
+ """Update outputs display with current page"""
73
+ global current_outputs, current_page, page_size
74
+
75
+ if not current_outputs:
76
+ return "📭 No outputs found. Generate some images first!", "<div style='text-align: center; padding: 40px; color: #888;'>No images found</div>", "[]"
77
+
78
+ total = len(current_outputs)
79
+ total_pages = (total + page_size - 1) // page_size # Ceiling division
80
+
81
+ # Calculate page bounds
82
+ start_idx = current_page * page_size
83
+ end_idx = min(start_idx + page_size, total)
84
+ page_outputs = current_outputs[start_idx:end_idx]
85
+
86
+ # Format display
87
+ display_text = f"📊 Total outputs: {total}\n"
88
+ display_text += f"📄 Page {current_page + 1} of {total_pages}\n"
89
+ display_text += f"🖼️ Showing {start_idx + 1}-{end_idx} of {total}\n"
90
+ display_text += f"⏰ {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n"
91
+
92
+ # Create gallery HTML with lightbox
93
+ gallery_html = """
94
+ <style>
95
+ .image-gallery {
96
+ display: grid;
97
+ grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
98
+ gap: 15px;
99
+ margin-bottom: 20px;
100
+ }
101
+ .image-card {
102
+ border-radius: 10px;
103
+ overflow: hidden;
104
+ background: rgba(255,255,255,0.1);
105
+ padding: 10px;
106
+ cursor: pointer;
107
+ transition: transform 0.2s;
108
+ }
109
+ .image-card:hover {
110
+ transform: scale(1.02);
111
+ background: rgba(255,255,255,0.15);
112
+ }
113
+ .image-card img {
114
+ width: 100%;
115
+ height: 200px;
116
+ object-fit: cover;
117
+ border-radius: 8px;
118
+ }
119
+ .image-meta {
120
+ margin-top: 8px;
121
+ font-size: 12px;
122
+ line-height: 1.4;
123
+ }
124
+ .lightbox {
125
+ display: none;
126
+ position: fixed;
127
+ z-index: 9999;
128
+ left: 0;
129
+ top: 0;
130
+ width: 100%;
131
+ height: 100%;
132
+ background: rgba(0,0,0,0.9);
133
+ justify-content: center;
134
+ align-items: center;
135
+ }
136
+ .lightbox img {
137
+ max-width: 90%;
138
+ max-height: 90%;
139
+ border-radius: 10px;
140
+ box-shadow: 0 20px 60px rgba(0,0,0,0.5);
141
+ }
142
+ .lightbox.active {
143
+ display: flex;
144
+ }
145
+ .close-btn {
146
+ position: absolute;
147
+ top: 20px;
148
+ right: 30px;
149
+ color: white;
150
+ font-size: 40px;
151
+ font-weight: bold;
152
+ cursor: pointer;
153
+ z-index: 10000;
154
+ }
155
+ .pagination {
156
+ display: flex;
157
+ justify-content: center;
158
+ gap: 10px;
159
+ margin-top: 20px;
160
+ }
161
+ .page-btn {
162
+ padding: 8px 16px;
163
+ background: rgba(255,255,255,0.1);
164
+ border: 1px solid rgba(255,255,255,0.2);
165
+ border-radius: 8px;
166
+ color: white;
167
+ cursor: pointer;
168
+ transition: background 0.2s;
169
+ }
170
+ .page-btn:hover {
171
+ background: rgba(255,255,255,0.2);
172
+ }
173
+ .page-btn.disabled {
174
+ opacity: 0.5;
175
+ cursor: not-allowed;
176
+ }
177
+ .page-info {
178
+ display: flex;
179
+ align-items: center;
180
+ padding: 8px 16px;
181
+ color: white;
182
+ }
183
+ </style>
184
+
185
+ <div class="lightbox" id="lightbox" onclick="closeLightbox()">
186
+ <span class="close-btn" onclick="closeLightbox()">&times;</span>
187
+ <img id="lightbox-img" onclick="event.stopPropagation()">
188
+ </div>
189
+
190
+ <script>
191
+ function openLightbox(imgSrc) {
192
+ document.getElementById('lightbox-img').src = imgSrc;
193
+ document.getElementById('lightbox').classList.add('active');
194
+ }
195
+ function closeLightbox() {
196
+ document.getElementById('lightbox').classList.remove('active');
197
+ }
198
+ // Close lightbox on ESC key
199
+ document.addEventListener('keydown', function(e) {
200
+ if (e.key === 'Escape') closeLightbox();
201
+ });
202
+ </script>
203
+
204
+ <div class="image-gallery">
205
+ """
206
+
207
+ for idx, output in enumerate(page_outputs, start=start_idx + 1):
208
+ output_id = output.get('id', 'N/A')
209
+ created_at = output.get('created_at', 'N/A')
210
+ model_name = output.get('model_name', 'Unknown')
211
+
212
+ # Gallery status with emojis
213
+ gallery_status = output.get('gallery_status', 'not_submitted')
214
+ gallery_emoji = {
215
+ 'not_submitted': '🔒',
216
+ 'submitted': '📤',
217
+ 'approved': '✅',
218
+ 'rejected': '❌'
219
+ }.get(gallery_status, '❓')
220
+
221
+ # Favorites
222
+ is_favorited = output.get('is_favorited', False)
223
+ favorite_emoji = '❤️' if is_favorited else '🤍'
224
+
225
+ # Format timestamp
226
+ if created_at != 'N/A':
227
+ try:
228
+ dt = datetime.fromisoformat(created_at.replace('Z', '+00:00'))
229
+ created_date = dt.strftime('%Y-%m-%d')
230
+ except:
231
+ created_date = created_at
232
+ else:
233
+ created_date = 'Unknown'
234
+
235
+ # Get image URL
236
+ image_url = output.get('image_url')
237
+ if not image_url:
238
+ image_urls = output.get('image_urls', [])
239
+ if image_urls and isinstance(image_urls, list) and len(image_urls) > 0:
240
+ image_url = image_urls[0]
241
+
242
+ if image_url:
243
+ # Text display
244
+ display_text += f"{idx}. 🔹 **Output {output_id[:8]}...**\n"
245
+ display_text += f" 🕒 {created_at}\n"
246
+ display_text += f" 🤖 {model_name}\n"
247
+ display_text += f" 🖼️ {gallery_emoji} {gallery_status}\n"
248
+ display_text += f" {favorite_emoji} Favorite\n"
249
 
250
+ # Show generation details if available
251
+ generation = output.get('generation', {})
252
+ if generation:
253
+ prompt = generation.get('prompt', 'No prompt')
254
+ if len(prompt) > 50:
255
+ prompt = prompt[:50] + '...'
256
+ display_text += f" 📝 {prompt}\n"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
257
 
258
+ display_text += "─" * 40 + "\n"
259
 
260
+ # Add to gallery with click event
261
+ gallery_html += f"""
262
+ <div class="image-card" onclick="openLightbox('{image_url}')">
263
+ <img src="{image_url}" alt="Output {idx}">
264
+ <div class="image-meta">
265
+ <div>#{idx} 📅 {created_date}</div>
266
+ <div>🤖 {model_name[:15]}{'...' if len(model_name) > 15 else ''}</div>
267
+ <div>{gallery_emoji} {gallery_status}</div>
268
+ <div>{favorite_emoji}</div>
269
+ </div>
270
+ </div>
271
+ """
272
  else:
273
+ display_text += f"{idx}. ⚠️ No image data\n"
274
+ display_text += "─" * 40 + "\n"
275
+
276
+ gallery_html += "</div>"
277
+
278
+ # Add pagination controls
279
+ gallery_html += f"""
280
+ <div class="pagination">
281
+ <button class="page-btn {'disabled' if current_page == 0 else ''}"
282
+ onclick="{'return false;' if current_page == 0 else f'window.paginationButtonClick({current_page - 1})'}">
283
+ ◀ Previous
284
+ </button>
285
+ <div class="page-info">
286
+ Page {current_page + 1} of {total_pages}
287
+ </div>
288
+ <button class="page-btn {'disabled' if current_page >= total_pages - 1 else ''}"
289
+ onclick="{'return false;' if current_page >= total_pages - 1 else f'window.paginationButtonClick({current_page + 1})'}">
290
+ Next ▶
291
+ </button>
292
+ </div>
293
+ """
294
+
295
+ return display_text, gallery_html, str(current_outputs)
296
+
297
+ def load_outputs():
298
+ """Load outputs from API and display first page"""
299
+ global current_page
300
+ current_page = 0
301
+ data = fetch_outputs()
302
+ if data:
303
+ return update_outputs_display()
304
+ else:
305
+ return "❌ Failed to load outputs", "<div style='color: red; padding: 20px;'>Failed to load outputs</div>", "[]"
306
+
307
+ def next_page():
308
+ """Go to next page"""
309
+ global current_page
310
+ if current_outputs:
311
+ total_pages = (len(current_outputs) + page_size - 1) // page_size
312
+ if current_page < total_pages - 1:
313
+ current_page += 1
314
+ return update_outputs_display()
315
+
316
+ def prev_page():
317
+ """Go to previous page"""
318
+ global current_page
319
+ if current_page > 0:
320
+ current_page -= 1
321
+ return update_outputs_display()
322
 
323
  # Create Gradio interface
324
  with gr.Blocks(title="StableCog Dashboard") as demo:
 
335
 
336
  with gr.Tab("🖼️ Outputs"):
337
  with gr.Row():
338
+ with gr.Column(scale=1):
339
+ outputs_display = gr.Textbox(label="Output Details", lines=25)
340
+ with gr.Column(scale=2):
341
+ outputs_gallery = gr.HTML(label="Image Gallery")
342
+
343
+ with gr.Row():
344
+ outputs_raw = gr.Code(label="Raw JSON", language="json", lines=15)
345
+
346
+ with gr.Row():
347
+ load_outputs_btn = gr.Button("🔄 Load Outputs", variant="primary")
348
+ prev_page_btn = gr.Button("◀ Previous Page")
349
+ next_page_btn = gr.Button("Next Page ▶")
350
+
351
+ # JavaScript for pagination
352
+ js = """
353
+ <script>
354
+ window.paginationButtonClick = function(page) {
355
+ const event = new CustomEvent('gradio_pagination', { detail: { page: page } });
356
+ document.dispatchEvent(event);
357
+ }
358
+ </script>
359
+ """
360
+ gr.HTML(js)
361
+
362
+ # Connect buttons
363
+ load_outputs_btn.click(
364
+ load_outputs,
365
+ outputs=[outputs_display, outputs_gallery, outputs_raw]
366
+ )
367
+
368
+ prev_page_btn.click(
369
+ prev_page,
370
+ outputs=[outputs_display, outputs_gallery, outputs_raw]
371
+ )
372
 
373
+ next_page_btn.click(
374
+ next_page,
375
+ outputs=[outputs_display, outputs_gallery, outputs_raw]
376
+ )
377
 
378
  if __name__ == "__main__":
379
  demo.launch()