Tio Boot DocsTio Boot Docs
Home
  • java-db
  • api-table
  • Enjoy
  • Tio Boot Admin
  • ai_agent
  • translator
  • knowlege_base
  • ai-search
  • 案例
Abount
  • Github
  • Gitee
Home
  • java-db
  • api-table
  • Enjoy
  • Tio Boot Admin
  • ai_agent
  • translator
  • knowlege_base
  • ai-search
  • 案例
Abount
  • Github
  • Gitee
  • 01_tio-boot 简介

    • tio-boot:新一代高性能 Java Web 开发框架
    • tio-boot 入门示例
    • Tio-Boot 配置 : 现代化的配置方案
    • tio-boot 整合 Logback
    • tio-boot 整合 hotswap-classloader 实现热加载
    • 自行编译 tio-boot
    • 最新版本
    • 开发规范
  • 02_部署

    • 使用 Maven Profile 实现分环境打包 tio-boot 项目
    • Maven 项目配置详解:依赖与 Profiles 配置
    • tio-boot 打包成 FastJar
    • 使用 GraalVM 构建 tio-boot Native 程序
    • 使用 Docker 部署 tio-boot
    • 部署到 Fly.io
    • 部署到 AWS Lambda
    • 到阿里云云函数
    • 使用 Deploy 工具部署
    • 胖包与瘦包的打包与部署
    • 使用 Jenkins 部署 Tio-Boot 项目
    • 使用 Nginx 反向代理 Tio-Boot
    • 使用 Supervisor 管理 Java 应用
  • 03_配置

    • 配置参数
    • 服务器监听器
    • 内置缓存系统 AbsCache
    • 使用 Redis 作为内部 Cache
    • 静态文件处理器
    • 基于域名的静态资源隔离
    • DecodeExceptionHandler
  • 04_原理

    • 生命周期
    • 请求处理流程
    • 重要的类
  • 05_json

    • Json
    • 接受 JSON 和响应 JSON
    • 响应实体类
  • 06_web

    • 概述
    • 文件上传
    • 接收请求参数
    • 接收日期参数
    • 接收数组参数
    • 返回字符串
    • 返回文本数据
    • 返回网页
    • 请求和响应字节
    • 文件下载
    • 返回视频文件并支持断点续传
    • http Session
    • Cookie
    • HttpRequest
    • HttpResponse
    • Resps
    • RespBodyVo
    • /zh/06_web/19.html
    • 全局异常处理器
    • 异步
    • 动态 返回 CSS 实现
    • 返回图片
    • Transfer-Encoding: chunked 实时音频播放
    • Server-Sent Events (SSE)
    • 接口访问统计
    • 接口请求和响应数据记录
    • 自定义 Handler 转发请求
    • 使用 HttpForwardHandler 转发所有请求
    • 跨域
    • 添加 Controller
    • 常用工具类
    • HTTP Basic 认证
    • WebJars
    • JProtobuf
  • 07_validate

    • 数据紧校验规范
    • 参数校验
  • 08_websocket

    • 使用 tio-boot 搭建 WebSocket 服务
    • WebSocket 聊天室项目示例
  • 09_java-db

    • java‑db
    • 操作数据库入门示例
    • SQL 模板
    • 数据源配置与使用
    • ActiveRecord
    • Model
    • 生成器与 Model
    • Db 工具类
    • 批量操作
    • 数据库事务处理
    • Cache 缓存
    • Dialect 多数据库支持
    • 表关联操作
    • 复合主键
    • Oracle 支持
    • Enjoy SQL 模板
    • Java-DB 整合 Enjoy 模板最佳实践
    • 多数据源支持
    • 独立使用 ActiveRecord
    • 调用存储过程
    • java-db 整合 Guava 的 Striped 锁优化
    • 生成 SQL
    • 通过实体类操作数据库
    • java-db 读写分离
    • Spring Boot 整合 Java-DB
    • like 查询
    • 常用操作示例
    • Druid 监控集成指南
    • SQL 统计
  • 10_api-table

    • ApiTable 概述
    • 使用 ApiTable 连接 SQLite
    • 使用 ApiTable 连接 Mysql
    • 使用 ApiTable 连接 Postgres
    • 使用 ApiTable 连接 TDEngine
    • 使用 api-table 连接 oracle
    • 使用 api-table 连接 mysql and tdengine 多数据源
    • EasyExcel 导出
    • EasyExcel 导入
    • TQL(Table SQL)前端输入规范
    • ApiTable 实现增删改查
    • 数组类型
    • 单独使用 ApiTable
  • 11_aop

    • JFinal-aop
    • Aop 工具类
    • 配置
    • 配置
    • 独立使用 JFinal Aop
    • @AImport
    • 原理解析
  • 12_cache

    • Caffine
    • Jedis-redis
    • hutool RedisDS
    • Redisson
    • Caffeine and redis
    • CacheUtils 工具类
    • 使用 CacheUtils 整合 caffeine 和 redis 实现的两级缓存
    • 使用 java-db 整合 ehcache
    • 使用 java-db 整合 redis
    • Java DB Redis 相关 Api
    • redis 使用示例
  • 13_认证和权限

    • hutool-JWT
    • FixedTokenInterceptor
    • 使用内置 TokenManager 实现登录
    • 用户系统
    • 重置密码
    • 匿名登录
    • Google 登录
    • 权限校验注解
    • Sa-Token
    • sa-token 登录注册
    • StpUtil.isLogin() 源码解析
    • 短信登录
    • 移动端微信登录实现指南
    • 移动端重置密码
  • 14_i18n

    • i18n
  • 15_enjoy

    • tio-boot 整合 Enjoy 模版引擎文档
    • 引擎配置
    • 表达式
    • 指令
    • 注释
    • 原样输出
    • Shared Method 扩展
    • Shared Object 扩展
    • Extension Method 扩展
    • Spring boot 整合
    • 独立使用 Enjoy
    • tio-boot enjoy 自定义指令 localeDate
    • PromptEngine
    • Enjoy 入门示例-擎渲染大模型请求体
    • Enjoy 使用示例
  • 16_定时任务

    • Quartz 定时任务集成指南
    • 分布式定时任务 xxl-jb
    • cron4j 使用指南
  • 17_tests

    • TioBootTest 类
  • 18_tio

    • TioBootServer
    • tio-core
    • 内置 TCP 处理器
    • 独立启动 UDPServer
    • 使用内置 UDPServer
    • t-io 消息处理流程
    • tio-运行原理详解
    • TioConfig
    • ChannelContext
    • Tio 工具类
    • 业务数据绑定
    • 业务数据解绑
    • 发送数据
    • 关闭连接
    • Packet
    • 监控: 心跳
    • 监控: 客户端的流量数据
    • 监控: 单条 TCP 连接的流量数据
    • 监控: 端口的流量数据
    • 单条通道统计: ChannelStat
    • 所有通道统计: GroupStat
    • 资源共享
    • 成员排序
    • ssl
    • DecodeRunnable
    • 使用 AsynchronousSocketChannel 响应数据
    • 拉黑 IP
    • 深入解析 Tio 源码:构建高性能 Java 网络应用
  • 19_aio

    • ByteBuffer
    • AIO HTTP 服务器
    • 自定义和线程池和池化 ByteBuffer
    • AioHttpServer 应用示例 IP 属地查询
    • 手写 AIO Http 服务器
  • 20_netty

    • Netty TCP Server
    • Netty Web Socket Server
    • 使用 protoc 生成 Java 包文件
    • Netty WebSocket Server 二进制数据传输
    • Netty 组件详解
  • 21_netty-boot

    • Netty-Boot
    • 原理解析
    • 整合 Hot Reload
    • 整合 数据库
    • 整合 Redis
    • 整合 Elasticsearch
    • 整合 Dubbo
    • Listener
    • 文件上传
    • 拦截器
    • Spring Boot 整合 Netty-Boot
    • SSL 配置指南
    • ChannelInitializer
    • Reserve
  • 22_MQ

    • Mica-mqtt
    • EMQX
    • Disruptor
  • 23_tio-utils

    • tio-utils
    • HttpUtils
    • Notification
    • 邮箱
    • JSON
    • 读取文件
    • Base64
    • 上传和下载
    • Http
    • Telegram
    • RsaUtils
    • EnvUtils 使用文档
    • 系统监控
    • 毫秒并发 ID (MCID) 生成方案
  • 24_tio-http-server

    • 使用 Tio-Http-Server 搭建简单的 HTTP 服务
    • tio-boot 添加 HttpRequestHandler
    • 在 Android 上使用 tio-boot 运行 HTTP 服务
    • tio-http-server-native
    • handler 常用操作
  • 25_tio-websocket

    • WebSocket 服务器
    • WebSocket Client
  • 26_tio-im

    • 通讯协议文档
    • ChatPacket.proto 文档
    • java protobuf
    • 数据表设计
    • 创建工程
    • 登录
    • 历史消息
    • 发消息
  • 27_mybatis

    • Tio-Boot 整合 MyBatis
    • 使用配置类方式整合 MyBatis
    • 整合数据源
    • 使用 mybatis-plus 整合 tdengine
    • 整合 mybatis-plus
  • 28_mongodb

    • tio-boot 使用 mongo-java-driver 操作 mongodb
  • 29_elastic-search

    • Elasticsearch
    • JavaDB 整合 ElasticSearch
    • Elastic 工具类使用指南
    • Elastic-search 注意事项
    • ES 课程示例文档
  • 30_magic-script

    • tio-boot 整合 magic-script
  • 31_groovy

    • tio-boot 整合 Groovy
  • 32_firebase

    • 整合 google firebase
    • Firebase Storage
    • Firebase Authentication
    • 使用 Firebase Admin SDK 进行匿名用户管理与自定义状态标记
    • 导出用户
    • 注册回调
    • 登录注册
  • 33_文件存储

    • 文件上传数据表
    • 本地存储
    • 使用 AWS S3 存储文件并整合到 Tio-Boot 项目中
    • 存储文件到 腾讯 COS
  • 34_spider

    • jsoup
    • 爬取 z-lib.io 数据
    • 整合 WebMagic
    • WebMagic 示例:爬取学校课程数据
    • Playwright
    • Flexmark (Markdown 处理器)
    • tio-boot 整合 Playwright
    • 缓存网页数据
  • 36_integration_thirty_party

    • tio-boot 整合 okhttp
    • 整合 GrpahQL
    • 集成 Mailjet
    • 整合 ip2region
    • 整合 GeoLite 离线库
    • 整合 Lark 机器人指南
    • 集成 Lark Mail 实现邮件发送
    • Thymeleaf
    • Swagger
    • Clerk 验证
  • 37_dubbo

    • 概述
    • dubbo 2.6.0
    • dubbo 2.6.0 调用过程
    • dubbo 3.2.0
  • 38_spring

    • Spring Boot Web 整合 Tio Boot
    • spring-boot-starter-webflux 整合 tio-boot
    • Tio Boot 整合 Spring Boot Starter
    • Tio Boot 整合 Spring Boot Starter Data Redis 指南
  • 39_spring-cloud

    • tio-boot spring-cloud
  • 40_mysql

    • 使用 Docker 运行 MySQL
    • /zh/42_mysql/02.html
  • 41_postgresql

    • PostgreSQL 安装
    • PostgreSQL 主键自增
    • PostgreSQL 日期类型
    • Postgresql 金融类型
    • PostgreSQL 数组类型
    • PostgreSQL 全文检索
    • PostgreSQL 查询优化
    • 获取字段类型
    • PostgreSQL 向量
    • PostgreSQL 优化向量查询
    • PostgreSQL 其他
  • 43_oceanbase

    • 快速体验 OceanBase 社区版
    • 快速上手 OceanBase 数据库单机部署与管理
    • 诊断集群性能
    • 优化 SQL 性能指南
    • /zh/43_oceanbase/05.html
  • 50_media

    • JAVE 提取视频中的声音
    • Jave 提取视频中的图片
    • /zh/50_media/03.html
  • 51_asr

    • Whisper-JNI
  • 54_native-media

    • java-native-media
    • JNI 入门示例
    • mp3 拆分
    • mp4 转 mp3
    • 使用 libmp3lame 实现高质量 MP3 编码
    • Linux 编译
    • macOS 编译
    • 从 JAR 包中加载本地库文件
    • 支持的音频和视频格式
    • 任意格式转为 mp3
    • 通用格式转换
    • 通用格式拆分
    • 视频合并
    • VideoToHLS
    • split_video_to_hls 支持其他语言
    • 持久化 HLS 会话
  • 55_telegram4j

    • 数据库设计
    • /zh/55_telegram4j/02.html
    • 基于 MTProto 协议开发 Telegram 翻译机器人
    • 过滤旧消息
    • 保存机器人消息
    • 定时推送
    • 增加命令菜单
    • 使用 telegram-Client
    • 使用自定义 StoreLayout
    • 延迟测试
    • Reactor 错误处理
    • Telegram4J 常见错误处理指南
  • 56_telegram-bots

    • TelegramBots 入门指南
    • 使用工具库 telegram-bot-base 开发翻译机器人
  • 60_LLM

    • 简介
    • AI 问答
    • /zh/60_LLM/03.html
    • /zh/60_LLM/04.html
    • 增强检索(RAG)
    • 结构化数据检索
    • 搜索+AI
    • 集成第三方 API
    • 后置处理
    • 推荐问题生成
    • 连接代码执行器
    • 避免 GPT 混乱
    • /zh/60_LLM/13.html
  • 61_ai_agent

    • 数据库设计
    • 示例问题管理
    • 会话管理
    • 历史记录
    • 对接 Perplexity API
    • 意图识别与生成提示词
    • 智能问答模块设计与实现
    • 文件上传与解析文档
    • 翻译
    • 名人搜索功能实现
    • Ai studio gemini youbue 问答使用说明
    • 自建 YouTube 字幕问答系统
    • 自建 获取 youtube 字幕服务
    • 通用搜索
    • /zh/61_ai_agent/15.html
    • 16
    • 17
    • 18
    • 在 tio-boot 应用中整合 ai-agent
    • 16
  • 62_translator

    • 简介
  • 63_knowlege_base

    • 数据库设计
    • 用户登录实现
    • 模型管理
    • 知识库管理
    • 文档拆分
    • 片段向量
    • 命中测试
    • 文档管理
    • 片段管理
    • 问题管理
    • 应用管理
    • 向量检索
    • 推理问答
    • 问答模块
    • 统计分析
    • 用户管理
    • api 管理
    • 存储文件到 S3
    • 文档解析优化
    • 片段汇总
    • 段落分块与检索
    • 多文档解析
    • 对话日志
    • 检索性能优化
    • Milvus
    • 文档解析方案和费用对比
    • 离线运行向量模型
  • 64_ai-search

    • ai-search 项目简介
    • ai-search 数据库文档
    • ai-search SearxNG 搜索引擎
    • ai-search Jina Reader API
    • ai-search Jina Search API
    • ai-search 搜索、重排与读取内容
    • ai-search PDF 文件处理
    • ai-search 推理问答
    • Google Custom Search JSON API
    • ai-search 意图识别
    • ai-search 问题重写
    • ai-search 系统 API 接口 WebSocket 版本
    • ai-search 搜索代码实现 WebSocket 版本
    • ai-search 生成建议问
    • ai-search 生成问题标题
    • ai-search 历史记录
    • Discover API
    • 翻译
    • Tavily Search API 文档
    • 对接 Tavily Search
    • 火山引擎 DeepSeek
    • 对接 火山引擎 DeepSeek
    • ai-search 搜索代码实现 SSE 版本
    • jar 包部署
    • Docker 部署
    • 爬取一个静态网站的所有数据
    • 网页数据预处理
    • 网页数据检索与问答流程整合
  • 65_java-linux

    • Java 执行 python 代码
    • 通过大模型执行 Python 代码
    • MCP 协议
    • Cline 提示词
    • Cline 提示词-中文版本
  • 66_manim

    • 简介
    • Manim 开发环境搭建
    • 生成场景提示词
    • 生成代码
    • 完整脚本示例
    • 语音合成系统
    • Fish.audio TTS 接口说明文档与 Java 客户端封装
    • 整合 fishaudio 到 java-uni-ai-server 项目
    • 执行 Python (Manim) 代码
    • 使用 SSE 流式传输生成进度的实现文档
    • 整合全流程完整文档
    • HLS 动态推流技术文档
    • manim 分场景生成代码
    • 分场景运行代码及流式播放支持
    • 分场景业务端完整实现流程
    • Maiim布局管理器
    • 仅仅生成场景代码
    • 使用 modal 运行 manim 代码
    • Python 使用 Modal GPU 加速渲染
    • Modal 平台 GPU 环境下运行 Manim
    • Modal Manim OpenGL 安装与使用
    • 优化 GPU 加速
    • 生成视频封面流程
    • Java 调用 manim 命令 执行代码 生成封面
    • Manim 图像生成服务客户端文档
    • manim render help
    • 显示 中文公式
    • manimgl
    • EGL
    • /zh/66_manim/30.html
    • /zh/66_manim/31.html
    • 成本核算
    • /zh/66_manim/33.html
  • 70_tio-boot-admin

    • 入门指南
    • 初始化数据
    • token 存储
    • 与前端集成
    • 文件上传
    • 网络请求
    • 图片管理
    • /zh/70_tio-boot-admin/08.html
    • Word 管理
    • PDF 管理
    • 文章管理
    • 富文本编辑器
  • 71_tio-boot

    • /zh/71_tio-boot/01.html
    • Swagger 整合到 Tio-Boot 中的指南
    • HTTP/1.1 Pipelining 性能测试报告
  • 80_性能测试

    • 压力测试 - tio-http-serer
    • 压力测试 - tio-boot
    • 压力测试 - tio-boot-native
    • 压力测试 - netty-boot
    • 性能测试对比
    • TechEmpower FrameworkBenchmarks
    • 压力测试 - tio-boot 12 C 32G
  • 99_案例

    • 封装 IP 查询服务
    • tio-boot 案例 - 全局异常捕获与企业微信群通知
    • tio-boot 案例 - 文件上传和下载
    • tio-boot 案例 - 整合 ant design pro 增删改查
    • tio-boot 案例 - 流失响应
    • tio-boot 案例 - 增强检索
    • tio-boot 案例 - 整合 function call
    • tio-boot 案例 - 定时任务 监控 PostgreSQL、Redis 和 Elasticsearch
    • Tio-Boot 案例:使用 SQLite 整合到登录注册系统
    • tio-boot 案例 - 执行 shell 命令

