-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_ui.py
More file actions
611 lines (508 loc) · 21.5 KB
/
test_ui.py
File metadata and controls
611 lines (508 loc) · 21.5 KB
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
#!/usr/bin/env python3
"""
Decart SDK Test UI - Interactive testing interface for the Python SDK.
Usage:
pip install gradio
python test_ui.py
Then open http://localhost:7860 in your browser.
"""
import asyncio
import gradio as gr
from pathlib import Path
from typing import Optional
import tempfile
# Import the SDK
from decart import DecartClient, models
def get_client(api_key: str) -> DecartClient:
"""Create a Decart client with the given API key."""
if not api_key or not api_key.strip():
raise ValueError("Please enter an API key")
return DecartClient(api_key=api_key.strip())
# ============================================================================
# Image Processing (Process API)
# ============================================================================
async def process_text_to_image(
api_key: str,
prompt: str,
seed: Optional[int],
resolution: str,
orientation: str,
) -> tuple[Optional[bytes], str]:
"""Generate an image from text prompt."""
try:
client = get_client(api_key)
options = {
"model": models.image("lucy-pro-t2i"),
"prompt": prompt,
}
if seed:
options["seed"] = seed
if resolution and resolution != "default":
options["resolution"] = resolution
if orientation and orientation != "default":
options["orientation"] = orientation
result = await client.process(options)
return result, f"Success! Generated image from prompt: '{prompt[:50]}...'"
except Exception as e:
return None, f"Error: {str(e)}"
async def process_image_to_image(
api_key: str,
prompt: str,
input_image: str,
seed: Optional[int],
strength: float,
) -> tuple[Optional[bytes], str]:
"""Transform an image with a prompt."""
try:
if not input_image:
return None, "Please upload an image"
client = get_client(api_key)
options = {
"model": models.image("lucy-pro-i2i"),
"prompt": prompt,
"data": Path(input_image),
}
if seed:
options["seed"] = seed
if strength:
options["strength"] = strength
result = await client.process(options)
return result, f"Success! Transformed image with prompt: '{prompt[:50]}...'"
except Exception as e:
return None, f"Error: {str(e)}"
# ============================================================================
# Video Processing (Queue API)
# ============================================================================
async def process_video_t2v(
api_key: str,
prompt: str,
seed: Optional[int],
enhance_prompt: bool,
progress=gr.Progress(),
) -> tuple[Optional[str], str]:
"""Generate a video from text prompt."""
try:
client = get_client(api_key)
options = {
"model": models.video("lucy-pro-t2v"),
"prompt": prompt,
}
if seed:
options["seed"] = seed
if enhance_prompt is not None:
options["enhance_prompt"] = enhance_prompt
progress(0.1, desc="Submitting job...")
def on_status_change(job):
if job.status == "pending":
progress(0.2, desc="Job pending...")
elif job.status == "processing":
progress(0.5, desc="Processing video...")
options["on_status_change"] = on_status_change
result = await client.queue.submit_and_poll(options)
if result.status == "failed":
return None, f"Job failed: {result.error}"
progress(0.9, desc="Saving video...")
# Save to temp file
with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as f:
f.write(result.data)
return f.name, f"Success! Generated video from prompt: '{prompt[:50]}...'"
except Exception as e:
return None, f"Error: {str(e)}"
async def process_video_v2v(
api_key: str,
prompt: str,
input_video: str,
seed: Optional[int],
enhance_prompt: bool,
progress=gr.Progress(),
) -> tuple[Optional[str], str]:
"""Transform a video with a prompt."""
try:
if not input_video:
return None, "Please upload a video"
client = get_client(api_key)
options = {
"model": models.video("lucy-pro-v2v"),
"prompt": prompt,
"data": Path(input_video),
}
if seed:
options["seed"] = seed
if enhance_prompt is not None:
options["enhance_prompt"] = enhance_prompt
progress(0.1, desc="Submitting job...")
def on_status_change(job):
if job.status == "pending":
progress(0.2, desc="Job pending...")
elif job.status == "processing":
progress(0.5, desc="Processing video...")
options["on_status_change"] = on_status_change
result = await client.queue.submit_and_poll(options)
if result.status == "failed":
return None, f"Job failed: {result.error}"
progress(0.9, desc="Saving video...")
with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as f:
f.write(result.data)
return f.name, f"Success! Transformed video with prompt: '{prompt[:50]}...'"
except Exception as e:
return None, f"Error: {str(e)}"
async def process_video_restyle(
api_key: str,
input_video: str,
use_reference_image: bool,
prompt: str,
reference_image: Optional[str],
seed: Optional[int],
enhance_prompt: bool,
progress=gr.Progress(),
) -> tuple[Optional[str], str]:
"""Restyle a video with prompt OR reference image."""
try:
if not input_video:
return None, "Please upload a video"
client = get_client(api_key)
options = {
"model": models.video("lucy-restyle-v2v"),
"data": Path(input_video),
}
if use_reference_image:
if not reference_image:
return None, "Please upload a reference image"
options["reference_image"] = Path(reference_image)
else:
if not prompt:
return None, "Please enter a prompt"
options["prompt"] = prompt
if enhance_prompt is not None:
options["enhance_prompt"] = enhance_prompt
if seed:
options["seed"] = seed
progress(0.1, desc="Submitting job...")
def on_status_change(job):
if job.status == "pending":
progress(0.2, desc="Job pending...")
elif job.status == "processing":
progress(0.5, desc="Processing video...")
options["on_status_change"] = on_status_change
result = await client.queue.submit_and_poll(options)
if result.status == "failed":
return None, f"Job failed: {result.error}"
progress(0.9, desc="Saving video...")
with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as f:
f.write(result.data)
mode = "reference image" if use_reference_image else f"prompt: '{prompt[:30]}...'"
return f.name, f"Success! Restyled video with {mode}"
except Exception as e:
return None, f"Error: {str(e)}"
async def process_video_i2v(
api_key: str,
prompt: str,
input_image: str,
seed: Optional[int],
enhance_prompt: bool,
progress=gr.Progress(),
) -> tuple[Optional[str], str]:
"""Generate a video from an image."""
try:
if not input_image:
return None, "Please upload an image"
client = get_client(api_key)
options = {
"model": models.video("lucy-pro-i2v"),
"prompt": prompt,
"data": Path(input_image),
}
if seed:
options["seed"] = seed
if enhance_prompt is not None:
options["enhance_prompt"] = enhance_prompt
progress(0.1, desc="Submitting job...")
def on_status_change(job):
if job.status == "pending":
progress(0.2, desc="Job pending...")
elif job.status == "processing":
progress(0.5, desc="Processing video...")
options["on_status_change"] = on_status_change
result = await client.queue.submit_and_poll(options)
if result.status == "failed":
return None, f"Job failed: {result.error}"
progress(0.9, desc="Saving video...")
with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as f:
f.write(result.data)
return f.name, "Success! Generated video from image"
except Exception as e:
return None, f"Error: {str(e)}"
# ============================================================================
# Tokens API
# ============================================================================
async def create_token(api_key: str) -> str:
"""Create a short-lived client token."""
try:
client = get_client(api_key)
result = await client.tokens.create()
return f"Success!\n\nToken: {result.api_key}\nExpires: {result.expires_at}"
except Exception as e:
return f"Error: {str(e)}"
# ============================================================================
# Gradio UI
# ============================================================================
def create_ui():
"""Create the Gradio interface."""
with gr.Blocks(
title="Decart SDK Test UI",
theme=gr.themes.Soft(),
css="""
.status-success { color: green; }
.status-error { color: red; }
""",
) as demo:
gr.Markdown(
"""
# Decart SDK Test UI
Interactive testing interface for the Decart Python SDK.
Enter your API key below to get started.
"""
)
# API Key input (shared across all tabs)
api_key = gr.Textbox(
label="API Key",
placeholder="Enter your Decart API key",
type="password",
elem_id="api-key-input",
)
with gr.Tabs():
# ================================================================
# Image Processing Tab
# ================================================================
with gr.TabItem("Image Generation"):
gr.Markdown("### Text to Image")
with gr.Row():
with gr.Column():
t2i_prompt = gr.Textbox(
label="Prompt",
placeholder="A beautiful sunset over mountains",
lines=3,
)
with gr.Row():
t2i_seed = gr.Number(label="Seed (optional)", precision=0)
t2i_resolution = gr.Dropdown(
label="Resolution",
choices=["default", "720p", "1080p"],
value="default",
)
t2i_orientation = gr.Dropdown(
label="Orientation",
choices=["default", "landscape", "portrait", "square"],
value="default",
)
t2i_btn = gr.Button("Generate Image", variant="primary")
with gr.Column():
t2i_output = gr.Image(label="Generated Image", type="filepath")
t2i_status = gr.Textbox(label="Status", interactive=False)
t2i_btn.click(
fn=lambda *args: asyncio.run(process_text_to_image(*args)),
inputs=[api_key, t2i_prompt, t2i_seed, t2i_resolution, t2i_orientation],
outputs=[t2i_output, t2i_status],
)
gr.Markdown("---")
gr.Markdown("### Image to Image")
with gr.Row():
with gr.Column():
i2i_input = gr.Image(label="Input Image", type="filepath")
i2i_prompt = gr.Textbox(
label="Prompt",
placeholder="Make it look like anime",
lines=2,
)
with gr.Row():
i2i_seed = gr.Number(label="Seed (optional)", precision=0)
i2i_strength = gr.Slider(
label="Strength",
minimum=0.0,
maximum=1.0,
value=0.75,
step=0.05,
)
i2i_btn = gr.Button("Transform Image", variant="primary")
with gr.Column():
i2i_output = gr.Image(label="Transformed Image", type="filepath")
i2i_status = gr.Textbox(label="Status", interactive=False)
i2i_btn.click(
fn=lambda *args: asyncio.run(process_image_to_image(*args)),
inputs=[api_key, i2i_prompt, i2i_input, i2i_seed, i2i_strength],
outputs=[i2i_output, i2i_status],
)
# ================================================================
# Video Processing Tab
# ================================================================
with gr.TabItem("Video Generation"):
gr.Markdown("### Text to Video")
with gr.Row():
with gr.Column():
t2v_prompt = gr.Textbox(
label="Prompt",
placeholder="A cat walking in a park",
lines=3,
)
with gr.Row():
t2v_seed = gr.Number(label="Seed (optional)", precision=0)
t2v_enhance = gr.Checkbox(label="Enhance Prompt", value=True)
t2v_btn = gr.Button("Generate Video", variant="primary")
with gr.Column():
t2v_output = gr.Video(label="Generated Video")
t2v_status = gr.Textbox(label="Status", interactive=False)
t2v_btn.click(
fn=lambda *args: asyncio.run(process_video_t2v(*args)),
inputs=[api_key, t2v_prompt, t2v_seed, t2v_enhance],
outputs=[t2v_output, t2v_status],
)
gr.Markdown("---")
gr.Markdown("### Image to Video")
with gr.Row():
with gr.Column():
i2v_input = gr.Image(label="Input Image", type="filepath")
i2v_prompt = gr.Textbox(
label="Prompt",
placeholder="The scene comes to life",
lines=2,
)
with gr.Row():
i2v_seed = gr.Number(label="Seed (optional)", precision=0)
i2v_enhance = gr.Checkbox(label="Enhance Prompt", value=True)
i2v_btn = gr.Button("Generate Video", variant="primary")
with gr.Column():
i2v_output = gr.Video(label="Generated Video")
i2v_status = gr.Textbox(label="Status", interactive=False)
i2v_btn.click(
fn=lambda *args: asyncio.run(process_video_i2v(*args)),
inputs=[api_key, i2v_prompt, i2v_input, i2v_seed, i2v_enhance],
outputs=[i2v_output, i2v_status],
)
gr.Markdown("---")
gr.Markdown("### Video to Video")
with gr.Row():
with gr.Column():
v2v_input = gr.Video(label="Input Video")
v2v_prompt = gr.Textbox(
label="Prompt",
placeholder="Make it look like Lego world",
lines=2,
)
with gr.Row():
v2v_seed = gr.Number(label="Seed (optional)", precision=0)
v2v_enhance = gr.Checkbox(label="Enhance Prompt", value=True)
v2v_btn = gr.Button("Transform Video", variant="primary")
with gr.Column():
v2v_output = gr.Video(label="Transformed Video")
v2v_status = gr.Textbox(label="Status", interactive=False)
v2v_btn.click(
fn=lambda *args: asyncio.run(process_video_v2v(*args)),
inputs=[api_key, v2v_prompt, v2v_input, v2v_seed, v2v_enhance],
outputs=[v2v_output, v2v_status],
)
# ================================================================
# Video Restyle Tab (NEW - with reference image support)
# ================================================================
with gr.TabItem("Video Restyle (NEW)"):
gr.Markdown(
"""
### Video Restyle with Prompt OR Reference Image
This model supports two modes:
- **Text Prompt**: Describe the style you want
- **Reference Image**: Upload an image to use as style reference
"""
)
with gr.Row():
with gr.Column():
restyle_input = gr.Video(label="Input Video")
restyle_mode = gr.Checkbox(
label="Use Reference Image (instead of text prompt)",
value=False,
)
restyle_prompt = gr.Textbox(
label="Prompt",
placeholder="Make it look like anime",
lines=2,
visible=True,
)
restyle_ref_image = gr.Image(
label="Reference Image",
type="filepath",
visible=False,
)
with gr.Row():
restyle_seed = gr.Number(label="Seed (optional)", precision=0)
restyle_enhance = gr.Checkbox(
label="Enhance Prompt",
value=True,
visible=True,
)
restyle_btn = gr.Button("Restyle Video", variant="primary")
with gr.Column():
restyle_output = gr.Video(label="Restyled Video")
restyle_status = gr.Textbox(label="Status", interactive=False)
# Toggle visibility based on mode
def toggle_mode(use_ref):
return (
gr.update(visible=not use_ref), # prompt
gr.update(visible=use_ref), # ref image
gr.update(visible=not use_ref), # enhance
)
restyle_mode.change(
fn=toggle_mode,
inputs=[restyle_mode],
outputs=[restyle_prompt, restyle_ref_image, restyle_enhance],
)
restyle_btn.click(
fn=lambda *args: asyncio.run(process_video_restyle(*args)),
inputs=[
api_key,
restyle_input,
restyle_mode,
restyle_prompt,
restyle_ref_image,
restyle_seed,
restyle_enhance,
],
outputs=[restyle_output, restyle_status],
)
# ================================================================
# Tokens Tab
# ================================================================
with gr.TabItem("Tokens"):
gr.Markdown(
"""
### Create Client Token
Create a short-lived token for client-side use.
These tokens are meant for temporary access and expire automatically.
"""
)
with gr.Row():
with gr.Column():
token_btn = gr.Button("Create Token", variant="primary")
with gr.Column():
token_output = gr.Textbox(
label="Result",
lines=5,
interactive=False,
)
token_btn.click(
fn=lambda key: asyncio.run(create_token(key)),
inputs=[api_key],
outputs=[token_output],
)
gr.Markdown(
"""
---
**Note**: This UI uses the Decart Python SDK.
For realtime/WebRTC features, use the example scripts in `examples/`.
"""
)
return demo
if __name__ == "__main__":
demo = create_ui()
demo.launch(
server_name="127.0.0.1", # localhost only
server_port=7860,
share=False,
)