MySafeCode commited on
Commit
0cb2d3d
·
verified ·
1 Parent(s): a44b51d

Update a.py

Browse files
Files changed (1) hide show
  1. a.py +184 -55
a.py CHANGED
@@ -1,66 +1,195 @@
1
- import gradio as gr
2
- import requests
3
  import os
 
 
4
  from byteplussdkarkruntime import Ark
 
5
 
6
- API_KEY = os.environ.get("Key", "")
 
 
7
 
8
- def test_both(prompt_text):
9
- results = []
10
-
11
- # TEST 1: Direct BytePlus URL
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  try:
13
- client_direct = Ark(
14
- base_url="https://ark.ap-southeast.bytepluses.com/api/v3",
15
- api_key=API_KEY,
16
- timeout=10
17
- )
18
- result_direct = client_direct.content_generation.tasks.create(
19
- model="seedance-1-5-pro-251215",
20
- content=[{"type": "text", "text": prompt_text}]
21
- )
22
- results.append(f"✅ DIRECT: Task created {result_direct.id}")
23
- except Exception as e:
24
- results.append(f"❌ DIRECT: {str(e)[:100]}")
 
 
25
 
26
- # TEST 2: Proxy URL
27
- try:
28
- client_proxy = Ark(
29
- base_url="https://1hit.no/proxy/proxy.php",
30
- api_key=API_KEY,
31
- timeout=10
32
- )
33
- result_proxy = client_proxy.content_generation.tasks.create(
34
- model="seedance-1-5-pro-251215",
35
- content=[{"type": "text", "text": prompt_text}]
36
- )
37
- results.append(f"✅ PROXY: Task created {result_proxy.id}")
38
- except Exception as e:
39
- results.append(f"❌ PROXY: {str(e)[:100]}")
40
 
41
- # TEST 3: Direct requests (no SDK)
42
  try:
43
- url = "https://ark.ap-southeast.bytepluses.com/api/v3/contents/generations/tasks"
44
- headers = {
45
- "Content-Type": "application/json",
46
- "Authorization": f"Bearer {API_KEY}"
47
- }
48
- data = {
49
- "model": "seedance-1-5-pro-251215",
50
- "content": [{"type": "text", "text": prompt_text}]
51
- }
52
- r = requests.post(url, headers=headers, json=data, timeout=10)
53
- results.append(f"✅ REQUESTS: Status {r.status_code}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  except Exception as e:
55
- results.append(f"❌ REQUESTS: {str(e)[:100]}")
56
-
57
- return "\n\n".join(results)
58
 
59
- with gr.Blocks() as demo:
60
- gr.Markdown("# BytePlus Connection Test")
61
- prompt = gr.Textbox("test", label="Prompt")
62
- btn = gr.Button("Test All")
63
- output = gr.Textbox(label="Results", lines=10)
64
- btn.click(fn=test_both, inputs=prompt, outputs=output)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
 
66
- demo.launch()
 
 
 
 
1
  import os
2
+ import time
3
+ import gradio as gr
4
  from byteplussdkarkruntime import Ark
5
+ import requests
6
 
7
+ # Get API key from Hugging Face secret "Key" and CLEAN it
8
+ API_KEY = os.environ.get("Key", "").strip() # The .strip() fixes the newline issue!
9
+ print(f"✅ Key loaded, length: {len(API_KEY)}")
10
 
11
+ # Initialize client with proxy
12
+ client = Ark(
13
+ base_url="https://1hit.no/proxy/proxy.php", # Using proxy
14
+ api_key=API_KEY,
15
+ timeout=30.0,
16
+ max_retries=3,
17
+ )
18
+
19
+ # Fresh new prompts
20
+ DEFAULT_PROMPTS = {
21
+ "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",
22
+ "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",
23
+ "Action Sequence": "High-speed drone chasing a sports car through a winding coastal road, dramatic cliffside views, action movie style --duration 5 --camerafixed false",
24
+ "Abstract Art": "Surreal drone flight through floating geometric shapes in a dreamlike void, pastel colors, ethereal atmosphere --duration 5 --camerafixed false",
25
+ "Wildlife Documentary": "Drone following a herd of elephants across the African savanna at sunset, National Geographic style, majestic wildlife cinematography --duration 5 --camerafixed false",
26
+ "Sports Highlight": "Drone racing alongside professional skiers carving through fresh powder in the Alps, high-energy sports broadcast style --duration 5 --camerafixed false",
27
+ "Beach Paradise": "Drone gliding over turquoise waters and white sand beaches, palm trees swaying, tropical paradise aerial view --duration 5 --camerafixed false",
28
+ "Ancient Temple": "Drone circling around ancient Angkor Wat temple at dawn, mystical atmosphere, historical documentary style --duration 5 --camerafixed false"
29
+ }
30
+
31
+ def poll_via_json(task_id):
32
+ """Fallback method: poll io.json for results"""
33
+ json_url = "https://1hit.no/proxy/io.json"
34
  try:
35
+ response = requests.get(json_url)
36
+ data = response.json()
37
+ if task_id in data:
38
+ task_data = data[task_id]
39
+ if task_data.get('status') == 'succeeded':
40
+ return task_data.get('video_url')
41
+ elif task_data.get('status') == 'failed':
42
+ return None
43
+ except:
44
+ pass
45
+ return None
46
+
47
+ def generate_video(image_path, prompt_text, progress=gr.Progress()):
48
+ """Generate video with all features"""
49
 
50
+ if not API_KEY:
51
+ yield "❌ API Key not configured. Please add 'Key' secret.", None
52
+ return
53
+
54
+ if image_path is None:
55
+ yield "⚠️ Please upload an image first", None
56
+ return
 
 
 
 
 
 
 
57
 
 
58
  try:
59
+ progress(0, desc="Preparing image...")
60
+
61
+ # Get HF temp URL
62
+ image_url = f"/file={image_path}"
63
+ print(f"Using image URL: {image_url}")
64
+
65
+ yield " Image ready! Creating video request...", None
66
+
67
+ progress(0.2, desc="Creating request...")
68
+
69
+ # Create task
70
+ try:
71
+ create_result = client.content_generation.tasks.create(
72
+ model="seedance-1-5-pro-251215",
73
+ content=[
74
+ {"type": "text", "text": prompt_text},
75
+ {"type": "image_url", "image_url": {"url": image_url}}
76
+ ]
77
+ )
78
+ except Exception as e:
79
+ yield f"❌ API Error: {str(e)}", None
80
+ return
81
+
82
+ task_id = create_result.id
83
+ print(f"Task created: {task_id}")
84
+ yield f"✅ Task created: {task_id}", None
85
+
86
+ progress(0.3, desc="Polling for results...")
87
+
88
+ # Poll for results
89
+ attempts = 0
90
+ max_attempts = 120
91
+ used_fallback = False
92
+
93
+ while attempts < max_attempts:
94
+ try:
95
+ get_result = client.content_generation.tasks.get(task_id=task_id)
96
+ status = get_result.status
97
+
98
+ if status == "succeeded":
99
+ progress(1.0, desc="Complete!")
100
+ video_url = get_result.content.video_url if hasattr(get_result, 'content') else None
101
+ yield "✅ Video generated successfully!", video_url
102
+ return
103
+
104
+ elif status == "failed":
105
+ error_msg = get_result.error if hasattr(get_result, 'error') else "Unknown error"
106
+ yield f"❌ Failed: {error_msg}", None
107
+ return
108
+ else:
109
+ progress(0.3 + (attempts/max_attempts)*0.7, desc=f"Status: {status}")
110
+ yield f"⏳ Status: {status}... (attempt {attempts + 1})", None
111
+ time.sleep(1)
112
+ attempts += 1
113
+
114
+ except Exception as e:
115
+ if not used_fallback:
116
+ print("SDK polling failed, trying JSON fallback...")
117
+ used_fallback = True
118
+
119
+ video_url = poll_via_json(task_id)
120
+ if video_url:
121
+ yield "✅ Video generated successfully! (via JSON)", video_url
122
+ return
123
+ elif video_url is None:
124
+ yield "❌ Task failed (via JSON)", None
125
+ return
126
+ else:
127
+ yield f"⏳ Status: processing... (JSON fallback)", None
128
+ time.sleep(5)
129
+ attempts += 1
130
+
131
+ yield "⏰ Timeout after 2 minutes", None
132
+
133
  except Exception as e:
134
+ yield f"❌ Error: {str(e)}", None
 
 
135
 
136
+ def update_prompt(choice):
137
+ return DEFAULT_PROMPTS.get(choice, "")
138
+
139
+ # Interface
140
+ with gr.Blocks(title="BytePlus Video Generator", theme=gr.themes.Soft()) as demo:
141
+
142
+ gr.Markdown("# 🎥 BytePlus Video Generator")
143
+
144
+ with gr.Row():
145
+ if API_KEY:
146
+ gr.Markdown("✅ **API Key:** Configured")
147
+ else:
148
+ gr.Markdown("❌ **API Key:** Not configured - please add 'Key' secret")
149
+
150
+ with gr.Row():
151
+ with gr.Column():
152
+ image_input = gr.Image(
153
+ label="Upload Starting Image",
154
+ type="filepath",
155
+ height=300
156
+ )
157
+
158
+ shot_type = gr.Dropdown(
159
+ choices=list(DEFAULT_PROMPTS.keys()),
160
+ label="🎬 Shot Type",
161
+ value="Cinematic Nature"
162
+ )
163
+
164
+ prompt = gr.Textbox(
165
+ label="📝 Custom Prompt",
166
+ lines=3,
167
+ value=DEFAULT_PROMPTS["Cinematic Nature"]
168
+ )
169
+
170
+ shot_type.change(fn=update_prompt, inputs=shot_type, outputs=prompt)
171
+
172
+ generate_btn = gr.Button("🚀 Generate Video", variant="primary", size="lg")
173
+
174
+ with gr.Column():
175
+ status = gr.Textbox(label="Status", lines=5)
176
+ video_output = gr.Video(label="Generated Video")
177
+
178
+ # Quick shot buttons
179
+ gr.Markdown("### Quick Shot Select")
180
+ with gr.Row():
181
+ gr.Button("🏔️ Nature").click(fn=lambda: "Cinematic Nature", outputs=shot_type)
182
+ gr.Button("🌃 City").click(fn=lambda: "Urban Exploration", outputs=shot_type)
183
+ gr.Button("🏎️ Action").click(fn=lambda: "Action Sequence", outputs=shot_type)
184
+ gr.Button("🎨 Abstract").click(fn=lambda: "Abstract Art", outputs=shot_type)
185
+ gr.Button("🦁 Wildlife").click(fn=lambda: "Wildlife Documentary", outputs=shot_type)
186
+ gr.Button("⛷️ Sports").click(fn=lambda: "Sports Highlight", outputs=shot_type)
187
+
188
+ generate_btn.click(
189
+ fn=generate_video,
190
+ inputs=[image_input, prompt],
191
+ outputs=[status, video_output]
192
+ )
193
 
194
+ if __name__ == "__main__":
195
+ demo.launch(server_name="0.0.0.0")