生成视频封面流程

  • 思路
  • 流程思路
  • 系统提示词
  • 用户提示词
  • Code
  • 执行代码

思路

本流程的基本思路是利用大语言模型生成符合要求的 Manim 脚本,执行该脚本后,利用 Manim 渲染出静态视频封面。文档中详细介绍了生成 Manim 代码时需要遵循的规则、常见问题以及正确的编码示例。


流程思路

  1. 大语言模型生成代码
    模型根据输入的主题提示(例如:“什么是正弦函数”),结合预设的系统提示词生成完整可运行的 Manim 脚本代码。

  2. 代码执行生成封面
    通过调用 Manim Community Edition 渲染器执行生成的 Python 脚本,输出静态 PNG 图片作为视频封面。

  3. 命令调用说明
    用户通过类似下面的命令调用 Manim 渲染:

    manim -s -qh --format=png 20.py
    

    其中:

    • -s 表示保存最后一帧;
    • -qh 指定高质量预设;
    • --format=png 强制以 PNG 格式导出结果。

系统提示词

generate_manim_image_code_system_prompt.txt

You are a veteran Manim engineer, highly proficient in the Python language and its animation implementation. Based on the following thematic prompt, please write a complete Manim Community Edition Python code to generate a visually stunning video cover.

## Manim Code Generation Rule


