MySafeCode commited on
Commit
61ecc21
·
verified ·
1 Parent(s): a7673c2

Delete ab.py

Browse files
Files changed (1) hide show
  1. ab.py +0 -287
ab.py DELETED
@@ -1,287 +0,0 @@
1
- import os
2
- import time
3
- import gradio as gr
4
- from byteplussdkarkruntime import Ark
5
- import httpx
6
- import socket
7
- import requests
8
-
9
- # Get API key from Hugging Face secret "Key"
10
- API_KEY = os.environ.get("Key", "")
11
-
12
- # Initialize client with proxy
13
- client = Ark(
14
- base_url="https://1hit.no/proxy/proxy.php",
15
- api_key=API_KEY,
16
- timeout=30.0,
17
- max_retries=3,
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 test_connection():
33
- """Test if we can reach the API before trying"""
34
- try:
35
- socket.gethostbyname('ark.ap-southeast.bytepluses.com')
36
- return True, "DNS resolved"
37
- except Exception as e:
38
- return False, f"DNS failed: {e}"
39
-
40
- def poll_via_json(task_id):
41
- """Fallback method: poll io.json for results"""
42
- json_url = "https://1hit.no/proxy/io.json"
43
- try:
44
- response = requests.get(json_url)
45
- data = response.json()
46
- if task_id in data:
47
- task_data = data[task_id]
48
- if task_data.get('status') == 'succeeded':
49
- return task_data.get('video_url')
50
- elif task_data.get('status') == 'failed':
51
- return None
52
- except:
53
- pass
54
- return None
55
-
56
- def generate_video(image_path, prompt_text, progress=gr.Progress()):
57
- """Generate video with robust error handling"""
58
-
59
- # Test connection first
60
- conn_ok, conn_msg = test_connection()
61
- if not conn_ok:
62
- yield f"❌ Connection Error: {conn_msg}. This might be a network restriction from Hugging Face.", None
63
- return
64
-
65
- if not API_KEY:
66
- yield "❌ API Key not configured. Please add 'Key' secret.", None
67
- return
68
-
69
- if image_path is None:
70
- yield "⚠️ Please upload an image first", None
71
- return
72
-
73
- try:
74
- progress(0, desc="Preparing image...")
75
-
76
- # Get HF temp URL
77
- image_url = f"/file={image_path}"
78
- print(f"Using image URL: {image_url}")
79
-
80
- yield "✅ Image ready! Creating video request...", None
81
-
82
- progress(0.2, desc="Creating request...")
83
-
84
- # Create task with timeout
85
- try:
86
- create_result = client.content_generation.tasks.create(
87
- model="seedance-1-5-pro-251215",
88
- content=[
89
- {
90
- "type": "text",
91
- "text": prompt_text
92
- },
93
- {
94
- "type": "image_url",
95
- "image_url": {
96
- "url": image_url
97
- }
98
- }
99
- ]
100
- )
101
- except Exception as e:
102
- error_str = str(e)
103
- if "Connection error" in error_str or "202602" in error_str:
104
- yield f"❌ Network Error: Cannot reach BytePlus API. This is likely a Hugging Face network restriction.", None
105
- else:
106
- yield f"❌ API Error: {error_str}", None
107
- return
108
-
109
- task_id = create_result.id
110
- print(f"Task created: {task_id}")
111
- yield f"✅ Task created: {task_id}", None
112
-
113
- progress(0.3, desc="Polling for results...")
114
-
115
- # Poll for results - TRY SDK FIRST, then fallback to JSON
116
- attempts = 0
117
- max_attempts = 120
118
- used_fallback = False
119
-
120
- while attempts < max_attempts:
121
- try:
122
- # Try SDK method first
123
- get_result = client.content_generation.tasks.get(task_id=task_id)
124
- status = get_result.status
125
-
126
- if status == "succeeded":
127
- progress(1.0, desc="Complete!")
128
- video_url = get_result.content.video_url if hasattr(get_result, 'content') else None
129
- print(f"Video URL: {video_url}")
130
- yield "✅ Video generated successfully!", video_url
131
- return
132
-
133
- elif status == "failed":
134
- error_msg = get_result.error if hasattr(get_result, 'error') else "Unknown error"
135
- yield f"❌ Failed: {error_msg}", None
136
- return
137
- else:
138
- progress(0.3 + (attempts/max_attempts)*0.7, desc=f"Status: {status}")
139
- yield f"⏳ Status: {status}... (attempt {attempts + 1})", None
140
- time.sleep(1)
141
- attempts += 1
142
-
143
- except Exception as e:
144
- # If SDK fails, try JSON fallback
145
- if not used_fallback:
146
- print("SDK polling failed, trying JSON fallback...")
147
- used_fallback = True
148
-
149
- video_url = poll_via_json(task_id)
150
- if video_url:
151
- yield "✅ Video generated successfully! (via JSON)", video_url
152
- return
153
- elif video_url is None:
154
- yield "❌ Task failed (via JSON)", None
155
- return
156
- else:
157
- yield f"⏳ Status: processing... (JSON fallback)", None
158
- time.sleep(5)
159
- attempts += 1
160
-
161
- yield "⏰ Timeout after 2 minutes", None
162
-
163
- except Exception as e:
164
- print(f"Error: {e}")
165
- if "Connection error" in str(e):
166
- yield "❌ Connection Error: Cannot reach BytePlus API. This is likely a Hugging Face network restriction. Try running locally instead.", None
167
- else:
168
- yield f"❌ Error: {str(e)}", None
169
-
170
- def update_prompt(choice):
171
- """Update prompt when shot type changes"""
172
- return DEFAULT_PROMPTS.get(choice, "")
173
-
174
- # Interface
175
- with gr.Blocks(title="BytePlus Video Generator", theme=gr.themes.Soft()) as demo:
176
-
177
- gr.Markdown("""
178
- # 🎥 BytePlus Video Generator
179
- Upload an image and choose a shot type to generate a stunning video.
180
- """)
181
-
182
- # Status row
183
- with gr.Row():
184
- if API_KEY:
185
- gr.Markdown("✅ **API Key:** Configured")
186
- else:
187
- gr.Markdown("❌ **API Key:** Not configured - please add 'Key' secret")
188
-
189
- # Connection test button
190
- with gr.Row():
191
- test_btn = gr.Button("🔌 Test Connection", size="sm")
192
- test_result = gr.Textbox(label="Connection Test", lines=1)
193
-
194
- def run_connection_test():
195
- ok, msg = test_connection()
196
- return f"{'✅' if ok else '❌'} {msg}"
197
-
198
- test_btn.click(fn=run_connection_test, outputs=test_result)
199
-
200
- gr.Markdown("---")
201
-
202
- with gr.Row():
203
- with gr.Column():
204
- # Image upload
205
- image_input = gr.Image(
206
- label="Upload Starting Image",
207
- type="filepath",
208
- height=300
209
- )
210
-
211
- # Shot type dropdown
212
- shot_type = gr.Dropdown(
213
- choices=list(DEFAULT_PROMPTS.keys()),
214
- label="🎬 Shot Type",
215
- value="Cinematic Nature"
216
- )
217
-
218
- # Custom prompt
219
- prompt = gr.Textbox(
220
- label="📝 Custom Prompt (override)",
221
- lines=3,
222
- placeholder="Or write your own prompt here...",
223
- value=DEFAULT_PROMPTS["Cinematic Nature"]
224
- )
225
-
226
- # Update prompt when shot type changes
227
- shot_type.change(
228
- fn=update_prompt,
229
- inputs=shot_type,
230
- outputs=prompt
231
- )
232
-
233
- # Generate button
234
- generate_btn = gr.Button("🚀 Generate Video", variant="primary", size="lg")
235
-
236
- with gr.Column():
237
- # Status
238
- status = gr.Textbox(
239
- label="Status",
240
- lines=5,
241
- interactive=False
242
- )
243
-
244
- # Video output
245
- video_output = gr.Video(
246
- label="Generated Video",
247
- interactive=False
248
- )
249
-
250
- # Example shots as quick buttons
251
- gr.Markdown("---")
252
- gr.Markdown("### Quick Shot Select")
253
- with gr.Row():
254
- gr.Button("🏔️ Nature").click(
255
- fn=lambda: "Cinematic Nature",
256
- outputs=shot_type
257
- )
258
- gr.Button("🌃 City").click(
259
- fn=lambda: "Urban Exploration",
260
- outputs=shot_type
261
- )
262
- gr.Button("🏎️ Action").click(
263
- fn=lambda: "Action Sequence",
264
- outputs=shot_type
265
- )
266
- gr.Button("🎨 Abstract").click(
267
- fn=lambda: "Abstract Art",
268
- outputs=shot_type
269
- )
270
- gr.Button("🦁 Wildlife").click(
271
- fn=lambda: "Wildlife Documentary",
272
- outputs=shot_type
273
- )
274
- gr.Button("⛷️ Sports").click(
275
- fn=lambda: "Sports Highlight",
276
- outputs=shot_type
277
- )
278
-
279
- # Connect generate button
280
- generate_event = generate_btn.click(
281
- fn=generate_video,
282
- inputs=[image_input, prompt],
283
- outputs=[status, video_output]
284
- )
285
-
286
- if __name__ == "__main__":
287
- demo.launch(server_name="0.0.0.0")