MySafeCode commited on
Commit
8abfc99
·
verified ·
1 Parent(s): f3cc2f8

Delete a.py

Browse files
Files changed (1) hide show
  1. a.py +0 -196
a.py DELETED
@@ -1,196 +0,0 @@
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
- image_url = "https://ark-doc.tos-ap-southeast-1.bytepluses.com/seepro_i2v%20.png"
64
- print(f"Using image URL: {image_url}")
65
-
66
- yield "✅ Image ready! Creating video request...", None
67
-
68
- progress(0.2, desc="Creating request...")
69
-
70
- # Create task
71
- try:
72
- create_result = client.content_generation.tasks.create(
73
- model="seedance-1-5-pro-251215",
74
- content=[
75
- {"type": "text", "text": prompt_text},
76
- {"type": "image_url", "image_url": {"url": image_url}}
77
- ]
78
- )
79
- except Exception as e:
80
- yield f"❌ API Error: {str(e)}", None
81
- return
82
-
83
- task_id = create_result.id
84
- print(f"Task created: {task_id}")
85
- yield f"✅ Task created: {task_id}", None
86
-
87
- progress(0.3, desc="Polling for results...")
88
-
89
- # Poll for results
90
- attempts = 0
91
- max_attempts = 120
92
- used_fallback = False
93
-
94
- while attempts < max_attempts:
95
- try:
96
- get_result = client.content_generation.tasks.get(task_id=task_id)
97
- status = get_result.status
98
-
99
- if status == "succeeded":
100
- progress(1.0, desc="Complete!")
101
- video_url = get_result.content.video_url if hasattr(get_result, 'content') else None
102
- yield "✅ Video generated successfully!", video_url
103
- return
104
-
105
- elif status == "failed":
106
- error_msg = get_result.error if hasattr(get_result, 'error') else "Unknown error"
107
- yield f"❌ Failed: {error_msg}", None
108
- return
109
- else:
110
- progress(0.3 + (attempts/max_attempts)*0.7, desc=f"Status: {status}")
111
- yield f"⏳ Status: {status}... (attempt {attempts + 1})", None
112
- time.sleep(1)
113
- attempts += 1
114
-
115
- except Exception as e:
116
- if not used_fallback:
117
- print("SDK polling failed, trying JSON fallback...")
118
- used_fallback = True
119
-
120
- video_url = poll_via_json(task_id)
121
- if video_url:
122
- yield "✅ Video generated successfully! (via JSON)", video_url
123
- return
124
- elif video_url is None:
125
- yield "❌ Task failed (via JSON)", None
126
- return
127
- else:
128
- yield f"⏳ Status: processing... (JSON fallback)", None
129
- time.sleep(5)
130
- attempts += 1
131
-
132
- yield "⏰ Timeout after 2 minutes", None
133
-
134
- except Exception as e:
135
- yield f"❌ Error: {str(e)}", None
136
-
137
- def update_prompt(choice):
138
- return DEFAULT_PROMPTS.get(choice, "")
139
-
140
- # Interface
141
- with gr.Blocks(title="BytePlus Video Generator", theme=gr.themes.Soft()) as demo:
142
-
143
- gr.Markdown("# 🎥 BytePlus Video Generator")
144
-
145
- with gr.Row():
146
- if API_KEY:
147
- gr.Markdown("✅ **API Key:** Configured")
148
- else:
149
- gr.Markdown("❌ **API Key:** Not configured - please add 'Key' secret")
150
-
151
- with gr.Row():
152
- with gr.Column():
153
- image_input = gr.Image(
154
- label="Upload Starting Image",
155
- type="filepath",
156
- height=300
157
- )
158
-
159
- shot_type = gr.Dropdown(
160
- choices=list(DEFAULT_PROMPTS.keys()),
161
- label="🎬 Shot Type",
162
- value="Cinematic Nature"
163
- )
164
-
165
- prompt = gr.Textbox(
166
- label="📝 Custom Prompt",
167
- lines=3,
168
- value=DEFAULT_PROMPTS["Cinematic Nature"]
169
- )
170
-
171
- shot_type.change(fn=update_prompt, inputs=shot_type, outputs=prompt)
172
-
173
- generate_btn = gr.Button("🚀 Generate Video", variant="primary", size="lg")
174
-
175
- with gr.Column():
176
- status = gr.Textbox(label="Status", lines=5)
177
- video_output = gr.Video(label="Generated Video")
178
-
179
- # Quick shot buttons
180
- gr.Markdown("### Quick Shot Select")
181
- with gr.Row():
182
- gr.Button("🏔️ Nature").click(fn=lambda: "Cinematic Nature", outputs=shot_type)
183
- gr.Button("🌃 City").click(fn=lambda: "Urban Exploration", outputs=shot_type)
184
- gr.Button("🏎️ Action").click(fn=lambda: "Action Sequence", outputs=shot_type)
185
- gr.Button("🎨 Abstract").click(fn=lambda: "Abstract Art", outputs=shot_type)
186
- gr.Button("🦁 Wildlife").click(fn=lambda: "Wildlife Documentary", outputs=shot_type)
187
- gr.Button("⛷️ Sports").click(fn=lambda: "Sports Highlight", outputs=shot_type)
188
-
189
- generate_btn.click(
190
- fn=generate_video,
191
- inputs=[image_input, prompt],
192
- outputs=[status, video_output]
193
- )
194
-
195
- if __name__ == "__main__":
196
- demo.launch(server_name="0.0.0.0")