MySafeCode commited on
Commit
9dbe2e6
·
verified ·
1 Parent(s): 789f1ac

Update ups.py

Browse files
Files changed (1) hide show
  1. ups.py +1 -184
ups.py CHANGED
@@ -18,16 +18,6 @@ client = Ark(
18
  )
19
 
20
  # Fresh new prompts
21
- DEFAULT_PROMPTS = {
22
- "Cinematic Nature": "Majestic drone shot soaring above misty mountains at golden hour, sunlight breaking through clouds, cinematic 4k quality, smooth motion --duration 5 --camerafixed false",
23
- "Urban Exploration": "Dynamic drone flight through narrow alleyways of a neon-lit Tokyo street at night, rain-slicked surfaces reflecting lights, cyberpunk aesthetic --duration 5 --camerafixed false",
24
- "Action Sequence": "High-speed drone chasing a sports car through a winding coastal road, dramatic cliffside views, action movie style --duration 5 --camerafixed false",
25
- "Abstract Art": "Surreal drone flight through floating geometric shapes in a dreamlike void, pastel colors, ethereal atmosphere --duration 5 --camerafixed false",
26
- "Wildlife Documentary": "Drone following a herd of elephants across the African savanna at sunset, National Geographic style, majestic wildlife cinematography --duration 5 --camerafixed false",
27
- "Sports Highlight": "Drone racing alongside professional skiers carving through fresh powder in the Alps, high-energy sports broadcast style --duration 5 --camerafixed false",
28
- "Beach Paradise": "Drone gliding over turquoise waters and white sand beaches, palm trees swaying, tropical paradise aerial view --duration 5 --camerafixed false",
29
- "Ancient Temple": "Drone circling around ancient Angkor Wat temple at dawn, mystical atmosphere, historical documentary style --duration 5 --camerafixed false"
30
- }
31
 
32
  def poll_via_json(task_id):
33
  """Check io.json for task status"""
@@ -48,101 +38,6 @@ def poll_via_json(task_id):
48
  pass
49
  return None
50
 
51
- def generate_video(image_path, manual_url, prompt_text, progress=gr.Progress()):
52
- """Generate video with proper polling and URL override"""
53
-
54
- if not API_KEY:
55
- yield "❌ API Key not configured. Please add 'Key' secret.", None
56
- return
57
-
58
- # Determine which URL to use
59
- if manual_url and manual_url.strip():
60
- image_url = manual_url.strip()
61
- source = "manual URL"
62
- elif image_path:
63
- image_url = f"/file={image_path}"
64
- source = "uploaded image"
65
- else:
66
- yield "⚠️ Please upload an image or enter a URL", None
67
- return
68
-
69
- try:
70
- progress(0, desc="Preparing image...")
71
- print(f"Using {source}: {image_url}")
72
- yield f"✅ Using {source}...", None
73
-
74
- progress(0.2, desc="Creating request...")
75
-
76
- # Create task
77
- try:
78
- create_result = client.content_generation.tasks.create(
79
- model="seedance-1-5-pro-251215",
80
- content=[
81
- {"type": "text", "text": prompt_text},
82
- {"type": "image_url", "image_url": {"url": image_url}}
83
- ]
84
- )
85
- except Exception as e:
86
- yield f"❌ API Error: {str(e)}", None
87
- return
88
-
89
- task_id = create_result.id
90
- print(f"Task created: {task_id}")
91
- yield f"✅ Task created: {task_id}", None
92
-
93
- progress(0.3, desc="Polling for results...")
94
-
95
- # Poll for results - TRY SDK FIRST, then fallback to JSON
96
- attempts = 0
97
- max_attempts = 120
98
- used_fallback = False
99
-
100
- while attempts < max_attempts:
101
- try:
102
- # Try SDK method first
103
- get_result = client.content_generation.tasks.get(task_id=task_id)
104
- status = get_result.status
105
-
106
- if status == "succeeded":
107
- progress(1.0, desc="Complete!")
108
- video_url = get_result.content.video_url if hasattr(get_result, 'content') else None
109
- yield "✅ Video generated successfully!", video_url
110
- return
111
-
112
- elif status == "failed":
113
- error_msg = get_result.error if hasattr(get_result, 'error') else "Unknown error"
114
- yield f"❌ Failed: {error_msg}", None
115
- return
116
- else:
117
- progress(0.3 + (attempts/max_attempts)*0.7, desc=f"Status: {status}")
118
- yield f"⏳ Status: {status}... (attempt {attempts + 1})", None
119
- time.sleep(2)
120
- attempts += 1
121
-
122
- except Exception as e:
123
- # If SDK fails, use JSON fallback
124
- if not used_fallback:
125
- print("SDK polling failed, using JSON fallback...")
126
- used_fallback = True
127
-
128
- # Poll JSON every 5 seconds
129
- result = poll_via_json(task_id)
130
- if result == "FAILED":
131
- yield "❌ Task failed (via JSON)", None
132
- return
133
- elif result and result != "PROCESSING":
134
- yield "✅ Video generated successfully! (via JSON)", result
135
- return
136
- else:
137
- progress(0.3 + (attempts/max_attempts)*0.7, desc="Status: processing (JSON)")
138
- yield f"⏳ Status: processing... (JSON fallback, attempt {attempts + 1})", None
139
- time.sleep(5)
140
- attempts += 1
141
-
142
- yield "⏰ Timeout after 2 minutes", None
143
-
144
- except Exception as e:
145
- yield f"❌ Error: {str(e)}", None
146
 
