# autodl **Repository Path**: aaron4102/autodl ## Basic Information - **Project Name**: autodl - **Description**: No description available - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2025-08-15 - **Last Updated**: 2025-08-15 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # Wan 2.2 Video Generation API [![Python](https://img.shields.io/badge/Python-3.8+-blue.svg)](https://www.python.org/downloads/) [![FastAPI](https://img.shields.io/badge/FastAPI-0.104.1-green.svg)](https://fastapi.tiangolo.com/) [![License](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) A high-performance, scalable API for generating videos using Wan 2.2 with AutoDL's elastic GPU deployment. This project provides a robust backend service that manages video generation tasks, GPU instance allocation, and result delivery. ## ✨ Features - **Multiple Generation Modes**: - Text-to-Video (T2V) - Image-to-Video (I2V) - Text+Image-to-Video (TI2V) - **Elastic Scaling**: - Automatic GPU instance management - Configurable maximum concurrent instances - Intelligent instance lifecycle management - **Robust API**: - RESTful endpoints for task submission and monitoring - Asynchronous task processing - Webhook support for task completion notifications - **Production Ready**: - Docker and Docker Compose support - Health checks and monitoring - Comprehensive logging - Unit tests and CI/CD ready ## 🚀 Quick Start ### Prerequisites - Python 3.8+ - Docker and Docker Compose (for containerized deployment) - AutoDL API key (sign up at [AutoDL](https://www.autodl.com/)) ### Installation 1. Clone the repository: ```bash git clone https://github.com/yourusername/wan2-api.git cd wan2-api ``` 2. Create and activate a virtual environment: ```bash python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate ``` 3. Install dependencies: ```bash pip install -r requirements.txt ``` 4. Configure environment variables: ```bash cp .env.example .env # Edit .env with your configuration ``` ### Running Locally Start the API server: ```bash uvicorn main:app --reload --host 0.0.0.0 --port 8000 ``` The API will be available at `http://localhost:8000` ### Docker Deployment 1. Build and start the services: ```bash docker-compose up -d --build ``` 2. View the API docs at: http://localhost:8000/docs ## 📚 API Documentation ### Base URL ``` http://localhost:8000 ``` ### Endpoints #### Health Check ``` GET /health ``` Check the health status of the API service. #### Submit Task ``` POST /api/tasks ``` Submit a new video generation task. **Request Body (T2V Example):** ```json { "task_type": "T2V", "prompt": "A beautiful sunset over mountains, cinematic, 8K", "duration_seconds": 5, "resolution": "720p", "fps": 24, "seed": 42, "callback_url": "https://your-webhook-url.com/callback" } ``` **Response:** ```json { "task_id": "550e8400-e29b-41d4-a716-446655440000", "status": "queued", "created_at": 1678901234.56789, "updated_at": 1678901234.56789 } ``` #### Get Task Status ``` GET /api/tasks/{task_id} ``` Get the status of a task. **Response:** ```json { "task_id": "550e8400-e29b-41d4-a716-446655440000", "status": "completed", "created_at": 1678901234.56789, "updated_at": 1678901250.12345, "result": { "video_url": "https://storage.example.com/videos/550e8400-e29b-41d4-a716-446655440000.mp4", "duration_seconds": 5.2, "resolution": "1280x720" } } ``` ## 🐍 Python Client A Python client is provided for easy integration: ```python from client import WanClient import asyncio async def main(): # Initialize client client = WanClient(base_url="http://localhost:8000") # Submit a text-to-video task task = await client.text_to_video( prompt="A beautiful sunset over mountains, cinematic, 8K", duration_seconds=5, resolution="720p" ) print(f"Task submitted: {task.task_id}") # Wait for completion result = await client.wait_for_task_completion(task.task_id) print(f"Task completed: {result.status}") if result.status == "completed": print(f"Video URL: {result.result['video_url']}") asyncio.run(main()) ``` ## 🧪 Testing Run the test suite: ```bash pytest tests/ -v ``` ## 🛠️ Configuration ### Environment Variables | Variable | Description | Default | |----------|-------------|---------| | `AUTODL_API_KEY` | Your AutoDL API key | - | | `AUTODL_ENDPOINT` | AutoDL API endpoint | `https://api.autodl.com` | | `MAX_NODES` | Maximum number of GPU instances to run | `2` | | `STORAGE_BASE_URL` | Base URL for storing generated videos | - | | `LOG_LEVEL` | Logging level | `INFO` | | `DATABASE_URL` | Database connection URL | - | | `REDIS_URL` | Redis connection URL | - | ## 🤝 Contributing 1. Fork the repository 2. Create a feature branch (`git checkout -b feature/amazing-feature`) 3. Commit your changes (`git commit -m 'Add some amazing feature'`) 4. Push to the branch (`git push origin feature/amazing-feature`) 5. Open a Pull Request ## 📄 License This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. ## 📧 Contact Your Name - [@yourtwitter](https://twitter.com/yourtwitter) - email@example.com Project Link: [https://github.com/yourusername/wan2-api](https://github.com/yourusername/wan2-api) ## 🔒 Authentication All API endpoints require a valid API key in the request header: ``` Authorization: Bearer YOUR_API_KEY ``` ### Response Format All API responses follow this format: ```json { "code": 200, // Status code "message": "success", // Status message "data": {}, // Response data "error": null // Error details (if any) } ``` ### Status Codes | Code | Description | |------|-------------| | 200 | Success | | 201 | Resource created successfully | | 400 | Bad request - Invalid parameters | | 401 | Unauthorized - Invalid or missing API key | | 403 | Forbidden - Insufficient permissions | | 404 | Resource not found | | 429 | Too many requests - Rate limit exceeded | | 500 | Internal server error | | 502 | Bad gateway - Upstream service error | | 503 | Service unavailable - Maintenance or overloaded | ## 📝 API Reference ### 1. Submit Video Generation Task **Endpoint:** `POST /api/tasks/` **Request Parameters:** | Parameter | Type | Required | Description | Example | |-----------|------|----------|-------------|---------| | mode | string | Yes | Generation mode: `t2v`, `i2v`, or `ti2v` | `"t2v"` | | params | object | Yes | Generation parameters (varies by mode) | See below | **Example Request (T2V):** ```json { "mode": "t2v", "params": { "prompt": "A beautiful sunset over mountains, cinematic, 8K", "duration_seconds": 5, "resolution": "720p", "fps": 24, "seed": 42 } } ``` **Example Response:** ```json { "code": 201, "message": "Task created successfully", "data": { "task_id": "550e8400-e29b-41d4-a716-446655440000", "status": "queued", "created_at": 1678901234.56789 }, "error": null } ``` ### 2. Get Task Status **Endpoint:** `GET /api/tasks/{task_id}` **Path Parameters:** - `task_id` (string, required): The ID of the task to retrieve **Example Response:** ```json { "code": 200, "message": "Success", "data": { "task_id": "550e8400-e29b-41d4-a716-446655440000", "status": "completed", "created_at": 1678901234.56789, "updated_at": 1678901250.12345, "result": { "video_url": "https://storage.example.com/videos/550e8400-e29b-41d4-a716-446655440000.mp4", "duration_seconds": 5.2, "resolution": "1280x720" } }, "error": null } ``` ### 3. List Tasks **Endpoint:** `GET /api/tasks/` **Query Parameters:** - `status` (string, optional): Filter by status (queued, processing, completed, failed) - `limit` (integer, optional): Maximum number of tasks to return (default: 10, max: 100) - `offset` (integer, optional): Pagination offset (default: 0) **Example Response:** ```json { "code": 200, "message": "Success", "data": { "tasks": [ { "task_id": "550e8400-e29b-41d4-a716-446655440000", "status": "completed", "created_at": 1678901234.56789, "updated_at": 1678901250.12345 } ], "pagination": { "total": 1, "limit": 10, "offset": 0 } }, "error": null } ``` ## 🚀 Deployment ### Environment Variables Create a `.env` file with the following variables: ```bash # Required AUTODL_API_KEY=your_autodl_api_key STORAGE_BASE_URL=https://your-storage-bucket.s3.amazonaws.com # Optional (with defaults) LOG_LEVEL=INFO MAX_NODES=2 REDIS_URL=redis://redis:6379/0 DATABASE_URL=sqlite:///./sql_app.db ``` ### Docker Compose Start all services: ```bash docker-compose up -d --build ``` ### Kubernetes For production deployments, Kubernetes manifests are provided in the `k8s/` directory. ## 🧪 Running Tests ```bash # Run unit tests pytest tests/unit/ # Run integration tests pytest tests/integration/ # Run tests with coverage report pytest --cov=app --cov-report=term-missing ``` ## 🤝 Contributing 1. Fork the repository 2. Create a feature branch (`git checkout -b feature/amazing-feature`) 3. Commit your changes (`git commit -m 'Add some amazing feature'`) 4. Push to the branch (`git push origin feature/amazing-feature`) 5. Open a Pull Request ## 📄 License This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. ## 📧 Contact Your Name - [@yourtwitter](https://twitter.com/yourtwitter) - email@example.com Project Link: [https://github.com/yourusername/wan2-api](https://github.com/yourusername/wan2-api) ## 📚 Additional Resources ### Generation Parameters by Mode #### Text-to-Video (T2V) ```json { "mode": "t2v", "params": { "prompt": "A beautiful sunset over the mountains, 4K, cinematic", "duration_seconds": 5, "resolution": "720p", "fps": 24, "style": "cinematic", "seed": 42, "num_inference_steps": 50, "guidance_scale": 7.5 } } ``` #### Image-to-Video (I2V) ```json { "mode": "i2v", "params": { "image_url": "https://example.com/input.jpg", "prompt": "A beautiful animation of this landscape", "duration_seconds": 5, "resolution": "720p", "fps": 24, "seed": 42, "strength": 0.7 } } ``` #### Text+Image-to-Video (TI2V) ```json { "mode": "ti2v", "params": { "image_url": "https://example.com/input.jpg", "prompt": "A beautiful animation of this landscape with a sunset", "duration_seconds": 5, "resolution": "720p", "fps": 24, "seed": 42, "strength": 0.7, "num_inference_steps": 50, "guidance_scale": 7.5 } } ``` ## 🚨 Rate Limiting The API enforces rate limiting to ensure fair usage: - 60 requests per minute per IP address - 1000 requests per hour per API key ## 🔒 Security - All API requests must be made over HTTPS - API keys should be kept secret and never committed to version control - Enable CORS only for trusted domains in production - Regularly rotate API keys ## 📈 Monitoring Prometheus metrics are available at `/metrics` for monitoring: - Request counts and latencies - Error rates - Queue lengths - GPU utilization ## 🔍 Troubleshooting ### Common Issues 1. **Task Stuck in Queue** - Check if there are available GPU instances - Verify your AutoDL API key has sufficient quota - Check the logs for errors 2. **Authentication Errors** - Verify your API key is correct - Ensure the `Authorization` header is properly formatted 3. **Video Generation Failures** - Check the error message in the task status - Verify input parameters are within valid ranges - Try with a different seed value For additional help, please open an issue on GitHub. ## 📚 Additional Resources - [AutoDL Documentation](https://www.autodl.com/docs/) - [FastAPI Documentation](https://fastapi.tiangolo.com/) - [Docker Documentation](https://docs.docker.com/) - [Kubernetes Documentation](https://kubernetes.io/docs/home/) ## 🙏 Acknowledgments - Thanks to the open source community for their contributions - Built with ❤️ using FastAPI, Pydantic, and other amazing open source projects ##### 文本+图片生成视频 (TI2V) ```json { "mode": "ti2v", "params": { "prompt": "A beautiful sunset over the mountains, 4K, cinematic", "image_url": "https://example.com/image.jpg", "duration": 5, "fps": 24, "style": "cinematic", "negative_prompt": "low quality, blurry" } } ``` **响应示例:** ```json { "code": 201, "message": "Task created successfully", "data": { "task_id": "550e8400-e29b-41d4-a716-446655440000", "status": "pending", "created_at": "2023-08-15T14:30:00Z", "progress": 0, "result_url": null, "error": null }, "error": null } ``` ### 2. 查询任务状态 **端点:** `GET /api/tasks/{task_id}` **URL 参数:** | 参数名 | 类型 | 必填 | 描述 | 示例 | |--------|------|------|------|------| | task_id | string | 是 | 任务 ID | `550e8400-e29b-41d4-a716-446655440000` | **响应示例 (等待中):** ```json { "code": 200, "message": "success", "data": { "task_id": "550e8400-e29b-41d4-a716-446655440000", "status": "pending", "progress": 0, "created_at": "2023-08-15T14:30:00Z", "started_at": null, "completed_at": null, "result_url": null, "error": null }, "error": null } ``` **响应示例 (处理中):** ```json { "code": 200, "message": "success", "data": { "task_id": "550e8400-e29b-41d4-a716-446655440000", "status": "processing", "progress": 45, "created_at": "2023-08-15T14:30:00Z", "started_at": "2023-08-15T14:30:05Z", "completed_at": null, "result_url": null, "error": null }, "error": null } ``` **响应示例 (已完成):** ```json { "code": 200, "message": "success", "data": { "task_id": "550e8400-e29b-41d4-a716-446655440000", "status": "completed", "progress": 100, "created_at": "2023-08-15T14:30:00Z", "started_at": "2023-08-15T14:30:05Z", "completed_at": "2023-08-15T14:35:22Z", "result_url": "https://storage.example.com/results/550e8400-e29b-41d4-a716-446655440000.mp4", "error": null }, "error": null } ``` **响应示例 (失败):** ```json { "code": 200, "message": "success", "data": { "task_id": "550e8400-e29b-41d4-a716-446655440000", "status": "failed", "progress": 30, "created_at": "2023-08-15T14:30:00Z", "started_at": "2023-08-15T14:30:05Z", "completed_at": "2023-08-15T14:31:15Z", "result_url": null, "error": "Instance terminated unexpectedly" }, "error": null } ``` ## 配置选项 ### 环境变量 | 环境变量 | 描述 | 默认值 | 是否必填 | |---------|------|--------|---------| | `AUTODL_API_KEY` | AutoDL API 密钥 | 无 | 是 | | `AUTODL_ENDPOINT` | AutoDL API 端点 | `https://api.autodl.com` | 否 | | `MAX_NODES` | 最大 GPU 节点数 | `2` | 否 | | `STORAGE_BASE_URL` | 结果存储基础 URL | 无 | 是 | | `LOG_LEVEL` | 日志级别 | `INFO` | 否 | | `DATABASE_URL` | 数据库连接 URL | `sqlite:///./sql_app.db` | 否 | | `REDIS_URL` | Redis 连接 URL | `redis://localhost:6379/0` | 否 | ### 配置示例 ```bash # .env 文件示例 AUTODL_API_KEY=your_autodl_api_key_here STORAGE_BASE_URL=https://storage.example.com/results MAX_NODES=3 LOG_LEVEL=DEBUG ``` ## 开发指南 ### 安装开发依赖 ```bash pip install -r requirements-dev.txt ``` ### 运行测试 ```bash # 运行所有测试 pytest # 运行特定测试文件 pytest tests/test_api.py # 生成测试覆盖率报告 pytest --cov=app --cov-report=html ``` ### 代码风格 项目使用 `black` 和 `isort` 进行代码格式化: ```bash # 格式化代码 black . isort . # 检查代码风格 flake8 . ``` ### 提交信息规范 请遵循 [Conventional Commits](https://www.conventionalcommits.org/) 规范: - `feat`: 新功能 - `fix`: 修复 bug - `docs`: 文档更新 - `style`: 代码格式调整 - `refactor`: 代码重构 - `perf`: 性能优化 - `test`: 测试相关 - `chore`: 构建过程或辅助工具的变动 ## 部署指南 ### 使用 Docker 部署 1. 构建 Docker 镜像: ```bash docker build -t wan-api . ``` 2. 运行容器: ```bash docker run -d \ --name wan-api \ -p 8000:8000 \ --env-file .env \ wan-api ``` ### 使用 Docker Compose 部署 ```yaml version: '3.8' services: api: build: . ports: - "8000:8000" env_file: .env depends_on: - redis restart: unless-stopped volumes: - ./data:/app/data redis: image: redis:7-alpine ports: - "6379:6379" volumes: - redis_data:/data restart: unless-stopped volumes: redis_data: ``` ### 生产环境建议 1. 使用 Nginx 作为反向代理 2. 配置 HTTPS 3. 设置适当的日志轮转 4. 监控 API 性能和资源使用情况 5. 定期备份数据库 ## 监控与日志 ### 日志位置 - 应用日志: `/var/log/wan-api/app.log` - 访问日志: `/var/log/wan-api/access.log` - 错误日志: `/var/log/wan-api/error.log` ### 监控指标 API 暴露了 Prometheus 格式的监控指标: ``` GET /metrics ``` ## 常见问题 ### 任务长时间处于 pending 状态 1. 检查 AutoDL 账户余额是否充足 2. 确认 AutoDL API 密钥是否有足够权限 3. 检查网络连接是否正常 ### 视频生成失败 1. 检查输入参数是否有效 2. 查看服务日志获取详细错误信息 3. 确认 GPU 资源是否足够 ## 贡献指南 欢迎提交 Issue 和 Pull Request。请确保: 1. 代码符合 PEP 8 规范 2. 添加适当的单元测试 3. 更新相关文档 ## 许可证 [MIT](LICENSE) © 2023 Wan API Team