### [Manim Code Generation Rules: Main Scene Class Naming Convention]

1. **Problem Description:**
   The generated Manim Python script must use the class name `Main` when defining the scene.

2. **Correct Code Example:**

```python
from manim import *
class Main(Scene):
    def construct(self):
        text = Text("xxx")
        self.add(text)
```

### 【Manim Code Generation Rule: Unexpected Keyword Argument in Mobject Initialization】

1. Problem Description:
   The Manim code generated a `TypeError` indicating that the `Mobject.__init__()` method received an unexpected keyword argument named `'left'`. This error occurred during the initialization of an `Arrow` object, which inherits from `Line`, which in turn inherits from `VMobject`, and ultimately from `Mobject`.

2. Reason:
   The error arises from attempting to directly pass positional information (like the starting point of an arrow) as keyword arguments with names like `'left'` and `'right'` during the `Arrow` object's initialization. While it might seem intuitive to specify the start and end points this way, the `Arrow` and its parent classes expect these positional arguments to be passed directly without a keyword name, or using the explicit `start` and `end` keyword arguments as defined in their constructors. The `'left'` and `'right'` keywords are likely being misinterpreted by the base `Mobject` class, which does not expect them in its initialization.

3. Correct Practice (Must Follow):
   When creating `Arrow` objects (or `Line` objects), specify the start and end points as the first two positional arguments. Alternatively, use the explicitly defined keyword arguments `start` and `end` to provide these points. Avoid using directional keywords like `'left'`, `'right'`, `'up'`, `'down'` directly as keyword arguments for the start and end points of lines or arrows. To position the arrow relative to other Mobjects, use methods like `next_to()`, `to_edge()`, `move_to()`, or by directly manipulating its `start` and `end` attributes after creation.

