File size: 7,974 Bytes
03cc9de f728c11 03cc9de 522178e d58bacc 03cc9de f0a9845 522178e b970eb4 f728c11 985fdaa f728c11 522178e 03cc9de 522178e 03cc9de 985fdaa f728c11 522178e f728c11 522178e f728c11 985fdaa 03cc9de 522178e 985fdaa 03cc9de 522178e 985fdaa 03cc9de 522178e 985fdaa 03cc9de 522178e 985fdaa 03cc9de 522178e 985fdaa 03cc9de 522178e 03cc9de f728c11 985fdaa 522178e 985fdaa 03cc9de 985fdaa 522178e 985fdaa 522178e f0a9845 985fdaa 522178e 985fdaa f728c11 522178e 985fdaa 03cc9de f728c11 522178e 03cc9de 522178e 03cc9de 522178e b970eb4 522178e b970eb4 522178e 985fdaa 03cc9de f728c11 522178e f728c11 985fdaa 03cc9de 522178e 03cc9de 985fdaa 522178e 03cc9de 985fdaa 522178e b970eb4 985fdaa 522178e 03cc9de 985fdaa 522178e f728c11 985fdaa 03cc9de | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 | import gradio as gr
import requests
import time
import json
import base64
from io import BytesIO
from PIL import Image
# --- 配置部分 ---
# 严格对应截图 8.08.15 中的 Base URL 格式
API_KEY = "zz2026021"
BASE_URL = "http://154.40.59.124:8000/flow/v1/videos"
HEADERS = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
}
# 严格对应截图 8.08.15 中的模型列表
MODELS = ["veo_3_1", "nano_banana", "nano_banana_pro", "imagen_4"]
def image_to_base64(image):
"""将图片转为 Base64 (用于图生视频 input_reference)"""
if image is None:
return None
buffered = BytesIO()
image.save(buffered, format="PNG")
img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
return f"data:image/png;base64,{img_str}"
def generate_video_strict(prompt, model_name, input_image=None):
"""
流程:
1. POST 创建任务
2. GET 查询状态 (带上 detail=true 参数)
3. 从 detail 字段直接解析 download_url (避免请求 /content 导致 JSON 错误)
"""
if not prompt:
yield "❌ 请输入提示词", ""
return
# --- 步骤 1: 创建任务 (POST) ---
# 对应截图 8.18.33
payload = {
"model": model_name,
"prompt": prompt
}
# 对应截图 8.07.47 / 8.18.33 input_reference
if input_image is not None:
base64_img = image_to_base64(input_image)
payload["input_reference"] = [base64_img]
try:
print(f"[-] 提交任务... Prompt: {prompt[:20]}")
res_create = requests.post(BASE_URL, headers=HEADERS, json=payload)
res_create.raise_for_status()
data_create = res_create.json()
# 兼容处理 ID
task_id = data_create.get("id") or data_create.get("data", {}).get("id")
if not task_id:
yield f"❌ 提交失败: 未返回 Task ID。响应: {res_create.text}", ""
return
yield f"✅ 任务已提交 (ID: {task_id})\n⏳ 正在轮询状态 (带 detail=true)...", ""
except Exception as e:
yield f"❌ 连接/提交错误: {str(e)}", ""
return
# --- 步骤 2: 轮询状态 (GET) ---
# 对应截图 8.18.48 (查询视频任务状态接口)
# 关键修正:添加 params={'detail': 'true'}
check_url = f"{BASE_URL}/{task_id}"
start_time = time.time()
while True:
elapsed = int(time.time() - start_time)
if elapsed > 600: # 10分钟超时
yield f"⚠️ 任务超时,ID: {task_id}", ""
break
try:
time.sleep(3)
# 关键修正点:这里必须加上 detail=true,否则服务器不返回 download_url
res_status = requests.get(check_url, headers=HEADERS, params={"detail": "true"})
if res_status.status_code != 200:
print(f"Status check failed: {res_status.status_code}")
continue
status_data = res_status.json()
# 对应截图 8.18.48 响应结构
status = status_data.get("status", "").upper()
# 实时日志更新
log_msg = f"🔄 生成中... ({elapsed}s) | 状态: {status}"
yield log_msg, ""
if status in ["SUCCEEDED", "SUCCESS", "COMPLETED"]:
# --- 步骤 3: 提取下载链接 ---
# 对应截图 8.12.42,成功的 JSON 数据应该在 detail 字段中
detail_info = status_data.get("detail", {})
# 尝试直接从 detail 获取 download_url (这是截图 8.12.42 展示的结构)
download_link = detail_info.get("download_url")
# 如果 detail 是字符串(有时 API 会这样),尝试二次解析
if not download_link and isinstance(detail_info, str):
try:
detail_json = json.loads(detail_info)
download_link = detail_json.get("download_url")
except:
pass
# 如果还是没有,尝试从 /content 接口获取重定向地址 (备用方案)
if not download_link:
yield f"⚠️ detail 中未找到链接,尝试探测 /content...", ""
try:
content_url = f"{BASE_URL}/{task_id}/content"
# allow_redirects=False 以便捕获 302 跳转链接,而不是下载文件
res_content = requests.get(content_url, headers=HEADERS, allow_redirects=False, stream=True)
if res_content.status_code in [301, 302, 303, 307, 308]:
download_link = res_content.headers.get('Location')
elif res_content.status_code == 200:
# 如果是 200,可能是直接的文件流,这种情况下只能让用户去访问 API 地址
download_link = content_url
except:
pass
if download_link:
# 生成 HTML 下载卡片
html_output = f"""
<div style="text-align: center; padding: 20px; background-color: #f0f9ff; border: 1px solid #bae6fd; border-radius: 10px;">
<div style="color: #0369a1; font-weight: bold; font-size: 18px; margin-bottom: 10px;">
🎉 视频生成成功!
</div>
<a href="{download_link}" target="_blank"
style="display: inline-block; background-color: #2563eb; color: white; padding: 12px 25px;
border-radius: 6px; text-decoration: none; font-weight: bold; font-size: 16px;">
📥 点击下载 .mp4 视频
</a>
<p style="margin-top: 10px; color: #64748b; font-size: 12px; word-break: break-all;">
{download_link}
</p>
</div>
"""
yield f"✅ 成功! 耗时 {elapsed}s", html_output
return
else:
yield f"❌ 任务成功但未找到下载链接。\n完整响应: {json.dumps(status_data, ensure_ascii=False)}", ""
return
elif status in ["FAILED", "FAILURE"]:
error_msg = status_data.get("detail", "未知错误")
yield f"❌ 生成失败: {error_msg}", ""
return
except Exception as e:
print(f"Polling error: {e}")
continue
# --- 界面构建 ---
with gr.Blocks(title="Flow Video Generator Strict", theme=gr.themes.Soft()) as demo:
gr.Markdown("### 🎬 Flow 视频直链生成器 (修正版)")
gr.Markdown("修复 JSON 解析错误:通过 `detail=true` 参数从状态接口直接获取链接,避免解析二进制文件流。")
with gr.Row():
with gr.Column():
prompt_input = gr.Textbox(label="提示词", placeholder="描述视频内容...", lines=3)
model_input = gr.Dropdown(choices=MODELS, value="veo_3_1", label="模型")
image_input = gr.Image(label="参考图 (可选)", type="pil", height=150)
btn = gr.Button("🚀 生成视频", variant="primary")
with gr.Column():
status_log = gr.Textbox(label="运行日志 (Status Log)", interactive=False)
result_html = gr.HTML(label="下载结果")
btn.click(
fn=generate_video_strict,
inputs=[prompt_input, model_input, image_input],
outputs=[status_log, result_html]
)
if __name__ == "__main__":
demo.launch() |