MySafeCode commited on
Commit
6a7f147
·
verified ·
1 Parent(s): 73367f6

Create a.py

Browse files
Files changed (1) hide show
  1. a.py +181 -0
a.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import time
4
+ import logging
5
+ import socket
6
+ import requests
7
+ from byteplussdkarkruntime import Ark
8
+ import byteplussdkcore
9
+
10
+ # Set up logging
11
+ logging.basicConfig(level=logging.INFO)
12
+ logger = logging.getLogger(__name__)
13
+
14
+ # Get API key from environment variable "key"
15
+ API_KEY = os.environ.get("key", "")
16
+ logger.info(f"API Key loaded: {'Yes' if API_KEY else 'No'}")
17
+ logger.info(f"Key length: {len(API_KEY)}")
18
+ if API_KEY:
19
+ logger.info(f"First 4 chars: {API_KEY[:4]}")
20
+
21
+ # Test basic connectivity first
22
+ def test_connectivity():
23
+ """Test if we can reach the API server"""
24
+ try:
25
+ # Test DNS resolution
26
+ ip = socket.gethostbyname('ark.ap-southeast.bytepluses.com')
27
+ logger.info(f"✅ DNS resolved: {ip}")
28
+
29
+ # Test basic HTTPS connection
30
+ r = requests.get("https://ark.ap-southeast.bytepluses.com", timeout=5)
31
+ logger.info(f"✅ Base URL reachable (status: {r.status_code})")
32
+ return True
33
+ except Exception as e:
34
+ logger.error(f"❌ Connection test failed: {e}")
35
+ return False
36
+
37
+ # Run connection test on startup
38
+ connectivity_ok = test_connectivity()
39
+
40
+ # Configure SDK
41
+ try:
42
+ configuration = byteplussdkcore.Configuration()
43
+ configuration.client_side_validation = True
44
+ configuration.schema = "http"
45
+ configuration.debug = True # Enable debug logging
46
+ configuration.logger_file = "sdk.log"
47
+ byteplussdkcore.Configuration.set_default(configuration)
48
+ logger.info("✅ SDK configured")
49
+ except Exception as e:
50
+ logger.error(f"❌ SDK config failed: {e}")
51
+
52
+ # Initialize client WITH THE KEY
53
+ try:
54
+ client = Ark(
55
+ base_url="https://ark.ap-southeast.bytepluses.com/api/v3",
56
+ api_key=API_KEY, # The key is here!
57
+ )
58
+ logger.info("✅ Client initialized with API key")
59
+ except Exception as e:
60
+ logger.error(f"❌ Client init failed: {e}")
61
+ client = None
62
+
63
+ def generate_video(prompt_text, image_url, progress=gr.Progress()):
64
+ """Generate video with detailed debugging"""
65
+
66
+ if not API_KEY:
67
+ yield "❌ No API key found in environment variable 'key'", None
68
+ return
69
+
70
+ if not client:
71
+ yield "❌ Client not initialized", None
72
+ return
73
+
74
+ if not connectivity_ok:
75
+ yield "❌ Cannot reach API server", None
76
+ return
77
+
78
+ try:
79
+ progress(0, desc="Creating task...")
80
+ logger.info("Creating task...")
81
+
82
+ # Log the request details (without exposing full key)
83
+ logger.info(f"Prompt: {prompt_text[:50]}...")
84
+ logger.info(f"Image URL: {image_url}")
85
+ logger.info(f"Using API key: {API_KEY[:4]}...{API_KEY[-4:]}")
86
+
87
+ create_result = client.content_generation.tasks.create(
88
+ model="seedance-1-5-pro-251215",
89
+ content=[
90
+ {
91
+ "type": "text",
92
+ "text": prompt_text
93
+ },
94
+ {
95
+ "type": "image_url",
96
+ "image_url": {
97
+ "url": image_url
98
+ }
99
+ }
100
+ ]
101
+ )
102
+
103
+ task_id = create_result.id
104
+ logger.info(f"✅ Task created: {task_id}")
105
+ yield f"Task created: {task_id}", None
106
+
107
+ progress(0.3, desc="Polling...")
108
+
109
+ # Poll for results
110
+ attempts = 0
111
+ while attempts < 60:
112
+ try:
113
+ get_result = client.content_generation.tasks.get(task_id=task_id)
114
+ status = get_result.status
115
+ logger.info(f"Status: {status}")
116
+
117
+ if status == "succeeded":
118
+ progress(1.0, desc="Complete!")
119
+ video_url = get_result.output[0].get('video_url') if get_result.output else None
120
+ yield "Success!", video_url
121
+ return
122
+ elif status == "failed":
123
+ error_msg = get_result.error if hasattr(get_result, 'error') else "Unknown error"
124
+ yield f"Failed: {error_msg}", None
125
+ return
126
+ else:
127
+ progress(0.3 + (attempts/60)*0.7, desc=f"Status: {status}")
128
+ yield f"Status: {status}...", None
129
+ time.sleep(1)
130
+ attempts += 1
131
+ except Exception as e:
132
+ logger.error(f"Polling error: {e}")
133
+ yield f"Polling error: {e}", None
134
+ return
135
+
136
+ yield "Timeout", None
137
+
138
+ except Exception as e:
139
+ logger.error(f"❌ Error: {e}", exc_info=True)
140
+ yield f"Error: {str(e)}", None
141
+
142
+ # Simple interface
143
+ with gr.Blocks() as demo:
144
+ gr.Markdown("# BytePlus Video Generator")
145
+
146
+ # Show connection and key status
147
+ status_lines = []
148
+ status_lines.append(f"🔑 API Key: {'✅ Loaded' if API_KEY else '❌ Missing'}")
149
+ if API_KEY:
150
+ status_lines.append(f" Length: {len(API_KEY)} chars")
151
+ status_lines.append(f" Starts with: {API_KEY[:4]}")
152
+ status_lines.append(f"🌐 API Server: {'✅ Reachable' if connectivity_ok else '❌ Unreachable'}")
153
+ status_lines.append(f"📦 SDK Client: {'✅ Initialized' if client else '❌ Failed'}")
154
+
155
+ gr.Markdown("\n".join(status_lines))
156
+
157
+ with gr.Row():
158
+ with gr.Column():
159
+ prompt = gr.Textbox(
160
+ label="Prompt",
161
+ lines=3,
162
+ value="At breakneck speed, drones fly through obstacles --duration 5 --camerafixed false"
163
+ )
164
+ image_url = gr.Textbox(
165
+ label="Image URL",
166
+ value="https://ark-doc.tos-ap-southeast-1.bytepluses.com/seepro_i2v%20.png"
167
+ )
168
+ btn = gr.Button("Generate", variant="primary")
169
+
170
+ with gr.Column():
171
+ status = gr.Textbox(label="Status", lines=8)
172
+ video = gr.Video(label="Generated Video")
173
+
174
+ btn.click(
175
+ fn=generate_video,
176
+ inputs=[prompt, image_url],
177
+ outputs=[status, video]
178
+ )
179
+
180
+ if __name__ == "__main__":
181
+ demo.launch(server_name="0.0.0.0")