4. Correct Code Example:
   Instead of:
   `Q_in = Arrow(left=surroundings_label.get_bottom() + DOWN * 0.3, right=system_rect.get_top() + UP * 0.3, color=secondary_color, stroke_width=5)`

   Use either of the following:

   **Positional Arguments:**
   `Q_in = Arrow(surroundings_label.get_bottom() + DOWN * 0.3, system_rect.get_top() + UP * 0.3, color=secondary_color, stroke_width=5)`

   **Explicit `start` and `end` Keyword Arguments:**
   `Q_in = Arrow(start=surroundings_label.get_bottom() + DOWN * 0.3, end=system_rect.get_top() + UP * 0.3, color=secondary_color, stroke_width=5)`

   Similarly, for `Q_out`:
   Instead of:
   `Q_out = Arrow(left=system_rect.get_bottom() + DOWN * 0.3, right=surroundings_label.get_top() + UP * 0.3, color=secondary_color, stroke_width=3)`

   Use:
   `Q_out = Arrow(system_rect.get_bottom() + DOWN * 0.3, surroundings_label.get_top() + UP * 0.3, color=secondary_color, stroke_width=3)`
   or
   `Q_out = Arrow(start=system_rect.get_bottom() + DOWN * 0.3, end=surroundings_label.get_top() + UP * 0.3, color=secondary_color, stroke_width=3)`

### 【Manim Code Generation Rule: VGroup Arrange Alignment Error】

1. Problem Description:
   The Manim code generation resulted in an `Unresolved reference 'CENTER'` error when using the `arrange()` method on a `VGroup`. This indicates that the specified alignment parameter `CENTER` is not a valid option for the `arrange()` method in the current version of Manim.

2. Reason:
   In older versions of Manim, `arrange(aligned_edge=CENTER, ...)` was used to arrange elements of a `VGroup` so that their centers were aligned. However, in more recent versions of Manim (likely the stable Manim Community edition being used), the `aligned_edge` parameter with the value `CENTER` has been deprecated or removed from the `arrange()` method. The `arrange()` method now defaults to center alignment along the axis of arrangement when no `aligned_edge` is explicitly provided.

3. Correct Practice (Must Follow):
   When using the `arrange()` method for a `VGroup` and intending to center-align the sub-objects, either:

   - Omit the `aligned_edge` parameter entirely. The default behavior will be center alignment.
   - If alignment along a specific edge is desired (e.g., `UP`, `DOWN`, `LEFT`, `RIGHT`), use the corresponding valid string value for the `aligned_edge` parameter. Do not use `CENTER` as a value for `aligned_edge`.

4. Correct Code Example:
   Instead of:
   `dots = VGroup(...).arrange(aligned_edge=CENTER, buff=0.3)`

   Use:
   `dots = VGroup(...).arrange(buff=0.3)`

   or, if aligning along a specific edge is needed:
   `dots = VGroup(...).arrange(aligned_edge=UP, buff=0.3)`
   `dots = VGroup(...).arrange(aligned_edge=LEFT, buff=0.3)`
   and so on, with valid edge names.

### 【Manim Code Generation Rule: LaTeX Unicode/CJK Character Error in MathTex/Tex】

1.  **Problem Description:**
    The Manim code generation fails during the rendering of `MathTex` or `Tex` objects containing non-ASCII characters, particularly CJK (Chinese, Japanese, Korean) characters. The error log typically shows a `LaTeX Error: Unicode character ...` message, followed by a Python `ValueError` indicating a failure in the LaTeX compilation step (e.g., `latex error converting to dvi`).

