Tom1986 commited on
Commit
a2e2aa0
·
1 Parent(s): e1d82ba

Deploy Genie TTS

Browse files
Files changed (7) hide show
  1. .gitignore +196 -0
  2. DEPLOYMENT.md +151 -0
  3. PROJECT_SUMMARY.md +118 -0
  4. README.md.space +18 -0
  5. app.py +539 -0
  6. guidance.md +67 -0
  7. requirements.txt +40 -0
.gitignore ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/#use-with-ide
110
+ .pdm.toml
111
+
112
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
113
+ __pypackages__/
114
+
115
+ # Celery stuff
116
+ celerybeat-schedule
117
+ celerybeat.pid
118
+
119
+ # SageMath parsed files
120
+ *.sage.py
121
+
122
+ # Environments
123
+ .env
124
+ .venv
125
+ env/
126
+ venv/
127
+ ENV/
128
+ env.bak/
129
+ venv.bak/
130
+
131
+ # Spyder project settings
132
+ .spyderproject
133
+ .spyproject
134
+
135
+ # Rope project settings
136
+ .ropeproject
137
+
138
+ # mkdocs documentation
139
+ /site
140
+
141
+ # mypy
142
+ .mypy_cache/
143
+ .dmypy.json
144
+ dmypy.json
145
+
146
+ # Pyre type checker
147
+ .pyre/
148
+
149
+ # pytype static type analyzer
150
+ .pytype/
151
+
152
+ # Cython debug symbols
153
+ cython_debug/
154
+
155
+ # Hugging Face specific
156
+ .cache/
157
+ huggingface_hub/
158
+ models/
159
+ checkpoints/
160
+
161
+ # Model and audio cache files
162
+ *.wav
163
+ *.mp3
164
+ *.onnx
165
+ *.bin
166
+ *.pth
167
+ *.ckpt
168
+
169
+ # Temporary files
170
+ tmp/
171
+ temp/
172
+ *.tmp
173
+
174
+ # OS specific
175
+ .DS_Store
176
+ .DS_Store?
177
+ ._*
178
+ .Spotlight-V100
179
+ .Trashes
180
+ ehthumbs.db
181
+ Thumbs.db
182
+
183
+ # IDE
184
+ .vscode/
185
+ .idea/
186
+ *.swp
187
+ *.swo
188
+ *~
189
+
190
+ # Log files
191
+ *.log
192
+ logs/
193
+
194
+ # Gradio temporary files
195
+ gradio_cached_examples/
196
+ flagged/
DEPLOYMENT.md ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Hugging Face Space 部署指南
2
+
3
+ ## 📋 准备工作
4
+
5
+ 确保您已经有以下文件:
6
+ - `app.py` - 主要的 Gradio 应用
7
+ - `requirements.txt` - Python 依赖
8
+ - `README.md` - 项目说明文档
9
+ - `.gitignore` - Git 忽略文件
10
+ - `README.md.space` - Hugging Face Space 配置(需要重命名为 README.md)
11
+
12
+ ## 🚀 部署步骤
13
+
14
+ ### 1. 创建 Hugging Face Space
15
+
16
+ 1. 登录 [Hugging Face](https://huggingface.co/)
17
+ 2. 点击您的头像 → "New Space"
18
+ 3. 填写 Space 信息:
19
+ - **Space name**: `GENIE` (或其他您喜欢的名称)
20
+ - **License**: MIT
21
+ - **SDK**: Gradio
22
+ - **Hardware**: CPU (免费) 或 GPU (付费)
23
+ - **Visibility**: Public
24
+
25
+ ### 2. 上传文件
26
+
27
+ 有两种方式上传文件:
28
+
29
+ #### 方式 A: Git 上传(推荐)
30
+ ```bash
31
+ # 1. 克隆您创建的 Space
32
+ git clone https://huggingface.co/spaces/YOUR_USERNAME/GENIE
33
+ cd GENIE
34
+
35
+ # 2. 复制所有文件到此目录
36
+ # 将 README.md.space 重命名为 README.md(会替换默认的)
37
+
38
+ # 3. 提交并推送
39
+ git add .
40
+ git commit -m "Initial Genie TTS deployment"
41
+ git push
42
+ ```
43
+
44
+ #### 方式 B: Web 界面上传
45
+ 1. 在 Space 页面点击 "Files" 标签
46
+ 2. 点击 "Add file" → "Upload file"
47
+ 3. 上传所有必要文件
48
+ 4. 将 `README.md.space` 的内容复制到默认的 `README.md` 中
49
+
50
+ ### 3. 配置 Space
51
+
52
+ 确保 README.md 文件开头包含正确的 YAML 元数据:
53
+
54
+ ```yaml
55
+ ---
56
+ title: 🔮 Genie TTS - AI语音合成
57
+ emoji: 🎵
58
+ colorFrom: purple
59
+ colorTo: pink
60
+ sdk: gradio
61
+ sdk_version: 4.44.0
62
+ app_file: app.py
63
+ pinned: false
64
+ license: mit
65
+ short_description: 基于Genie的日语文本转语音系统
66
+ tags:
67
+ - text-to-speech
68
+ - japanese
69
+ - gpt-sovits
70
+ - audio
71
+ - ai
72
+ - tts
73
+ - voice-synthesis
74
+ ---
75
+ ```
76
+
77
+ ### 4. 等待构建
78
+
79
+ - Space 将自动开始构建
80
+ - 首次构建可能需要 5-10 分钟
81
+ - 您可以在 "Logs" 标签中查看构建进度
82
+
83
+ ### 5. 测试应用
84
+
85
+ 1. 构建完成后,访问您的 Space
86
+ 2. 测试基本功能:
87
+ - 选择角色 "misono_mika"
88
+ - 输入日语文本,例如:"おはようございます"
89
+ - 点击 "开始合成"
90
+ - 等待音频生成
91
+
92
+ ## ⚠️ 注意事项
93
+
94
+ ### 性能考虑
95
+ - **首次运行**: 需要下载约 200MB 的模型文件,可能需要 30-60 秒
96
+ - **后续使用**: 模型会被缓存,合成速度较快(5-15 秒)
97
+ - **并发限制**: 免费 CPU 硬件建议限制并发用户数
98
+
99
+ ### 内存管理
100
+ - Genie TTS 需要约 500MB-1GB RAM
101
+ - 如果遇到内存不足错误,考虑升级到付费硬件
102
+
103
+ ### 错误排查
104
+
105
+ 1. **依赖安装错误**
106
+ - 检查 `requirements.txt` 中的版本冲突
107
+ - 查看构建日志中的错误信息
108
+
109
+ 2. **模型下载失败**
110
+ - 通常是网络问题,等待几分钟后重试
111
+ - 检查 Hugging Face Hub 的连接状态
112
+
113
+ 3. **音频生成失败**
114
+ - 检查输入文本是否为日语
115
+ - 验证文本长度不超过 500 字符
116
+
117
+ ## 🔧 高级配置
118
+
119
+ ### 自定义硬件
120
+ 如果需要更好的性能,可以升级硬件:
121
+ - **CPU Upgrade**: 更快的处理速度
122
+ - **GPU T4**: 显著提升推理速度(需要付费)
123
+
124
+ ### 环境变量
125
+ 在 Space 设置中添加环境变量:
126
+ ```
127
+ HF_HUB_ENABLE_PROGRESS_BAR=1
128
+ TOKENIZERS_PARALLELISM=false
129
+ ```
130
+
131
+ ### 域名和访问
132
+ - Space URL: `https://huggingface.co/spaces/YOUR_USERNAME/GENIE`
133
+ - 可以申请自定义域名(Pro 功能)
134
+
135
+ ## 📊 监控和维护
136
+
137
+ - 查看 Space 使用统计
138
+ - 监控错误日志
139
+ - 定期更新依赖包
140
+ - 根据用户反馈优化功能
141
+
142
+ ## 🤝 社区分享
143
+
144
+ 部署成功后,您可以:
145
+ - 在社交媒体分享您的 Space
146
+ - 在相关社区发布
147
+ - 收集用户反馈并持续改进
148
+
149
+ ---
150
+
151
+ 祝您部署成功!如有问题,可以参考 [Hugging Face Spaces 官方文档](https://huggingface.co/docs/hub/spaces)。
PROJECT_SUMMARY.md ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🎯 项目完成总结
2
+
3
+ ## ✅ 已完成的工作
4
+
5
+ 我已经为您成功创建了一个完整的 Hugging Face Spaces 部署方案,将 Genie TTS 模型部署为 Web 应用。
6
+
7
+ ### 📁 文件结构
8
+ ```
9
+ genie/
10
+ ├── app.py # 主要的 Gradio 应用文件
11
+ ├── requirements.txt # Python 依赖包列表
12
+ ├── README.md # 项目说明文档
13
+ ├── README.md.space # Hugging Face Space 配置文件
14
+ ├── .gitignore # Git 忽略文件配置
15
+ ├── DEPLOYMENT.md # 详细部署指南
16
+ └── PROJECT_SUMMARY.md # 项目总结(本文件)
17
+ ```
18
+
19
+ ### 🔧 核心功能实现
20
+
21
+ #### 1. Gradio Web 界面 (`app.py`)
22
+ - **多标签页设计**: 语音合成、示例教程、项目信息
23
+ - **智能角色管理**: 自动加载预训练角色模型
24
+ - **进度显示**: 实时显示模型加载和合成进度
25
+ - **错误处理**: 友好的错误提示和重试机制
26
+ - **音频输出**: 支持在线播放和下载
27
+ - **示例库**: 内置多个日语示例文本
28
+
29
+ #### 2. 依赖管理 (`requirements.txt`)
30
+ - **核心包**: genie-tts, gradio, torch
31
+ - **音频处理**: librosa, soundfile, scipy
32
+ - **模型推理**: onnxruntime
33
+ - **Hugging Face 集成**: huggingface-hub, transformers
34
+ - **系统监控**: psutil, rich
35
+
36
+ #### 3. 模型管理系统
37
+ - **自动下载**: 首次使用自动从 Hugging Face 下载模型
38
+ - **缓存机制**: 智能缓存管理,避免重复下载
39
+ - **内存优化**: LRU 缓存和资源清理
40
+ - **错误恢复**: 网络错误重试和失败处理
41
+
42
+ #### 4. 文本处理优化
43
+ - **预处理**: 自动文本清理和标点符号规范化
44
+ - **长度限制**: 防止过长文本导致的问题
45
+ - **编码处理**: 正确处理日语字符编码
46
+ - **分句支持**: 自动分句处理长文本
47
+
48
+ ### 🌟 应用特色
49
+
50
+ 1. **用户友好界面**
51
+ - 现代化设计,响应式布局
52
+ - 多标签页组织,信息层次清晰
53
+ - 实时进度反馈和状态显示
54
+ - 丰富的示例和使用指南
55
+
56
+ 2. **性能优化**
57
+ - CPU 优化推理,无需 GPU
58
+ - 智能缓存管理
59
+ - 内存使用监控
60
+ - 异常处理和资源清理
61
+
62
+ 3. **部署友好**
63
+ - 完整的依赖声明
64
+ - 环境变量配置
65
+ - 详细的部署指南
66
+ - Git 版本控制支持
67
+
68
+ ## 🚀 部署步骤
69
+
70
+ ### 快速部署
71
+ 1. 访问 [Hugging Face Spaces](https://huggingface.co/spaces)
72
+ 2. 创建新的 Space,选择 Gradio SDK
73
+ 3. 上传所有文件(将 `README.md.space` 重命名为 `README.md`)
74
+ 4. 等待自动构建完成
75
+
76
+ ### 详细步骤
77
+ 请参考 `DEPLOYMENT.md` 文件中的详细指南。
78
+
79
+ ## 📊 预期性能
80
+
81
+ - **首次启动**: 30-60秒(下载模型)
82
+ - **后续合成**: 5-15秒每段文本
83
+ - **内存需求**: ~500MB RAM
84
+ - **存储需求**: ~200MB(模型文件)
85
+
86
+ ## 🎯 支持功能
87
+
88
+ - ✅ 日语文本转语音
89
+ - ✅ 预训练角色 (misono_mika)
90
+ - ✅ 实时音频播放
91
+ - ✅ 音频文件下载
92
+ - ✅ 示例文本库
93
+ - ✅ 错误处理和重试
94
+ - ✅ 响应式 Web 界面
95
+
96
+ ## 🔮 未来扩展
97
+
98
+ 可以考虑的功能扩展:
99
+ - 添加更多预训练角色
100
+ - 支持中文和英文TTS
101
+ - 批量文本处理
102
+ - 语音风格调节
103
+ - API 接口支持
104
+
105
+ ## ⚠️ 注意事项
106
+
107
+ 1. **首次使用**: 需要下载模型文件,请确保网络连接稳定
108
+ 2. **文本限制**: 目前主要支持日语,建议文本长度控制在500字符以内
109
+ 3. **并发限制**: 免费版 Hugging Face Spaces 有并发限制
110
+ 4. **模型版本**: 基于 GPT-SoVITS V2,支持高质量语音合成
111
+
112
+ ## 🎉 部署成功!
113
+
114
+ 您现在可以按照 `DEPLOYMENT.md` 中的指南将此应用部署到 Hugging Face Spaces 上。部署成功后,用户可以通过 Web 界面轻松使用 Genie TTS 进行日语语音合成。
115
+
116
+ ---
117
+
118
+ **祝您部署顺利!如有任何问题,请参考相关文档或联系开发者。** 🚀
README.md.space ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ title: 🔮 Genie TTS - AI语音合成
2
+ emoji: 🎵
3
+ colorFrom: purple
4
+ colorTo: pink
5
+ sdk: gradio
6
+ sdk_version: 4.44.0
7
+ app_file: app.py
8
+ pinned: false
9
+ license: mit
10
+ short_description: 基于Genie的日语文本转语音系统
11
+ tags:
12
+ - text-to-speech
13
+ - japanese
14
+ - gpt-sovits
15
+ - audio
16
+ - ai
17
+ - tts
18
+ - voice-synthesis
app.py ADDED
@@ -0,0 +1,539 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import tempfile
4
+ import logging
5
+ import warnings
6
+ import subprocess
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ # 设置日志
11
+ logging.basicConfig(level=logging.INFO)
12
+ logger = logging.getLogger(__name__)
13
+
14
+ # 禁用一些警告
15
+ warnings.filterwarnings("ignore", category=FutureWarning)
16
+ warnings.filterwarnings("ignore", category=UserWarning)
17
+
18
+ def install_genie_tts():
19
+ """安装genie-tts包"""
20
+ try:
21
+ import genie_tts
22
+ logger.info("genie-tts已安装")
23
+ return True
24
+ except ImportError:
25
+ logger.info("正在安装genie-tts...")
26
+ try:
27
+ subprocess.check_call([sys.executable, "-m", "pip", "install", "genie-tts"])
28
+ import genie_tts
29
+ logger.info("genie-tts安装成功")
30
+ return True
31
+ except Exception as e:
32
+ logger.error(f"安装genie-tts失败: {e}")
33
+ return False
34
+
35
+ # 安装Genie TTS
36
+ install_success = install_genie_tts()
37
+
38
+ if install_success:
39
+ try:
40
+ import genie_tts as genie
41
+ logger.info("Genie TTS导入成功")
42
+ except ImportError as e:
43
+ logger.error(f"导入Genie TTS失败: {e}")
44
+ genie = None
45
+ else:
46
+ genie = None
47
+
48
+ class GenieTTSInterface:
49
+ def __init__(self):
50
+ self.available_characters = ['misono_mika'] # 预定义角色
51
+ self.current_character = None
52
+ self.model_cache_dir = self.setup_cache_directory()
53
+ self.is_initialized = False
54
+
55
+ def setup_cache_directory(self):
56
+ """设置模型缓存目录"""
57
+ cache_dir = os.path.join(tempfile.gettempdir(), "genie_tts_cache")
58
+ os.makedirs(cache_dir, exist_ok=True)
59
+ return cache_dir
60
+
61
+ def check_model_availability(self, character_name):
62
+ """检查模型是否已缓存"""
63
+ model_files = [
64
+ 'prompt.wav', 'prompt_wav.json',
65
+ 't2s_encoder_fp32.onnx', 't2s_first_stage_decoder_fp32.onnx',
66
+ 't2s_stage_decoder_fp32.onnx', 'vits_fp32.onnx'
67
+ ]
68
+
69
+ character_cache_dir = os.path.join(self.model_cache_dir, character_name)
70
+ if not os.path.exists(character_cache_dir):
71
+ return False
72
+
73
+ for file_name in model_files:
74
+ if not os.path.exists(os.path.join(character_cache_dir, file_name)):
75
+ return False
76
+ return True
77
+
78
+ def initialize_genie(self):
79
+ """初始化Genie TTS环境"""
80
+ if self.is_initialized:
81
+ return True
82
+
83
+ try:
84
+ # 设置环境变量以优化下载
85
+ os.environ["HF_HUB_ENABLE_PROGRESS_BAR"] = "1"
86
+ os.environ["TOKENIZERS_PARALLELISM"] = "false" # 避免警告
87
+
88
+ # 设置缓存目录
89
+ if hasattr(genie, '_internal'):
90
+ logger.info("Genie TTS环境初始化成功")
91
+
92
+ self.is_initialized = True
93
+ return True
94
+
95
+ except Exception as e:
96
+ logger.error(f"初始化Genie TTS失败: {e}")
97
+ return False
98
+
99
+ def load_character(self, character_name):
100
+ """加载角色模型"""
101
+ if not genie:
102
+ return None, "Genie TTS未正确安装"
103
+
104
+ if not self.initialize_genie():
105
+ return None, "Genie TTS初始化失败"
106
+
107
+ try:
108
+ logger.info(f"正在加载角色: {character_name}")
109
+
110
+ # 检查模型是否已缓存
111
+ if self.check_model_availability(character_name):
112
+ logger.info(f"使用缓存的模型: {character_name}")
113
+ else:
114
+ logger.info(f"首次下载模型: {character_name},请稍候...")
115
+
116
+ # 加载预定义角色(这会自动处理下载)
117
+ genie.load_predefined_character(character_name)
118
+ self.current_character = character_name
119
+
120
+ return f"角色 {character_name} 加载成功!", ""
121
+
122
+ except Exception as e:
123
+ error_msg = str(e)
124
+ logger.error(f"加载角色失败: {error_msg}")
125
+
126
+ # 提供更友好的错误信息
127
+ if "network" in error_msg.lower() or "connection" in error_msg.lower():
128
+ return None, "网络连接错误,请检查网络连接后重试"
129
+ elif "disk space" in error_msg.lower():
130
+ return None, "磁盘空间不足,请清理空间后重试"
131
+ elif "timeout" in error_msg.lower():
132
+ return None, "下载超时,请重试"
133
+ else:
134
+ return None, f"加载角色失败: {error_msg}"
135
+
136
+ def estimate_download_size(self, character_name):
137
+ """估算下载大小"""
138
+ # 基于Genie模型的实际大小
139
+ model_sizes = {
140
+ 'misono_mika': 180 # MB
141
+ }
142
+ return model_sizes.get(character_name, 200)
143
+
144
+ def cleanup_cache(self):
145
+ """清理缓存"""
146
+ try:
147
+ import shutil
148
+ if os.path.exists(self.model_cache_dir):
149
+ shutil.rmtree(self.model_cache_dir)
150
+ self.setup_cache_directory()
151
+ logger.info("缓存清理完成")
152
+ return True
153
+ except Exception as e:
154
+ logger.error(f"清理缓存失败: {e}")
155
+ return False
156
+
157
+ def synthesize_speech(self, text, character_name, play_audio=False):
158
+ """文本转语音 - 增强版"""
159
+ if not genie:
160
+ return None, "Genie TTS未正确安装"
161
+
162
+ if not text.strip():
163
+ return None, "请输入要合成的文本"
164
+
165
+ # 文本长度检查
166
+ if len(text) > 500:
167
+ return None, "文本过长(超过500字符),请缩短文本长度"
168
+
169
+ if character_name != self.current_character:
170
+ status, error = self.load_character(character_name)
171
+ if error:
172
+ return None, error
173
+
174
+ try:
175
+ # 文本预处理
176
+ processed_text = self.preprocess_text(text)
177
+
178
+ # 创建临时文件保存音频
179
+ with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp_file:
180
+ output_path = tmp_file.name
181
+
182
+ logger.info(f"正在合成语音: {processed_text[:50]}...")
183
+
184
+ # 设置内存限制环境变量
185
+ original_env = os.environ.get('PYTORCH_JIT_USE_NNC_NOT_NVFUSER', None)
186
+ os.environ['PYTORCH_JIT_USE_NNC_NOT_NVFUSER'] = '1'
187
+
188
+ try:
189
+ # 执行TTS
190
+ genie.tts(
191
+ character_name=character_name,
192
+ text=processed_text,
193
+ play=False, # 在服务器环境不播放
194
+ split_sentence=True,
195
+ save_path=output_path
196
+ )
197
+ finally:
198
+ # 恢复环境变量
199
+ if original_env is None and 'PYTORCH_JIT_USE_NNC_NOT_NVFUSER' in os.environ:
200
+ del os.environ['PYTORCH_JIT_USE_NNC_NOT_NVFUSER']
201
+ elif original_env is not None:
202
+ os.environ['PYTORCH_JIT_USE_NNC_NOT_NVFUSER'] = original_env
203
+
204
+ # 验证输出文件
205
+ if not os.path.exists(output_path):
206
+ return None, "语音合成失败:输出文件未生成"
207
+
208
+ file_size = os.path.getsize(output_path)
209
+ if file_size == 0:
210
+ return None, "语音合成失败:输出文件为空"
211
+ elif file_size < 1000: # 小于1KB可能是错误
212
+ return None, "语音合成失败:输出文件异常小"
213
+
214
+ logger.info(f"语音合成成功,文件大小: {file_size/1024:.1f}KB")
215
+ return output_path, ""
216
+
217
+ except Exception as e:
218
+ error_msg = str(e)
219
+ logger.error(f"语音合成失败: {error_msg}")
220
+
221
+ # 提供更详细的错误信息
222
+ if "out of memory" in error_msg.lower() or "memory" in error_msg.lower():
223
+ return None, "内存不足,请尝试缩短文本或重启应用"
224
+ elif "cuda" in error_msg.lower():
225
+ return None, "GPU相关错误,正在使用CPU模式重试"
226
+ elif "model" in error_msg.lower():
227
+ return None, "模型加载错误,请重新选择角色"
228
+ elif "timeout" in error_msg.lower():
229
+ return None, "处理超时,请尝试缩短文本"
230
+ else:
231
+ return None, f"语音合成失败: {error_msg}"
232
+
233
+ def preprocess_text(self, text):
234
+ """文本预处理"""
235
+ # 基本清理
236
+ text = text.strip()
237
+
238
+ # 替换常见的问题字符
239
+ replacements = {
240
+ '"': '"',
241
+ '"': '"',
242
+ ''': "'",
243
+ ''': "'",
244
+ '—': '一',
245
+ '–': '-',
246
+ }
247
+
248
+ for old, new in replacements.items():
249
+ text = text.replace(old, new)
250
+
251
+ # 确保句子有适当的标点
252
+ if text and not text.endswith(('。', '!', '?', '.', '!', '?')):
253
+ text += '。'
254
+
255
+ return text
256
+
257
+ def get_system_info(self):
258
+ """获取系统信息用于调试"""
259
+ try:
260
+ import psutil
261
+ memory = psutil.virtual_memory()
262
+ disk = psutil.disk_usage('/')
263
+
264
+ return {
265
+ 'memory_total': f"{memory.total / (1024**3):.1f}GB",
266
+ 'memory_available': f"{memory.available / (1024**3):.1f}GB",
267
+ 'memory_percent': f"{memory.percent}%",
268
+ 'disk_free': f"{disk.free / (1024**3):.1f}GB"
269
+ }
270
+ except:
271
+ return {"status": "无法获取系统信息"}
272
+
273
+ # 创建接口实例
274
+ tts_interface = GenieTTSInterface()
275
+
276
+ def create_interface():
277
+ """创建Gradio界面"""
278
+
279
+ def tts_wrapper(text, character, progress=gr.Progress()):
280
+ """TTS包装函数"""
281
+ if not text.strip():
282
+ return None, "❌ 请输入要合成的文本"
283
+
284
+ progress(0.1, desc="准备模型...")
285
+
286
+ # 加载字符模型
287
+ if character != tts_interface.current_character:
288
+ progress(0.3, desc=f"加载角色模型: {character}")
289
+ status, error = tts_interface.load_character(character)
290
+ if error:
291
+ return None, f"❌ {error}"
292
+
293
+ progress(0.5, desc="正在合成语音...")
294
+
295
+ audio_path, error = tts_interface.synthesize_speech(text, character)
296
+
297
+ progress(0.9, desc="完成处理...")
298
+
299
+ if error:
300
+ return None, f"❌ {error}"
301
+
302
+ progress(1.0, desc="✅ 合成成功!")
303
+ return audio_path, f"✅ 合成成功!音频长度: {get_audio_duration(audio_path):.1f}秒"
304
+
305
+ def get_audio_duration(audio_path):
306
+ """获取音频时长"""
307
+ try:
308
+ import librosa
309
+ y, sr = librosa.load(audio_path, sr=None)
310
+ return len(y) / sr
311
+ except:
312
+ return 0
313
+
314
+ def clear_all():
315
+ """清空所有输入和输出"""
316
+ return "", None, "🔄 已清空所有内容"
317
+
318
+ def load_example(text, character):
319
+ """加载示例"""
320
+ return text, character, f"📝 已加载示例: {text[:20]}..."
321
+
322
+ # 定义界面
323
+ with gr.Blocks(
324
+ title="🔮 Genie TTS - 语音合成",
325
+ theme=gr.themes.Soft(),
326
+ css="""
327
+ .gradio-container {
328
+ max-width: 1200px !important;
329
+ }
330
+ .status-success {
331
+ color: #28a745 !important;
332
+ }
333
+ .status-error {
334
+ color: #dc3545 !important;
335
+ }
336
+ """
337
+ ) as demo:
338
+ gr.Markdown("""
339
+ # 🔮 Genie TTS - AI 语音合成系统
340
+
341
+ 基于 [High-Logic/Genie](https://github.com/High-Logic/Genie) 的轻量级 TTS 推理引擎,支持高质量日语语音合成。
342
+
343
+ <div style="background: linear-gradient(90deg, #667eea 0%, #764ba2 100%); padding: 1rem; border-radius: 10px; color: white; margin: 1rem 0;">
344
+ <strong>🌟 功能特点</strong><br>
345
+ ✅ CPU 优化推理,无需 GPU<br>
346
+ ✅ 基于 GPT-SoVITS V2 技术<br>
347
+ ✅ 支持长文本自动分句<br>
348
+ ✅ 实时音频流输出
349
+ </div>
350
+
351
+ **📖 使用说明:** 选择角色模型 → 输入日语文本 → 点击合成按钮 → 获得高质量语音
352
+ """)
353
+
354
+ with gr.Tab("🎵 语音合成") as tts_tab:
355
+ with gr.Row():
356
+ with gr.Column(scale=1):
357
+ # 角色选择
358
+ with gr.Group():
359
+ gr.Markdown("### 👤 角色设置")
360
+ character_dropdown = gr.Dropdown(
361
+ choices=tts_interface.available_characters,
362
+ value="misono_mika",
363
+ label="🎭 选择角色",
364
+ info="当前可用的预训练角色模型",
365
+ interactive=True
366
+ )
367
+
368
+ # 文本输入
369
+ with gr.Group():
370
+ gr.Markdown("### 📝 文本输入")
371
+ text_input = gr.Textbox(
372
+ lines=5,
373
+ label="📄 输入文本",
374
+ placeholder="请输入要合成的日语文本...\n例如:どうしようかな……やっぱりやりたいかも……!",
375
+ info="💡 支持日语文本,建议输入完整的句子以获得更好的效果",
376
+ show_copy_button=True
377
+ )
378
+
379
+ # 控制按钮
380
+ with gr.Row():
381
+ submit_btn = gr.Button(
382
+ "🎵 开始合成",
383
+ variant="primary",
384
+ size="lg",
385
+ scale=2
386
+ )
387
+ clear_btn = gr.Button(
388
+ "🔄 清空",
389
+ variant="secondary",
390
+ scale=1
391
+ )
392
+
393
+ with gr.Column(scale=1):
394
+ # 音频输出
395
+ with gr.Group():
396
+ gr.Markdown("### 🔊 音频输出")
397
+ audio_output = gr.Audio(
398
+ label="🎶 生成的音频",
399
+ type="filepath",
400
+ interactive=False,
401
+ show_download_button=True
402
+ )
403
+
404
+ # 状态显示
405
+ status_output = gr.Textbox(
406
+ label="📊 合成状态",
407
+ interactive=False,
408
+ show_copy_button=False
409
+ )
410
+
411
+ # 示例和教程标签页
412
+ with gr.Tab("📚 示例与教程") as examples_tab:
413
+ gr.Markdown("### 🎯 快速示例")
414
+ gr.Markdown("点击下面的示例可以快速体验不同类型的文本合成效果:")
415
+
416
+ # 示例网格
417
+ with gr.Row():
418
+ with gr.Column():
419
+ gr.Markdown("**🌅 问候语**")
420
+ gr.Examples(
421
+ examples=[
422
+ ["おはようございます!", "misono_mika"],
423
+ ["こんにちは、元気ですか?", "misono_mika"],
424
+ ["お疲れさまでした", "misono_mika"]
425
+ ],
426
+ inputs=[text_input, character_dropdown],
427
+ outputs=[text_input, character_dropdown, status_output],
428
+ fn=load_example,
429
+ run_on_click=True
430
+ )
431
+
432
+ with gr.Column():
433
+ gr.Markdown("**💭 情感表达**")
434
+ gr.Examples(
435
+ examples=[
436
+ ["どうしようかな……やっぱりやりたいかも……!", "misono_mika"],
437
+ ["うーん、これは難しいですね", "misono_mika"],
438
+ ["わあ、すごいですね!", "misono_mika"]
439
+ ],
440
+ inputs=[text_input, character_dropdown],
441
+ outputs=[text_input, character_dropdown, status_output],
442
+ fn=load_example,
443
+ run_on_click=True
444
+ )
445
+
446
+ with gr.Column():
447
+ gr.Markdown("**🎭 日常对话**")
448
+ gr.Examples(
449
+ examples=[
450
+ ["ありがとうございます", "misono_mika"],
451
+ ["さようなら、また明日", "misono_mika"],
452
+ ["お先に失礼します", "misono_mika"]
453
+ ],
454
+ inputs=[text_input, character_dropdown],
455
+ outputs=[text_input, character_dropdown, status_output],
456
+ fn=load_example,
457
+ run_on_click=True
458
+ )
459
+
460
+ gr.Markdown("""
461
+ ### 📋 使用技巧
462
+
463
+ 1. **文本长度**: 建议单次输入文本长度在 100 字以内,过长的文本会自动分句处理
464
+ 2. **标点符号**: 适当使用标点符号(。!?)可以改善语音的自然度
465
+ 3. **特殊符号**: 支持省略号(……)和感叹号(!)等情感表达
466
+ 4. **处理时间**: 首次加载角色需要下载模型(约30秒),后续合成较快(5-10秒)
467
+
468
+ ### 🔧 技术说明
469
+
470
+ - **模型架构**: 基于 Transformer 的端到端语音合成
471
+ - **采样率**: 32kHz,支持高质量音频输出
472
+ - **推理方式**: CPU 优化的 ONNX 模型,适合云端部署
473
+ - **内存占用**: 约 500MB RAM,支持并发处理
474
+ """)
475
+
476
+ # 关于标签页
477
+ with gr.Tab("ℹ️ 关于项目") as about_tab:
478
+ gr.Markdown("""
479
+ ### 🔍 项目信息
480
+
481
+ **Genie TTS** 是基于 GPT-SoVITS V2 架构的轻量级语音合成引擎,专门为 CPU 推理优化。
482
+
483
+ #### 📊 技术规格
484
+
485
+ | 项目 | 规格 |
486
+ |------|------|
487
+ | **基础模型** | GPT-SoVITS V2 |
488
+ | **推理框架** | ONNX Runtime |
489
+ | **支持语言** | 日语 (Japanese) |
490
+ | **音频格式** | WAV, 32kHz |
491
+ | **推理设备** | CPU (无需 GPU) |
492
+ | **模型大小** | ~200MB |
493
+ | **内存需求** | ~500MB RAM |
494
+
495
+ #### � 相关链接
496
+
497
+ - 🏠 [项目主页](https://github.com/High-Logic/Genie)
498
+ - 🤗 [Hugging Face 模型](https://huggingface.co/High-Logic/Genie)
499
+ - 📖 [GPT-SoVITS 官方](https://github.com/RVC-Boss/GPT-SoVITS)
500
+ - 💬 [问题反馈](https://github.com/High-Logic/Genie/issues)
501
+
502
+ #### 🙏 致谢
503
+
504
+ 感谢以下项目和开发者:
505
+ - [High-Logic](https://github.com/High-Logic) 团队开发的 Genie TTS
506
+ - [RVC-Boss](https://github.com/RVC-Boss) 团队的 GPT-SoVITS 项目
507
+ - Hugging Face 提供的模型托管和 Spaces 平台
508
+
509
+ #### ⚖️ 免责声明
510
+
511
+ 本应用仅用于演示和研究目的。请合理使用,生成的语音内容责任由使用者承担。
512
+ """)
513
+
514
+ # 绑定事件
515
+ submit_btn.click(
516
+ fn=tts_wrapper,
517
+ inputs=[text_input, character_dropdown],
518
+ outputs=[audio_output, status_output],
519
+ show_progress="full",
520
+ queue=True
521
+ )
522
+
523
+ clear_btn.click(
524
+ fn=clear_all,
525
+ outputs=[text_input, audio_output, status_output]
526
+ )
527
+
528
+ return demo
529
+
530
+ # 启动应用
531
+ if __name__ == "__main__":
532
+ demo = create_interface()
533
+ demo.launch(
534
+ server_name="0.0.0.0",
535
+ server_port=7860,
536
+ show_api=False,
537
+ show_error=True,
538
+ quiet=False
539
+ )
guidance.md ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Spaces
2
+ Hugging Face's logo
3
+
4
+ Tom1986
5
+ /
6
+ GENIE
7
+
8
+
9
+ like
10
+ 0
11
+
12
+ Logs
13
+ App
14
+ Files
15
+ Community
16
+ Settings
17
+
18
+
19
+ 🚀 Get started with your gradio Space!
20
+ Your new space has been created, follow these steps to get started (or read the full documentation)
21
+
22
+ Start by cloning this repo by using:
23
+
24
+ Use an access token as git password/credential
25
+
26
+
27
+ # When prompted for a password, use an access token with write permissions.
28
+ # Generate one from your settings: https://huggingface.co/settings/tokens
29
+ git clone https://huggingface.co/spaces/Tom1986/GENIE
30
+
31
+ # Make sure hf CLI is installed: pip install -U "huggingface_hub[cli]"
32
+ hf download Tom1986/GENIE --repo-type=space
33
+ Create your gradio app.py file:
34
+
35
+
36
+ import gradio as gr
37
+
38
+ def greet(name):
39
+ return "Hello " + name + "!!"
40
+
41
+ demo = gr.Interface(fn=greet, inputs="text", outputs="text")
42
+ demo.launch()
43
+ Then commit and push:
44
+
45
+
46
+ git add app.py
47
+ git commit -m "Add application file"
48
+ git push
49
+ Hint Alternatively, you can create the app.py file directly in your browser.
50
+ Finally, your Space should be running on this page after a few moments!
51
+
52
+ Dependencies
53
+
54
+ You can add a requirements.txt file at the root of the repository to specify Python dependencies
55
+
56
+ If needed, you can also add a packages.txt file at the root of the repository to specify Debian dependencies.
57
+
58
+ The gradio package is pre-installed and its version is set in the sdk_version field in the README.md file.
59
+
60
+ Personalize your Space
61
+
62
+ Make your Space stand out by customizing its emoji, colors, and description by editing metadata in its README.md file.
63
+
64
+ Documentation
65
+
66
+ Read the full documentation for gradio Spaces here.
67
+
requirements.txt ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Hugging Face Spaces requirements for Genie TTS
2
+
3
+ # Core dependencies
4
+ gradio>=4.0.0
5
+ torch>=2.0.0
6
+ torchaudio>=2.0.0
7
+
8
+ # Genie TTS package
9
+ genie-tts
10
+
11
+ # Audio processing
12
+ librosa>=0.10.0
13
+ soundfile>=0.12.0
14
+ scipy>=1.9.0
15
+
16
+ # ONNX Runtime for model inference
17
+ onnxruntime>=1.16.0
18
+
19
+ # Additional dependencies
20
+ numpy>=1.21.0
21
+ pandas>=1.5.0
22
+ Pillow>=9.0.0
23
+
24
+ # Hugging Face integrations
25
+ huggingface-hub>=0.17.0
26
+ transformers>=4.25.0
27
+
28
+ # Japanese text processing (for pyopenjtalk if needed)
29
+ # Note: pyopenjtalk might need system dependencies on some platforms
30
+ # pyopenjtalk # Uncomment if needed
31
+
32
+ # System utilities
33
+ psutil>=5.8.0
34
+ requests>=2.25.0
35
+
36
+ # Logging and monitoring
37
+ rich>=12.0.0
38
+
39
+ # File handling
40
+ pathlib2>=2.3.0