147
  def update_prompt(choice):
148
  return DEFAULT_PROMPTS.get(choice, "")
@@ -278,87 +173,9 @@ def update_url_display(image_path, manual_url):
278
  return "No image selected"
279
 
280
  # Create the interface
281
- with gr.Blocks(title="BytePlus Video Generator", theme=gr.themes.Soft()) as demo:
282
 
283
- gr.Markdown("# 🎥 BytePlus Video Generator")
284
 
285
- with gr.Row():
286
- if API_KEY:
287
- gr.Markdown("✅ **API Key:** Configured")
288
- else:
289
- gr.Markdown("❌ **API Key:** Not configured - please add 'Key' secret")
290
-
291
- # Create tabs
292
- with gr.Tabs():
293
- # Tab 1: Generate Video (UPDATED with URL display)
294
- with gr.TabItem("🎬 Generate Video"):
295
- with gr.Row():
296
- with gr.Column():
297
- image_input = gr.Image(
298
- label="Upload Starting Image",
299
- type="filepath",
300
- height=300
301
- )
302
-
303
- # URL override section
304
- with gr.Accordion("🔗 Image URL Override", open=False):
305
- image_url_input = gr.Textbox(
306
- label="Enter image URL directly",
307
- placeholder="https://example.com/image.jpg",
308
- info="Leave empty to use uploaded image"
309
- )
310
- gr.Markdown("💡 *Using a URL will override the uploaded image*")
311
-
312
- # Current URL display
313
- with gr.Row():
314
- current_url_display = gr.Textbox(
315
- label="Current Image URL",
316
- value="No image selected",
317
- interactive=False,
318
- lines=2
319
- )
320
-
321
- shot_type = gr.Dropdown(
322
- choices=list(DEFAULT_PROMPTS.keys()),
323
- label="🎬 Shot Type",
324
- value="Cinematic Nature"
325
- )
326
-
327
- prompt = gr.Textbox(
328
- label="📝 Custom Prompt",
329
- lines=3,
330
- value=DEFAULT_PROMPTS["Cinematic Nature"]
331
- )
332
-
333
- shot_type.change(fn=update_prompt, inputs=shot_type, outputs=prompt)
334
-
335
- generate_btn = gr.Button("🚀 Generate Video", variant="primary", size="lg")
336
-
337
- with gr.Column():
338
- status = gr.Textbox(label="Status", lines=6)
339
- video_output = gr.Video(label="Generated Video")
340
-
341
- # Quick shot buttons
342
- gr.Markdown("### Quick Shot Select")
343
- with gr.Row():
344
- gr.Button("🏔️ Nature").click(fn=lambda: "Cinematic Nature", outputs=shot_type)
345
- gr.Button("🌃 City").click(fn=lambda: "Urban Exploration", outputs=shot_type)
346
- gr.Button("🏎️ Action").click(fn=lambda: "Action Sequence", outputs=shot_type)
347
- gr.Button("🎨 Abstract").click(fn=lambda: "Abstract Art", outputs=shot_type)
348
- gr.Button("🦁 Wildlife").click(fn=lambda: "Wildlife Documentary", outputs=shot_type)
349
- gr.Button("⛷️ Sports").click(fn=lambda: "Sports Highlight", outputs=shot_type)
350
-
351
- # Update URL display when inputs change
352
- image_input.change(
353
- fn=update_url_display,
354
- inputs=[image_input, image_url_input],
355
- outputs=current_url_display
356
- )
357
-
358
- image_url_input.change(
359
- fn=update_url_display,
360
- inputs=[image_input, image_url_input],
361
- outputs=current_url_display
362
  )
363
 
364
  # Tab 2: Manual Polling
 
18
  )
19
 
20
  # Fresh new prompts
 
 
 
 
 
 
 
 
 
 
21
 
22
  def poll_via_json(task_id):
23
  """Check io.json for task status"""
 
38
  pass
39
  return None
40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
  def update_prompt(choice):
43
  return DEFAULT_PROMPTS.get(choice, "")
 
173
  return "No image selected"
174
 
175
  # Create the interface
176
+ with gr.Blocks(title="BytePlus Video Gallery", theme=gr.themes.Soft()) as demo:
177
 
 
178
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
179
  )
180
 
181
  # Tab 2: Manual Polling