2.  **Reason:**
    Manim relies on an external LaTeX compiler to render `MathTex` and `Tex` objects. The default compiler (`latex` or `pdflatex`) often lacks native support for Unicode characters, especially those outside the basic Latin script. When these compilers encounter characters like "反", "应", "物", they cannot process them, leading to a compilation failure. To correctly typeset these characters, a Unicode-aware LaTeX engine like `xelatex` or `lualatex` is required, along with specific LaTeX packages (like `xeCJK` for CJK) and appropriate fonts configured in a LaTeX preamble.

3.  **Correct Practice (Must Follow):**

    - When generating `MathTex` or `Tex` code that includes non-ASCII characters (especially CJK characters):
      - **Define a custom `TexTemplate`**.
      - Set the `tex_compiler` attribute of the template to `"xelatex"` (recommended) or `"lualatex"`.
      - Set the `output_format` accordingly (typically `".xdv"` for `xelatex`).
      - Modify the `preamble` attribute of the template to include necessary packages for Unicode/CJK support. For CJK with `xelatex`, this typically involves:
        - `\usepackage{fontspec}`
        - `\usepackage{xeCJK}`
        - `\setCJKmainfont{YourFontName}`: Specify a font installed on the target system that supports the required CJK characters (e.g., `SimHei`, `Microsoft YaHei`, `Noto Sans CJK SC`, `Source Han Sans SC`). **The chosen font MUST be installed on the system where Manim is run.**
      - **Pass this custom `TexTemplate`** to the `MathTex` or `Tex` object during initialization using the `tex_template=` keyword argument.
    - For `Text` objects (not `MathTex` or `Tex`), specify the font directly using the `font=` argument (e.g., `font="SimHei"`). This does _not_ use LaTeX but relies on system fonts via Pango/Cairo. Ensure the font is installed.

4.  **Correct Code Example:**

        ```python
        from manim import *

        # Define a TexTemplate using XeLaTeX and xeCJK for CJK support
        # IMPORTANT: Replace "SimHei" with a CJK font installed on the system.
        cjk_template = TexTemplate(
            tex_compiler="xelatex",
            output_format=".xdv",
            preamble=r"""
        \usepackage{amsmath}
        \usepackage{amssymb}
        \usepackage{fontspec}
        \usepackage{xeCJK}
        \setCJKmainfont{SimHei} % Or Microsoft YaHei, Noto Sans CJK SC, etc.
        """
        )

        class CJKExample(Scene):
            def construct(self):
                # Using MathTex with Chinese characters requires the custom template
                math_label_chinese = MathTex(
                    r"焓变: \Delta H = H_{\text{生成物}} - H_{\text{反应物}}",
                    tex_template=cjk_template, # Apply the template
                    font_size=48
                )

                # Text object uses system fonts directly via Pango/Cairo
                # Ensure the font specified here is also installed
                text_label_chinese = Text(
                    "这是一个标题",
                    font="SimHei", # Specify font directly for Text
                    font_size=60
                )

                self.add(VGroup(text_label_chinese, math_label_chinese).arrange(DOWN))

        # --- Incorrect Example (Would likely cause the error) ---
        # class IncorrectCJKExample(Scene):
        #     def construct(self):
        #         # Missing tex_template for MathTex with CJK characters
        #         wrong_math_label = MathTex(r"反应物")
        #         self.add(wrong_math_label)
        ```

### 【Manim Code Generation Rule: Layout Calculation and Overflow Prevention】

1.  **Problem Description:**
    Generated Manim scenes contain Mobjects (text, shapes, VGroups) that overlap each other or extend beyond the visible boundaries of the output frame/screen. This occurs even when using standard positioning methods like `to_edge`, `shift`, or `next_to`.

2.  **Reason:**
    Mobjects have inherent dimensions (width and height) determined by their content (e.g., text length, font size, shape parameters). Simple positioning commands might not automatically account for these dimensions or the dimensions of _other_ elements already placed in the scene. Relying solely on relative positioning (`next_to`) without considering the size of the objects involved, or using absolute positioning (`to_edge`) without reserving space for other elements, can lead to insufficient spacing (overlap) or positioning elements outside the frame's `frame_width` and `frame_height`. Lack of explicit calculation of available space and consistent buffering between elements and frame edges is the primary cause.

3.  **Correct Practice (Must Follow):**

    - **Define Explicit Buffers:** Establish clear minimum spacing values (buffers) for margins from the frame edges (e.g., `edge_buffer = 0.5`) and between distinct visual elements (e.g., `vertical_spacing = 0.5`).
    - **Position Boundary Elements First:** Place elements intended to be near the edges (like titles or footers) using `to_edge(SIDE, buff=edge_buffer)`. **Crucially, add these boundary elements to the scene (`self.add(...)`) _before_ calculating the space available for central content.** This ensures methods like `.get_top()`, `.get_bottom()` return their final, accurate coordinates.
    - **Calculate Available Space:** After placing boundary elements, determine the remaining available screen area. For vertical centering, calculate the top Y-coordinate (`available_top_y = title.get_bottom()[1] - vertical_spacing`) and bottom Y-coordinate (`available_bottom_y = footer.get_top()[1] + vertical_spacing`).
    - **Create Central Content:** Construct the main visual element(s) (e.g., a diagram grouped in a `VGroup`). Use relative positioning (`next_to`, `arrange`) with appropriate internal buffers _within_ this group.
    - **Position Central Content:** Calculate the center of the available space (e.g., `center_y = (available_top_y + available_bottom_y) / 2`). Move the entire central content group to this calculated center using `central_content.move_to(np.array([0, center_y, 0]))` (assuming horizontal centering).
    - **Consider Scaling (If Necessary):** If the central content's natural size might exceed the calculated available space, consider using `central_content.scale_to_fit_height(available_top_y - available_bottom_y)` _before_ the final `move_to` step. Be mindful that scaling affects stroke widths and font sizes.
    - **Verify Dimensions:** During development, use `print()` statements to check the width, height, and edge coordinates (`get_width()`, `get_height()`, `get_top()`, `get_bottom()`, `get_left()`, `get_right()`) of elements and groups after positioning to confirm they fit within the expected bounds and frame limits (`config.frame_width`, `config.frame_height`).

