MySafeCode commited on
Commit
72f6ebe
·
verified ·
1 Parent(s): f72d09f

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +171 -0
app.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import time
4
+ import json
5
+ from PIL import Image
6
+ import logging
7
+ import sys
8
+
9
+ # Set up logging
10
+ logging.basicConfig(level=logging.INFO)
11
+ logger = logging.getLogger(__name__)
12
+
13
+ # Print Gradio version for debugging
14
+ logger.info(f"Gradio version: {gr.__version__}")
15
+
16
+ # Import BytePlus SDK
17
+ try:
18
+ import byteplussdkcore
19
+ from byteplussdkarkruntime import Ark
20
+ SDK_AVAILABLE = True
21
+ logger.info("✅ BytePlus SDK loaded successfully")
22
+ except ImportError as e:
23
+ SDK_AVAILABLE = False
24
+ logger.warning(f"⚠️ BytePlus SDK not available: {e}")
25
+
26
+ def generate_video(api_key, prompt_text, image_url, model_id, progress=gr.Progress()):
27
+ """Generate video using the BytePlus SDK"""
28
+
29
+ if not api_key or api_key == "key":
30
+ yield "⚠️ Please enter your actual BytePlus API key (the 'key' is just a placeholder)", None
31
+ return
32
+
33
+ if not SDK_AVAILABLE:
34
+ yield "❌ BytePlus SDK not available. Please check installation of byteplus-python-sdk-v2", None
35
+ return
36
+
37
+ try:
38
+ progress(0, desc="Initializing SDK...")
39
+
40
+ # Set environment variable
41
+ os.environ["ARK_API_KEY"] = api_key
42
+
43
+ # Initialize client
44
+ client = Ark(
45
+ base_url="https://ark.ap-southeast.bytepluses.com/api/v3",
46
+ api_key=os.environ.get("ARK_API_KEY"),
47
+ )
48
+
49
+ progress(0.1, desc="Creating video generation request...")
50
+ logger.info("🚀 Creating video generation request...")
51
+
52
+ # Create task
53
+ create_result = client.content_generation.tasks.create(
54
+ model=model_id,
55
+ content=[
56
+ {
57
+ "type": "text",
58
+ "text": prompt_text
59
+ },
60
+ {
61
+ "type": "image_url",
62
+ "image_url": {
63
+ "url": image_url
64
+ }
65
+ }
66
+ ]
67
+ )
68
+
69
+ task_id = create_result.id
70
+ logger.info(f"📋 Task ID: {task_id}")
71
+
72
+ yield f"⏳ Task created with ID: {task_id}. Waiting for completion...", None
73
+
74
+ # Polling
75
+ max_attempts = 60
76
+ attempts = 0
77
+
78
+ while attempts < max_attempts:
79
+ progress(0.1 + (attempts / max_attempts) * 0.8,
80
+ desc=f"Polling status: {attempts + 1}/{max_attempts}")
81
+
82
+ get_result = client.content_generation.tasks.get(task_id=task_id)
83
+ status = get_result.status
84
+
85
+ if status == "succeeded":
86
+ progress(1.0, desc="Complete!")
87
+ logger.info("✅ Task succeeded!")
88
+
89
+ # Extract video URL
90
+ video_url = None
91
+ if hasattr(get_result, 'output') and get_result.output:
92
+ if isinstance(get_result.output, list) and len(get_result.output) > 0:
93
+ video_url = get_result.output[0].get('video_url')
94
+ elif hasattr(get_result.output, 'video_url'):
95
+ video_url = get_result.output.video_url
96
+ elif isinstance(get_result.output, dict):
97
+ video_url = get_result.output.get('video_url')
98
+
99
+ if video_url:
100
+ yield f"✅ Video generated successfully!", video_url
101
+ else:
102
+ yield f"✅ Task completed but no video URL in response", None
103
+ break
104
+
105
+ elif status == "failed":
106
+ error_msg = get_result.error if hasattr(get_result, 'error') else "Unknown error"
107
+ yield f"❌ Task failed: {error_msg}", None
108
+ break
109
+ else:
110
+ yield f"⏳ Current status: {status}, waiting... ({attempts + 1}/{max_attempts})", None
111
+ time.sleep(1)
112
+ attempts += 1
113
+
114
+ if attempts >= max_attempts:
115
+ yield "⏰ Timeout: Task took too long to complete. Please try again.", None
116
+
117
+ except Exception as e:
118
+ logger.error(f"Error: {e}")
119
+ yield f"❌ Error: {str(e)}", None
120
+
121
+ # Simple, clean UI
122
+ with gr.Blocks(title="BytePlus Video Generator", theme=gr.themes.Soft()) as demo:
123
+ gr.Markdown("""
124
+ # 🎥 BytePlus Video Generator
125
+ Generate videos from images and text prompts
126
+ """)
127
+
128
+ with gr.Row():
129
+ with gr.Column():
130
+ api_key = gr.Textbox(
131
+ label="🔑 API Key",
132
+ type="password",
133
+ placeholder="Enter your BytePlus API key",
134
+ value="key"
135
+ )
136
+
137
+ model_id = gr.Textbox(
138
+ label="🤖 Model ID",
139
+ value="seedance-1-5-pro-251215"
140
+ )
141
+
142
+ image_url = gr.Textbox(
143
+ label="🖼️ Image URL",
144
+ value="https://ark-doc.tos-ap-southeast-1.bytepluses.com/seepro_i2v%20.png"
145
+ )
146
+
147
+ prompt = gr.Textbox(
148
+ label="📝 Prompt",
149
+ lines=3,
150
+ value="At breakneck speed, drones thread through intricate obstacles --duration 5 --camerafixed false"
151
+ )
152
+
153
+ generate_btn = gr.Button("🚀 Generate", variant="primary")
154
+
155
+ with gr.Column():
156
+ status = gr.Textbox(label="Status", lines=3)
157
+ video = gr.Video(label="Generated Video")
158
+ video_url = gr.Textbox(label="Video URL")
159
+
160
+ generate_btn.click(
161
+ fn=generate_video,
162
+ inputs=[api_key, prompt, image_url, model_id],
163
+ outputs=[status, video]
164
+ ).then(
165
+ fn=lambda url: url if url else "",
166
+ inputs=[video],
167
+ outputs=[video_url]
168
+ )
169
+
170
+ if __name__ == "__main__":
171
+ demo.launch()