Download app.py from elelabc/900: direct link, hf CLI and curl.
- Browser
- Download file 7.97 kB
-
https://huggingface.co/spaces/elelabc/900/resolve/main/app.py
- Command line
-
hf download hf://spaces/elelabc/900/app.py
-
curl -L -o app.py https://huggingface.co/spaces/elelabc/900/resolve/main/app.py
7.97 kB
| 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() |