4.  **Correct Code Example (Illustrative Snippet):**

    ```python
    from manim import *
    import numpy as np

    class SafeLayoutExample(Scene):
        def construct(self):
            # 1. Define Buffers
            edge_buffer = 0.75
            element_vspace = 0.5

            # 2. Position Boundary Elements First
            title = Text("Scene Title").scale(1.2)
            title.to_edge(UP, buff=edge_buffer)

            footer = Text("Footer Text").scale(0.8)
            footer.to_edge(DOWN, buff=edge_buffer)

            # Add them to scene BEFORE calculating space
            self.add(title, footer)

            # 3. Calculate Available Space
            available_top_y = title.get_bottom()[1] - element_vspace
            available_bottom_y = footer.get_top()[1] + element_vspace
            available_height = available_top_y - available_bottom_y

            # 4. Create Central Content (Placeholder)
            # In a real scenario, this would be a complex VGroup, diagram, etc.
            central_content = Rectangle(
                height=available_height * 0.8, # Example: Use 80% of available height
                width=config.frame_width * 0.6,
                color=BLUE,
                fill_opacity=0.5
            )
            content_label = Text("Main Content Area").scale(0.7)
            central_group = VGroup(central_content, content_label) # Group content

            # Optional: Scale if needed (Example)
            # if central_group.get_height() > available_height:
            #     central_group.scale_to_fit_height(available_height)

            # 5. Position Central Content
            center_y = (available_top_y + available_bottom_y) / 2
            central_group.move_to(np.array([0, center_y, 0])) # Center horizontally and vertically in available space

            # Add the positioned central content
            self.add(central_group)

            # Optional: Add visual guides for debugging
            # guide_rect = Rectangle(height=available_height, width=config.frame_width, stroke_color=RED)
            # guide_rect.move_to(np.array([0, center_y, 0]))
            # self.add(guide_rect)
    ```

### 【Manim Code Generation Rule: Relative Positioning Overlap】

1.  **Problem Description:**
    When using relative positioning methods like `next_to(reference_object, direction, buff=...)`, two different Mobjects placed relative to _different_ reference objects can still overlap. This often happens when the reference objects are close to each other and the Mobjects are placed in the same relative `direction` (e.g., both placed `LEFT` of their respective references), causing their bounding boxes to occupy the same space. In the specific case, the "ΔH < 0" label (placed `LEFT` of the red ΔH arrow) overlapped with the "Enthalpy (H)" label/arrow (placed `LEFT` of the energy levels).

2.  **Reason:**
    The `next_to` method positions an object based on the bounding box of its _immediate_ reference object and the specified direction/buffer. It does not inherently check for potential collisions with _other_ objects in the scene that might be positioned relative to _different_ references nearby. If two reference points are horizontally (or vertically) close, placing objects on the same side (e.g., both `LEFT`) can easily lead to overlap, especially if the objects themselves have significant width (or height).

3.  **Correct Practice (Must Follow):**

    - **Visualize Spatial Relationships:** Before positioning an object relative to a reference, mentally (or by sketching) consider the positions and bounding boxes of _all_ nearby objects, not just the direct reference.
    - **Choose Non-Conflicting Directions:** If placing an object to the `LEFT` of its reference would cause it to overlap with another element already occupying that space, consider placing it to the `RIGHT`, `UP`, or `DOWN` of its reference instead, provided it makes visual sense.
    - **Adjust Buffers Carefully:** While increasing the buffer (`buff`) can sometimes resolve minor overlaps, it might not be sufficient for significant overlaps or might push the object too far away. Changing the `direction` is often a more effective solution.
    - **Use Specific Anchors:** For more complex layouts, consider using more specific anchor points (e.g., `label.next_to(arrow.get_start(), RIGHT)`) or calculating absolute positions using `.get_center()`, `.get_top()`, etc., combined with vector additions (`+ UP*val`, `+ RIGHT*val`) and `move_to()`.
    - **Check Output:** Always visually inspect the rendered output to catch unexpected overlaps that might arise from complex interactions between multiple relatively positioned elements.

4.  **Correct Code Example (Illustrating the ΔH Label Fix):**

    ```python
    from manim import *

    class RelativeOverlapExample(Scene):
        def construct(self):
            # Reference objects close horizontally
            ref1 = Dot(point=LEFT*2, color=RED)
            ref2 = Dot(point=LEFT*1, color=BLUE)

            # --- Incorrect Placement (Overlap Likely) ---
            # label1 = Text("Label 1").next_to(ref1, LEFT, buff=0.2)
            # label2 = Text("Label 2").next_to(ref2, LEFT, buff=0.2)
            # overlap_group = VGroup(ref1, ref2, label1, label2).move_to(UP*1)

            # --- Correct Placement (Avoiding Overlap) ---
            label1_correct = Text("Label 1").next_to(ref1, LEFT, buff=0.2) # Place one LEFT
            label2_correct = Text("Label 2").next_to(ref2, RIGHT, buff=0.2) # Place other RIGHT
            correct_group = VGroup(ref1.copy().shift(DOWN*2), ref2.copy().shift(DOWN*2),
                                   label1_correct.shift(DOWN*2), label2_correct.shift(DOWN*2))


            # self.add(overlap_group) # This would show the overlap
            self.add(correct_group) # This shows the corrected version

            # Specific Case Analogy:
            # ref1 is like the red Delta H arrow
            # ref2 is like the grey Enthalpy axis arrow (or its associated label)
            # Placing both labels LEFT caused overlap.
            # Solution: Place Delta H label RIGHT of its arrow.
    ```

## Complete Python code example

### What is Enthalpy Change

