mxivideo/README_TEXT_VIDEO_AGENT_API.md

9.0 KiB

Text Video Agent API 工具库

基于 https://bowongai-dev--text-video-agent-fastapi-app.modal.run API 的完整 TypeScript 工具库封装。

📋 目录

🚀 功能特性

核心功能

  • 图片生成: 基于 Midjourney 的高质量图片生成
  • 视频生成: 基于极梦的视频生成功能
  • 文件上传: 支持文件上传到云存储
  • 图片描述: AI 图片内容分析和描述
  • 任务管理: 异步任务创建、查询和管理

高级特性

  • 重试机制: 自动重试失败的请求
  • 进度跟踪: 实时进度更新和状态监控
  • 类型安全: 完整的 TypeScript 类型定义
  • React 集成: 专用的 React Hook 和组件
  • 错误处理: 完善的错误处理和用户反馈

📦 安装使用

基础安装

# 复制相关文件到你的项目
cp src/services/textVideoAgentAPI.ts your-project/src/services/
cp src/services/textVideoAgentTypes.ts your-project/src/services/
cp src/hooks/useTextVideoAgent.ts your-project/src/hooks/
cp src/components/TextVideoGenerator.tsx your-project/src/components/

依赖要求

{
  "dependencies": {
    "react": "^18.0.0",
    "lucide-react": "^0.263.1"
  },
  "devDependencies": {
    "typescript": "^5.0.0"
  }
}

🔧 API 文档

基础用法

import { textVideoAgentAPI } from './services/textVideoAgentAPI'

// 健康检查
const health = await textVideoAgentAPI.healthCheck()

// 生成图片
const imageResult = await textVideoAgentAPI.generateImageSync({
  prompt: '一个美丽的风景',
  max_wait_time: 120
})

// 生成视频
const videoResult = await textVideoAgentAPI.generateVideoSync({
  prompt: '动态的自然风光',
  img_url: 'https://example.com/image.jpg',
  duration: '5'
})

主要方法

图片生成

// 同步生成(推荐)
generateImageSync(params: ImageGenerationParams): Promise<APIResponse>

// 异步生成
generateImageAsync(prompt: string, imgFile?: File): Promise<APIResponse>

// 带重试的生成
generateImageWithRetry(params: ImageGenerationParams, maxRetries?: number): Promise<APIResponse>

视频生成

// 同步生成
generateVideoSync(params: VideoGenerationParams): Promise<APIResponse>

// 异步生成
generateVideoAsync(params: VideoGenerationParams): Promise<APIResponse>

// 带重试的生成
generateVideoWithRetry(params: VideoGenerationParams, maxRetries?: number): Promise<APIResponse>

任务管理

// 创建任务
createTask(request: TaskRequest): Promise<APIResponse>

// 查询任务状态
getTaskStatusAsync(taskId: string): Promise<APIResponse>

// 同步等待任务完成
getTaskResultSync(taskId: string): Promise<APIResponse>

高级功能

// 端到端内容生成
generateContentEndToEnd(prompt: string, options?: GenerationOptions): Promise<ContentResult>

// 轮询任务直到完成
pollTaskUntilComplete(taskId: string, options?: PollingOptions): Promise<APIResponse>

🎣 React Hook

useTextVideoAgent

import { useTextVideoAgent } from './hooks/useTextVideoAgent'

function MyComponent() {
  const {
    state,
    generateImage,
    generateVideo,
    generateContentEndToEnd,
    reset,
    cancel
  } = useTextVideoAgent()

  const handleGenerate = async () => {
    const result = await generateContentEndToEnd('美丽的风景', {
      taskType: TaskType.VLOG,
      aspectRatio: AspectRatio.PORTRAIT,
      generateVideo: true
    })
    
    console.log('生成结果:', result)
  }

  return (
    <div>
      {state.isLoading && (
        <div>
          <p>{state.currentStep}</p>
          <progress value={state.progress} max={100} />
        </div>
      )}
      
      {state.error && (
        <div className="error">{state.error}</div>
      )}
      
      <button onClick={handleGenerate} disabled={state.isLoading}>
        生成内容
      </button>
    </div>
  )
}

useTaskPolling

import { useTaskPolling } from './hooks/useTextVideoAgent'

function TaskMonitor({ taskId }: { taskId: string }) {
  const { status, isPolling } = useTaskPolling(taskId, {
    onComplete: (result) => {
      console.log('任务完成:', result)
    },
    onError: (error) => {
      console.error('任务失败:', error)
    },
    onProgress: (status) => {
      console.log('进度更新:', status)
    }
  })

  return (
    <div>
      {isPolling && <p>任务进行中...</p>}
      {status && <pre>{JSON.stringify(status, null, 2)}</pre>}
    </div>
  )
}

