File size: 5,009 Bytes
9fe23a0 | 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 | import gradio as gr
import torch
import os
import uuid
import hashlib
import sqlite3
import base64
import numpy as np
from diffusers import StableDiffusionPipeline
from PIL import Image
import cv2
# ----------------------------
# 配置
# ----------------------------
CACHE_DIR = "./cache"
DB_PATH = os.path.join(CACHE_DIR, "t2v.db")
os.makedirs(CACHE_DIR, exist_ok=True)
API_TOKEN = os.environ.get("API_TOKEN")
if not API_TOKEN:
raise ValueError("请在 Space Settings 添加 API_TOKEN Secret")
# ----------------------------
# 数据库初始化
# ----------------------------
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute("""
CREATE TABLE IF NOT EXISTS video_records (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_token TEXT,
prompt TEXT,
duration INTEGER,
file_path TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
conn.commit()
conn.close()
# ----------------------------
# 低显存 CPU Pipeline
# ----------------------------
# 使用小模型 / CPU
pipe = StableDiffusionPipeline.from_pretrained(
"CompVis/video-ldm-small",
torch_dtype=torch.float32
).to("cpu")
# ----------------------------
# 工具函数
# ----------------------------
def prompt_to_filename(prompt: str, duration: int):
key = f"{prompt}-{duration}"
hash_name = hashlib.md5(key.encode()).hexdigest()
return os.path.join(CACHE_DIR, f"{hash_name}.mp4")
def save_video_record(user_token, prompt, duration, file_path):
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute("""
INSERT INTO video_records (user_token, prompt, duration, file_path)
VALUES (?, ?, ?, ?)
""", (user_token, prompt, duration, file_path))
conn.commit()
conn.close()
def video_to_base64(video_path: str):
with open(video_path, "rb") as f:
return "data:video/mp4;base64," + base64.b64encode(f.read()).decode()
# ----------------------------
# 核心生成函数
# ----------------------------
def generate_video_api(prompt: str, duration: int = 4, token: str = ""):
if token != API_TOKEN:
return "Unauthorized", None
# 限制短视频 CPU 可用
duration = min(duration, 5) # 最长5秒
num_frames = duration * 4 # 4 fps
wav_file = prompt_to_filename(prompt, duration)
if not os.path.exists(wav_file):
frames = []
for i in range(num_frames):
image = pipe(prompt, num_inference_steps=15).images[0]
frame = np.array(image)
frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
frames.append(frame)
# 保存为 MP4
h, w, _ = frames[0].shape
out = cv2.VideoWriter(wav_file, cv2.VideoWriter_fourcc(*'mp4v'), 4, (w, h))
for f in frames:
out.write(f)
out.release()
save_video_record(token, prompt, duration, wav_file)
return "OK", video_to_base64(wav_file)
# ----------------------------
# 查询历史记录
# ----------------------------
def query_video_records(token: str, keyword: str = None, limit: int = 10):
if token != API_TOKEN:
return "Unauthorized"
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
sql = "SELECT prompt, duration, file_path, created_at FROM video_records WHERE user_token=?"
params = [token]
if keyword:
sql += " AND prompt LIKE ?"
params.append(f"%{keyword}%")
sql += " ORDER BY created_at DESC LIMIT ?"
params.append(limit)
c.execute(sql, params)
rows = c.fetchall()
conn.close()
records = []
for prompt, duration, file_path, created_at in rows:
records.append({
"prompt": prompt,
"duration": duration,
"created_at": created_at,
"video_base64": video_to_base64(file_path)
})
return records
# ----------------------------
# Gradio Blocks
# ----------------------------
with gr.Blocks() as iface:
gr.Markdown("## T2V CPU 低显存生产级 API")
# 生成模块
with gr.Row():
prompt_input = gr.Textbox(label="Prompt")
duration_input = gr.Slider(1, 5, step=1, label="Duration (seconds)")
token_input = gr.Textbox(label="API Token")
generate_btn = gr.Button("生成视频")
status_output = gr.Textbox(label="状态")
output_video = gr.Video(label="Generated Video")
generate_btn.click(
fn=generate_video_api,
inputs=[prompt_input, duration_input, token_input],
outputs=[status_output, output_video]
)
gr.Markdown("## 查询历史生成记录")
token_input_q = gr.Textbox(label="API Token")
keyword_input_q = gr.Textbox(label="关键词筛选(可选)")
query_btn = gr.Button("查询历史")
output_records = gr.JSON(label="生成记录")
query_btn.click(
fn=query_video_records,
inputs=[token_input_q, keyword_input_q],
outputs=[output_records]
)
# 启用队列并启动
iface.queue()
iface.launch(server_name="0.0.0.0", server_port=7860) |