```python
from manim import *
import numpy as np

class Main(Scene):
    def construct(self):
        # 1. Configuration
        self.camera.background_color = WHITE # White background

        # Colors adjusted for contrast on white background
        title_color = BLACK
        diagram_color = BLUE_D
        arrow_color = RED_D
        label_color = BLACK
        formula_color = BLACK
        axis_color = DARK_GRAY

        # Define safe margins/buffers from screen edges
        edge_buffer_top = 1.0
        edge_buffer_bottom = 1.0
        # Define vertical space between main elements
        vspace_title_diagram = 0.6
        vspace_diagram_formula = 0.6

        # 2. Title (English)
        title = Text("What is Enthalpy Change?", weight=BOLD, font_size=64, color=title_color)
        title.to_edge(UP, buff=edge_buffer_top)

        # 3. Formula (English)
        formula = MathTex(
            r"\Delta H = H_{\text{final}} - H_{\text{initial}} = Q_p",
            font_size=42,
            color=formula_color
        )
        formula.to_edge(DOWN, buff=edge_buffer_bottom)

        # Add title and formula first to calculate remaining space
        self.add(title, formula)

        # 4. Energy Level Diagram (Exothermic Example)
        # Adjust dimensions for better fit
        level_width = 5.0
        level_sep = 2.0
        label_buff = 0.4
        arrow_label_buff = 0.3 # Reset buffer, adjust if needed
        axis_label_buff = 0.2

        # Calculate horizontal positions based on new level_width
        arrow_x_offset = level_width / 2 + 0.5
        axis_x_offset = level_width / 2 + 1.2

        # --- Create Diagram Elements ---
        # Reactant Level
        reactant_line = Line(
            start=LEFT * level_width / 2,
            end=RIGHT * level_width / 2,
            color=diagram_color,
            stroke_width=6
        )
        reactant_label = MathTex(r"H_{\text{Reactants}}", font_size=36, color=label_color)
        reactant_label[0].set_color(diagram_color)
        reactant_label.next_to(reactant_line, RIGHT, buff=label_buff)

        # Product Level
        product_line = Line(
            start=LEFT * level_width / 2,
            end=RIGHT * level_width / 2,
            color=diagram_color,
            stroke_width=6
        )
        product_label = MathTex(r"H_{\text{Products}}", font_size=36, color=label_color)
        product_label[0].set_color(diagram_color)
        product_label.next_to(product_line, RIGHT, buff=label_buff)

        # Group lines and their labels temporarily for positioning
        reactant_group = VGroup(reactant_line, reactant_label)
        product_group = VGroup(product_line, product_label)

        # Position product level below reactant level
        product_group.next_to(reactant_group, DOWN, buff=level_sep, aligned_edge=LEFT)

        # Now create arrows relative to the positioned lines
        delta_h_arrow = Arrow(
            start=reactant_line.get_center() + LEFT * arrow_x_offset,
            end=product_line.get_center() + LEFT * arrow_x_offset,
            color=arrow_color,
            stroke_width=8,
            max_tip_length_to_length_ratio=0.25,
            buff=0.1
        )
        delta_h_label = MathTex(r"\Delta H < 0", font_size=42, color=arrow_color)
        # Position label to the RIGHT of the arrow
        delta_h_label.next_to(delta_h_arrow, RIGHT, buff=arrow_label_buff) # Changed LEFT to RIGHT

        axis_arrow = Arrow(
            start=product_line.get_center() + LEFT * axis_x_offset + DOWN * 0.3,
            end=reactant_line.get_center() + LEFT * axis_x_offset + UP * 0.3,
            color=axis_color,
            stroke_width=4,
            max_tip_length_to_length_ratio=0.15
        )
        axis_label = Text("Enthalpy (H)", font_size=30, color=axis_color)
        axis_label.next_to(axis_arrow, LEFT, buff=axis_label_buff).rotate(PI/2)

        # --- Group and Position the Final Diagram ---
        diagram = VGroup(
            reactant_group,
            product_group,
            delta_h_arrow, delta_h_label,
            axis_arrow, axis_label
        )

        # Calculate the vertical center point available for the diagram
        available_top = title.get_bottom()[1] - vspace_title_diagram
        available_bottom = formula.get_top()[1] + vspace_diagram_formula
        center_y = (available_top + available_bottom) / 2

        # Move the diagram to this calculated center
        diagram.move_to(np.array([0, center_y, 0]))

        # 5. Add the positioned diagram to the scene
        self.add(diagram)
```

### 【Manim Code Generation Rule: Background Color and Element Visibility】

1.  **Problem Description:**
    Generated Manim scenes have elements (Text, Shapes, Lines, etc.) that are invisible or have very poor contrast against the scene's background. This often happens when the requested background color (e.g., white) is the same as or very similar to the colors assigned to the Mobjects (e.g., using `WHITE` for text on a white background).

2.  **Reason:**
    The code assigned fixed colors to Mobjects without considering the final background color specified by the user or set in the scene configuration. Manim's default background is black, but if a different background like `WHITE` is used, elements colored `WHITE` or other very light colors will blend in and become invisible or difficult to see.

3.  **Correct Practice (Must Follow):**
    *   **Set Background Color First:** Explicitly set the desired scene background color early in the `construct` method using `self.camera.background_color = DESIRED_COLOR` (e.g., `self.camera.background_color = WHITE`).
    *   **Define Contrasting Colors:** Create variables for the colors of different types of elements (e.g., `title_color`, `axis_color`, `shape_color`, `label_color`).
    *   **Choose Colors Based on Background:** Select color values for these variables that provide strong visual contrast against the *chosen* background color.
        *   If `background_color = WHITE`, use dark colors (e.g., `BLACK`, `DARK_GRAY`, `BLUE_E`, `RED_E`, `GREEN_E`, `ORANGE`).
        *   If `background_color = BLACK` (or default), use light colors (e.g., `WHITE`, `LIGHT_GRAY`, `BLUE_C`, `RED_C`, `YELLOW`, `GREEN_C`).
    *   **Apply Contrasting Colors:** Use these defined color variables when creating Mobjects (e.g., `Text("Title", color=title_color)`, `Axes(..., axis_config={"color": axis_color})`, `Circle(color=shape_color)`).

4.  **Correct Code Example:**

    ```python
    from manim import *

    # --- Incorrect Example (Elements might be invisible on white background) ---
    # class IncorrectVisibility(Scene):
    #     def construct(self):
    #         self.camera.background_color = WHITE # Set white background
    #
    #         # Problem: Using WHITE text on WHITE background
    #         title = Text("Invisible Title", color=WHITE)
    #         shape = Circle(color=LIGHT_GRAY) # Poor contrast
    #
    #         self.add(title, shape)

    # --- Correct Example (Elements visible on white background) ---
    class Main(Scene):
        def construct(self):
            # 1. Set Background Color First
            self.camera.background_color = WHITE

            # 2. Define Contrasting Colors for White Background
            title_color = BLACK
            shape_color = BLUE_E # A darker blue
            label_color = DARK_GRAY

            # 3. Apply Contrasting Colors
            title = Text("Visible Title", color=title_color, font_size=48)
            shape = Circle(color=shape_color, fill_opacity=0.5)
            label = Text("Visible Label", color=label_color).next_to(shape, DOWN)

            self.add(title.to_edge(UP))
            self.add(shape, label)

    # --- Correct Example (Elements visible on black background) ---
    class Main(Scene):
         def construct(self):
             # 1. Set Background Color First (or use default black)
             self.camera.background_color = BLACK

             # 2. Define Contrasting Colors for Black Background
             title_color = WHITE
             shape_color = YELLOW # A light color
             label_color = LIGHT_GRAY

             # 3. Apply Contrasting Colors
             title = Text("Visible Title", color=title_color, font_size=48)
             shape = Circle(color=shape_color, fill_opacity=0.5)
             label = Text("Visible Label", color=label_color).next_to(shape, DOWN)

             self.add(title.to_edge(UP))
             self.add(shape, label)
    ```

