Update ups.py
Browse files17 unmodified lines1819202122232425262728293031323314 unmodified lines48495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148129 unmodified lines27827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336417 unmodified lines)# Fresh new promptsDEFAULT_PROMPTS = {"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","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","Action Sequence": "High-speed drone chasing a sports car through a winding coastal road, dramatic cliffside views, action movie style --duration 5 --camerafixed false","Abstract Art": "Surreal drone flight through floating geometric shapes in a dreamlike void, pastel colors, ethereal atmosphere --duration 5 --camerafixed false","Wildlife Documentary": "Drone following a herd of elephants across the African savanna at sunset, National Geographic style, majestic wildlife cinematography --duration 5 --camerafixed false","Sports Highlight": "Drone racing alongside professional skiers carving through fresh powder in the Alps, high-energy sports broadcast style --duration 5 --camerafixed false","Beach Paradise": "Drone gliding over turquoise waters and white sand beaches, palm trees swaying, tropical paradise aerial view --duration 5 --camerafixed false","Ancient Temple": "Drone circling around ancient Angkor Wat temple at dawn, mystical atmosphere, historical documentary style --duration 5 --camerafixed false"}def poll_via_json(task_id):"""Check io.json for task status"""14 unmodified linespassreturn Nonedef generate_video(image_path, manual_url, prompt_text, progress=gr.Progress()):"""Generate video with proper polling and URL override"""if not API_KEY:yield "❌ API Key not configured. Please add 'Key' secret.", Nonereturn# Determine which URL to useif manual_url and manual_url.strip():image_url = manual_url.strip()source = "manual URL"elif image_path:image_url = f"/file={image_path}"source = "uploaded image"else:yield "⚠️ Please upload an image or enter a URL", Nonereturntry:progress(0, desc="Preparing image...")print(f"Using {source}: {image_url}")yield f"✅ Using {source}...", Noneprogress(0.2, desc="Creating request...")# Create tasktry:create_result = client.content_generation.tasks.create(model="seedance-1-5-pro-251215",content=[{"type": "text", "text": prompt_text},{"type": "image_url", "image_url": {"url": image_url}}])except Exception as e:yield f"❌ API Error: {str(e)}", Nonereturntask_id = create_result.idprint(f"Task created: {task_id}")yield f"✅ Task created: {task_id}", Noneprogress(0.3, desc="Polling for results...")# Poll for results - TRY SDK FIRST, then fallback to JSONattempts = 0max_attempts = 120used_fallback = Falsewhile attempts < max_attempts:try:# Try SDK method firstget_result = client.content_generation.tasks.get(task_id=task_id)status = get_result.statusif status == "succeeded":progress(1.0, desc="Complete!")video_url = get_result.content.video_url if hasattr(get_result, 'content') else Noneyield "✅ Video generated successfully!", video_urlreturnelif status == "failed":error_msg = get_result.error if hasattr(get_result, 'error') else "Unknown error"yield f"❌ Failed: {error_msg}", Nonereturnelse:progress(0.3 + (attempts/max_attempts)*0.7, desc=f"Status: {status}")yield f"⏳ Status: {status}... (attempt {attempts + 1})", Nonetime.sleep(2)attempts += 1except Exception as e:# If SDK fails, use JSON fallbackif not used_fallback:print("SDK polling failed, using JSON fallback...")used_fallback = True# Poll JSON every 5 secondsresult = poll_via_json(task_id)if result == "FAILED":yield "❌ Task failed (via JSON)", Nonereturnelif result and result != "PROCESSING":yield "✅ Video generated successfully! (via JSON)", resultreturnelse:progress(0.3 + (attempts/max_attempts)*0.7, desc="Status: processing (JSON)")yield f"⏳ Status: processing... (JSON fallback, attempt {attempts + 1})", Nonetime.sleep(5)attempts += 1yield "⏰ Timeout after 2 minutes", Noneexcept Exception as e:yield f"❌ Error: {str(e)}", Nonedef update_prompt(choice):return DEFAULT_PROMPTS.get(choice, "")129 unmodified linesreturn "No image selected"# Create the interfacewith gr.Blocks(title="BytePlus Video Generator", theme=gr.themes.Soft()) as demo:gr.Markdown("# 🎥 BytePlus Video Generator")with gr.Row():if API_KEY:gr.Markdown("✅ **API Key:** Configured")else:gr.Markdown("❌ **API Key:** Not configured - please add 'Key' secret")# Create tabswith gr.Tabs():# Tab 1: Generate Video (UPDATED with URL display)with gr.TabItem("🎬 Generate Video"):with gr.Row():with gr.Column():image_input = gr.Image(label="Upload Starting Image",type="filepath",height=300)# URL override sectionwith gr.Accordion("🔗 Image URL Override", open=False):image_url_input = gr.Textbox(label="Enter image URL directly",placeholder="https://example.com/image.jpg",info="Leave empty to use uploaded image")gr.Markdown("💡 *Using a URL will override the uploaded image*")# Current URL displaywith gr.Row():current_url_display = gr.Textbox(label="Current Image URL",value="No image selected",interactive=False,lines=2)shot_type = gr.Dropdown(choices=list(DEFAULT_PROMPTS.keys()),label="🎬 Shot Type",value="Cinematic Nature")prompt = gr.Textbox(label="📝 Custom Prompt",lines=3,value=DEFAULT_PROMPTS["Cinematic Nature"])shot_type.change(fn=update_prompt, inputs=shot_type, outputs=prompt)generate_btn = gr.Button("🚀 Generate Video", variant="primary", size="lg")with gr.Column():status = gr.Textbox(label="Status", lines=6)video_output = gr.Video(label="Generated Video")# Quick shot buttonsgr.Markdown("### Quick Shot Select")with gr.Row():gr.Button("🏔️ Nature").click(fn=lambda: "Cinematic Nature", outputs=shot_type)gr.Button("🌃 City").click(fn=lambda: "Urban Exploration", outputs=shot_type)gr.Button("🏎️ Action").click(fn=lambda: "Action Sequence", outputs=shot_type)gr.Button("🎨 Abstract").click(fn=lambda: "Abstract Art", outputs=shot_type)gr.Button("🦁 Wildlife").click(fn=lambda: "Wildlife Documentary", outputs=shot_type)gr.Button("⛷️ Sports").click(fn=lambda: "Sports Highlight", outputs=shot_type)# Update URL display when inputs changeimage_input.change(fn=update_url_display,inputs=[image_input, image_url_input],outputs=current_url_display)image_url_input.change(fn=update_url_display,inputs=[image_input, image_url_input],outputs=current_url_display)# Tab 2: Manual Polling17 unmodified lines18192021222314 unmodified lines383940414243129 unmodified lines17317417517617717817918018117 unmodified lines)# Fresh new promptsdef poll_via_json(task_id):"""Check io.json for task status"""14 unmodified linespassreturn Nonedef update_prompt(choice):return DEFAULT_PROMPTS.get(choice, "")129 unmodified linesreturn "No image selected"# Create the interfacewith gr.Blocks(title="BytePlus Video Gallery", theme=gr.themes.Soft()) as demo:)# Tab 2: Manual Polling
ups.py+1-184