MySafeCode commited on
Commit
9643953
·
verified ·
1 Parent(s): 70ce8b4

Update a.py

Browse files
Files changed (1) hide show
  1. a.py +45 -88
a.py CHANGED
@@ -2,8 +2,7 @@ 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
 
@@ -11,78 +10,44 @@ import byteplussdkcore
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",
@@ -104,55 +69,47 @@ def generate_video(prompt_text, image_url, progress=gr.Progress()):
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():
@@ -165,13 +122,13 @@ with gr.Blocks() as demo:
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]
 
2
  import os
3
  import time
4
  import logging
5
+ import httpx
 
6
  from byteplussdkarkruntime import Ark
7
  import byteplussdkcore
8
 
 
10
  logging.basicConfig(level=logging.INFO)
11
  logger = logging.getLogger(__name__)
12
 
13
+ # Get API key from environment variable "Key"
14
  API_KEY = os.environ.get("Key", "")
15
  logger.info(f"API Key loaded: {'Yes' if API_KEY else 'No'}")
16
  logger.info(f"Key length: {len(API_KEY)}")
 
 
17
 
18
+ # Configure SDK with HTTP scheme (as per the non-compatible upgrade notice)
19
+ configuration = byteplussdkcore.Configuration()
20
+ configuration.client_side_validation = True
21
+ configuration.schema = "http" # Explicitly use HTTP as per notice
22
+ configuration.debug = False
23
+ configuration.logger_file = "sdk.log"
24
+ byteplussdkcore.Configuration.set_default(configuration)
 
 
 
 
 
 
 
 
 
 
 
25
 
26
+ # Initialize client with timeout settings and proxy disable
27
+ client = Ark(
28
+ base_url="https://ark.ap-southeast.bytepluses.com/api/v3",
29
+ api_key=API_KEY,
30
+ timeout=1800, # 30 minute timeout as recommended
31
+ max_retries=3,
32
+ http_client=httpx.Client(
33
+ proxies={
34
+ "http://": None, # Disable proxy
35
+ "https://": None, # Disable proxy
36
+ },
37
+ timeout=httpx.Timeout(1800.0),
 
 
 
 
 
38
  )
39
+ )
 
 
 
40
 
41
  def generate_video(prompt_text, image_url, progress=gr.Progress()):
42
+ """Generate video with proper timeout settings"""
43
 
44
  if not API_KEY:
45
+ yield "❌ No API key found in environment variable 'Key'", None
 
 
 
 
 
 
 
 
46
  return
47
 
48
  try:
49
  progress(0, desc="Creating task...")
50
+ logger.info("Creating video generation task...")
 
 
 
 
 
51
 
52
  create_result = client.content_generation.tasks.create(
53
  model="seedance-1-5-pro-251215",
 
69
  logger.info(f"✅ Task created: {task_id}")
70
  yield f"Task created: {task_id}", None
71
 
72
+ progress(0.3, desc="Polling for results...")
73
 
74
  # Poll for results
75
  attempts = 0
76
+ max_attempts = 180 # 3 minutes max
77
+
78
+ while attempts < max_attempts:
79
  try:
80
  get_result = client.content_generation.tasks.get(task_id=task_id)
81
  status = get_result.status
 
82
 
83
  if status == "succeeded":
84
  progress(1.0, desc="Complete!")
85
  video_url = get_result.output[0].get('video_url') if get_result.output else None
86
+ yield "Success!", video_url
87
  return
88
  elif status == "failed":
89
  error_msg = get_result.error if hasattr(get_result, 'error') else "Unknown error"
90
+ yield f"Failed: {error_msg}", None
91
  return
92
  else:
93
+ progress(0.3 + (attempts/max_attempts)*0.7, desc=f"Status: {status}")
94
+ yield f"Status: {status}...", None
95
  time.sleep(1)
96
  attempts += 1
97
+
98
  except Exception as e:
99
  logger.error(f"Polling error: {e}")
100
+ yield f"⚠️ Polling error: {e}", None
101
+ time.sleep(2)
102
+ attempts += 1
103
 
104
+ yield "Timeout after 3 minutes", None
105
 
106
  except Exception as e:
107
+ logger.error(f"❌ Error: {e}")
108
+ yield f"Error: {str(e)}", None
109
 
110
  # Simple interface
111
+ with gr.Blocks(title="BytePlus Video Generator") as demo:
112
+ gr.Markdown("# 🎥 BytePlus Video Generator")
 
 
 
 
 
 
 
 
 
 
 
113
 
114
  with gr.Row():
115
  with gr.Column():
 
122
  label="Image URL",
123
  value="https://ark-doc.tos-ap-southeast-1.bytepluses.com/seepro_i2v%20.png"
124
  )
125
+ generate_btn = gr.Button("Generate", variant="primary")
126
 
127
  with gr.Column():
128
+ status = gr.Textbox(label="Status", lines=5)
129
  video = gr.Video(label="Generated Video")
130
 
131
+ generate_btn.click(
132
  fn=generate_video,
133
  inputs=[prompt, image_url],
134
  outputs=[status, video]