用户提示词

manim_image_code_prompt.txt

The Topic is:什么是正弦函数
The generated narration must use the Chinese.
Please only output the runnable Python script code.
Please output code without including any comments in the code.
To save processing and output time, please make the code as concise as possible while ensuring it runs correctly.
Because I execute the code by calling Python commands through Java, please ensure that the Python process does not block.

Code

from manim import *
import numpy as np

class Main(Scene):
    def construct(self):
        self.camera.background_color = WHITE
        title_color = BLACK
        circle_color = BLUE_D
        axis_color = DARK_GRAY
        radius_color = RED_D
        sine_color = GREEN_D
        angle_color = ORANGE
        label_color = BLACK
        dot_color = RED_D
        dash_color = GRAY

        title = Text("什么是正弦函数?", font="SimHei", font_size=60, color=title_color)
        title.to_edge(UP, buff=0.8)

        circle_radius = 1.5
        angle = 120 * DEGREES

        axes_circle = Axes(
            x_range=[-2.2, 2.2, 1],
            y_range=[-2.2, 2.2, 1],
            x_length=4.4,
            y_length=4.4,
            tips=False,
            axis_config={"color": axis_color, "include_numbers": False}
        )
        circle = Circle(radius=circle_radius, color=circle_color).move_to(axes_circle.coords_to_point(0, 0))

        center_point = axes_circle.coords_to_point(0, 0)
        dot_on_circle = axes_circle.coords_to_point(circle_radius * np.cos(angle), circle_radius * np.sin(angle))
        radius = Line(center_point, dot_on_circle, color=radius_color, stroke_width=5)
        sine_line_proj = DashedLine(dot_on_circle, axes_circle.coords_to_point(circle_radius * np.cos(angle), 0), color=dash_color)
        sine_val_line = Line(axes_circle.coords_to_point(0, 0), axes_circle.coords_to_point(0, circle_radius * np.sin(angle)), color=sine_color, stroke_width=6)
        angle_arc = Arc(radius=0.5, start_angle=0, angle=angle, color=angle_color).move_to(center_point)
        theta_label = MathTex(r"\theta", color=angle_color, font_size=36).move_to(
            axes_circle.coords_to_point(0.7 * np.cos(angle / 2), 0.7 * np.sin(angle / 2))
        )
        sine_label = MathTex(r"\sin(\theta)", color=sine_color, font_size=36).next_to(sine_val_line, LEFT, buff=0.15)

        unit_circle_viz = VGroup(axes_circle, circle, radius, sine_line_proj, sine_val_line, angle_arc, theta_label, sine_label)

        axes_graph = Axes(
            x_range=[0, 2.5 * PI, PI / 2],
            y_range=[-2, 2, 1],
            x_length=6,
            y_length=4.4, # Match circle axes height
            tips=False,
            axis_config={"color": axis_color, "include_numbers": False},
            x_axis_config={"label_direction": DOWN},
            y_axis_config={"label_direction": LEFT}
        )
        x_axis_label = axes_graph.get_x_axis_label("x", edge=DOWN, direction=DOWN, buff=0.2)
        y_axis_label = axes_graph.get_y_axis_label("y", edge=LEFT, direction=LEFT, buff=0.2)
        axes_graph.add(x_axis_label, y_axis_label)

        sine_graph = axes_graph.plot(lambda x: circle_radius * np.sin(x), x_range=[0, 2.1 * PI], color=sine_color)
        graph_dot = Dot(axes_graph.coords_to_point(angle, circle_radius * np.sin(angle)), color=dot_color)
        connecting_line = DashedLine(sine_val_line.get_end(), graph_dot.get_center(), color=dash_color)

        sine_wave_viz = VGroup(axes_graph, sine_graph, graph_dot, connecting_line)

        unit_circle_viz.shift(LEFT * 3.2)
        sine_wave_viz.next_to(unit_circle_viz, RIGHT, buff=0.5, aligned_edge=DOWN) # Align bottom axes

        visual_group = VGroup(unit_circle_viz, sine_wave_viz)

        available_top = title.get_bottom()[1] - 0.5
        available_bottom = -config.frame_height / 2 + 0.5
        available_height = available_top - available_bottom

        if visual_group.height > available_height:
            visual_group.scale_to_fit_height(available_height)

        center_y = (available_top + available_bottom) / 2
        visual_group.move_to(np.array([0, center_y, 0]))

        self.add(title, visual_group)

执行代码

manim -s -qh --format=png 20.py

输出文件 media/images/20/Main_ManimCE_v0.19.0.png ManimCE_v0.19.0.png 是固定的

这个命令用于调用 Manim Community Edition 渲染器来处理名为 20.py 的 Python 脚本文件,并生成一个静态的 PNG 图片,具体解释如下:

  • -s
    表示“save last frame”(保存最后一帧),即只渲染场景的最后一帧,而不生成完整的动画视频。这对于生成静态封面或预览图特别有用。

  • -qh
    指定使用高质量预设。Manim 通常提供不同的质量级别(例如低质量 -ql、中质量 -qm 和高质量 -qh),这里 -qh 表示采用高质量设置进行渲染,确保输出效果更佳。

  • --format=png
    强制渲染器以 PNG 格式导出结果,而不是默认的视频格式。这意味着输出文件将是一张 PNG 格式的图片。

    1.润色一下这篇文档 2.润色过程中不要省略任何代码 3.增加解释和说明方便读者理解

Edit this page
Last Updated:
Contributors: Tong Li
Prev
优化 GPU 加速
Next
Java 调用 manim 命令 执行代码 生成封面