🧩 组件示例

TextVideoGenerator 组件

import TextVideoGenerator from './components/TextVideoGenerator'

function App() {
  return (
    <TextVideoGenerator
      onImageGenerated={(imageUrl) => {
        console.log('图片生成完成:', imageUrl)
      }}
      onVideoGenerated={(videoUrl) => {
        console.log('视频生成完成:', videoUrl)
      }}
    />
  )
}

📝 类型定义

主要接口

// API 响应
interface APIResponse<T = any> {
  status: boolean
  msg: string
  data?: T
}

// 图片生成参数
interface ImageGenerationParams {
  prompt: string
  img_file?: File
  max_wait_time?: number
  poll_interval?: number
}

// 视频生成参数
interface VideoGenerationParams {
  prompt: string
  img_url?: string
  img_file?: File
  duration?: string
  max_wait_time?: number
  poll_interval?: number
}

// 任务请求
interface TaskRequest {
  task_type?: string
  prompt: string
  img_url?: string
  ar?: string
}

枚举类型

enum TaskType {
  TEA = 'tea',
  CHOP = 'chop',
  LADY = 'lady',
  VLOG = 'vlog'
}

enum AspectRatio {
  SQUARE = '1:1',
  PORTRAIT = '9:16',
  LANDSCAPE = '16:9'
}

enum VideoDuration {
  SHORT = '3',
  MEDIUM = '5',
  LONG = '10'
}

💡 使用示例

示例1: 基础图片生成

import { textVideoAgentAPI, TaskType, AspectRatio } from './services/textVideoAgentAPI'

async function generateImage() {
  try {
    const result = await textVideoAgentAPI.generateImageSync({
      prompt: '一个现代化的咖啡厅,温暖的灯光,舒适的环境',
      max_wait_time: 120
    })
    
    if (result.status) {
      console.log('图片URL:', result.data.image_url)
    }
  } catch (error) {
    console.error('生成失败:', error)
  }
}

示例2: 端到端内容生成

async function generateContent() {
  try {
    const result = await textVideoAgentAPI.generateContentEndToEnd(
      '制作一个关于健康生活的短视频',
      {
        taskType: TaskType.VLOG,
        aspectRatio: AspectRatio.PORTRAIT,
        videoDuration: VideoDuration.MEDIUM,
        generateVideo: true,
        onProgress: (step, progress) => {
          console.log(`${step}: ${progress}%`)
        }
      }
    )
    
    console.log('生成完成:', result)
  } catch (error) {
    console.error('生成失败:', error)
  }
}

示例3: 批量处理

async function batchGenerate() {
  const prompts = [
    '春天的樱花',
    '夏日的海滩',
    '秋天的枫叶',
    '冬日的雪景'
  ]
  
  const results = await Promise.allSettled(
    prompts.map(prompt => 
      textVideoAgentAPI.generateImageSync({ prompt })
    )
  )
  
  results.forEach((result, index) => {
    if (result.status === 'fulfilled') {
      console.log(`图片 ${index + 1} 生成成功:`, result.value.data?.image_url)
    } else {
      console.error(`图片 ${index + 1} 生成失败:`, result.reason)
    }
  })
}

🔧 配置选项

预设配置

import { PRESET_CONFIGS } from './services/textVideoAgentTypes'

// 快速生成(低质量)
const fastConfig = PRESET_CONFIGS.FAST

// 标准生成
const standardConfig = PRESET_CONFIGS.STANDARD

// 高质量生成
const highQualityConfig = PRESET_CONFIGS.HIGH_QUALITY

自定义配置

const customAPI = new TextVideoAgentAPI('https://your-custom-endpoint.com')

🚨 错误处理

try {
  const result = await textVideoAgentAPI.generateImageSync(params)
} catch (error) {
  if (error instanceof Error) {
    console.error('错误信息:', error.message)
  }
  
  // 处理特定错误类型
  if (error.message.includes('timeout')) {
    // 处理超时错误
  } else if (error.message.includes('quota')) {
    // 处理配额不足错误
  }
}

📊 性能优化

缓存策略

  • 图片生成结果自动缓存
  • 任务状态智能轮询
  • 网络请求去重

最佳实践

  • 使用适当的超时时间
  • 合理设置轮询间隔
  • 及时取消不需要的请求
  • 使用预设配置提高效率

🤝 贡献指南

  1. Fork 项目
  2. 创建功能分支
  3. 提交更改
  4. 推送到分支
  5. 创建 Pull Request

📄 许可证

MIT License

🆘 支持

如有问题或建议,请创建 Issue 或联系开发团队。