Spaces:
Runtime error

video / app.py
Julike's picture
Create app.py
9fe23a0 verified
Raw History Blame Contribute Delete
5.01 kB
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)