python+agnes api实现ai生成故事绘本有声读物代码

代码语言:python

所属分类:其他

代码描述:python+agnes api实现ai生成故事绘本有声读物代码,支持qwen的tts生成台词,支持字幕和视频比例设置,使用免费agnes 生成文案台词及分镜图片。

代码标签: python agnes api ai生成 故事 绘本 有声 读物 代码

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

import os
import json
import uuid
import time
import base64
import subprocess
import urllib.request
import urllib.error
import requests
import platform
from datetime import datetime
from pathlib import Path
from flask import Flask, request, jsonify, send_from_directory

# ============================================================
# 配置区
# ============================================================
# Agnes-AI 密钥配置
AGNES_API_KEY = os.environ.get("AGNES_API_KEY", "sk-")
BASE_URL = "https://apihub.agnes-ai.com"

# DashScope (阿里云) TTS 密钥配置
DASHSCOPE_API_KEY = "sk-"


WORK_DIR = Path("workspace_storybook")
WORK_DIR.mkdir(exist_ok=True)
PROJECTS_FILE = WORK_DIR / "projects.json"

app = Flask(__name__)

# ============================================================
# 底层基础工具函数
# ============================================================
def log_api_call(endpoint, req_data, res_data):
    print(f"\n{'='*20}[API CALL] {endpoint} {'='*20}")
    print(">>> REQUEST:", json.dumps(req_data, ensure_ascii=False, indent=2)[:500])
    print("<<< RESPONSE:", json.dumps(res_data, ensure_ascii=False, indent=2)[:500])
    print("=" * 60 + "\n")

def _get_resolution_str(aspect_ratio):
    mapping = {
        "16:9": "1280x720", "9:16": "720x1280", "1:1": "1024x1024"
    }
    return mapping.get(aspect_ratio, "1280x720")

def _get_resolution(aspect_ratio):
    res_str = _get_resolution_str(aspect_ratio)
    w, h = map(int, res_str.split('x'))
    return w, h

def download_file(url, target_path):
    try:
        urllib.request.urlretrieve(url, str(target_path))
        return True
    except Exception as e:
        print(f"Download error for {url}: {e}")
        return False

def get_system_font():
    """自动寻找系统自带的字体供 FFmpeg 烧录字幕使用"""
    candidates = []
    if platform.system() == 'Windows':
        candidates = [
            "C:/Windows/Fonts/msyh.ttc",   # 微软雅黑
            "C:/Windows/Fonts/simhei.ttf",  # 黑体
            "C:/Windows/Fonts/arial.ttf"    # Arial
        ]
    else:
        candidates = [
            "/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc",
            "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
            "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"
        ]
    
    for f in candidates:
        if os.path.exists(f):
            return f
    return None

def escape_ffmpeg_path(path_str):
    """转义 FFmpeg 滤镜中所需的文件路径,将反斜杠替换为正斜杠,转义冒号"""
    return path_str.replace('\\', '/').replace(':', '\\:')

# ============================================================
# Agnes-AI API 封装
# ============================================================
def call_agnes_chat(messages, model="agnes-2.0-flash", temperature=0.8, response_format=None):
    url = f"{BASE_URL}/v1/chat/completions"
    payload = {"model": model, "messages": messages, "temperature": temperature}
    if response_format:
        payload["response_format"] = response_format
    data = json.dumps(payload).encode("utf-8")
    req = urllib.request.Request(url, data=data, method="POST")
    req.add_header("Content-Type", "application/json")
    req.add_header("Authorization", f"Bearer {AGNES_API_KEY}")
    try:
        with urllib.request.urlopen(req, timeout=120) as resp:
            result = json.loads(resp.read().decode("utf-8"))
            return result["choices"][0]["message"]["content"]
    except urllib.error.HTTPError as e:
        err_msg = e.read().decode('utf-8')
        print(f"Agnes Chat API HTTP Error {e.code}: {err_msg}")
        return None
    except Exception as e:
        print(f"Agnes Chat API Error: {e}")
        return None

def call_agnes_image_gen(prompt, size="1280x720"):
    url = f"{BASE_URL}/v1/images/generations"
    headers = {
        "Authorization": f"Bearer {AGNES_API_KEY}",
        "Content-Type": "application/json"
    }
 .........完整代码请登录后点击上方下载按钮下载查看

网友评论0