jerrybwang commited on
Commit
cdf446f
·
1 Parent(s): 92b99c9

--other 更新代码

Browse files
Files changed (5) hide show
  1. README.md +85 -29
  2. app.py +82 -340
  3. check_deployment.py +134 -0
  4. packages.txt +2 -0
  5. requirements.txt +3 -3
README.md CHANGED
@@ -75,56 +75,112 @@ model = AutoModel.from_pretrained("FunAudioLLM/CosyVoice-300M")
75
 
76
  ## 部署到Hugging Face Space
77
 
78
- ### 快速部署
79
 
80
  1. **创建Space**
81
  - 访问 [Hugging Face Spaces](https://huggingface.co/spaces)
82
  - 点击 "New Space"
83
  - 选择 Gradio SDK
 
84
 
85
- 2. **上传文件**
86
- - 上传 `app.py`
87
- - 上传 `requirements.txt`
88
- - 上传 `config.py`(可选)
89
- - 上传 `README.md`(可选)
90
 
91
  3. **等待构建**
92
- - Space会自动安装依赖(约3-5分钟)
93
- - 自动下载CosyVoice模型
94
  - 启动应用
95
 
96
  4. **验证部署**
97
  - 检查模型状态指示器(应显示绿色✅)
98
- - 测试语音识别和文本转语音功能
 
99
 
100
- ### 硬件建议
101
 
102
- - **CPU Basic(免费)**: 适合测试和演示
103
- - **GPU T4(推荐)**: 更快的推理速度,更好的用户体验
104
- - **GPU A10G**: 适合高并发场景
 
 
105
 
106
- ### 部署问题修复
107
 
108
- 如果遇到以下错误:
109
- ```
110
- ERROR: cosyvoice does not appear to be a Python project
 
 
 
 
 
 
 
 
 
 
 
111
  ```
112
 
113
- **解决方案**: 已修复!当前版本的`requirements.txt`已移除有问题的依赖,改用transformers直接加载模型。
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
 
115
- 详细的故障排除指南请查看 [HF_SPACE_FIX.md](HF_SPACE_FIX.md)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
 
117
- ### 自动部署
118
- 1. 将本仓库推送到Hugging Face
119
- 2. 在Hugging Face网站创建新的Space
120
- 3. 选择"Gradio"作为SDK
121
- 4. 系统会自动检测配置并部署
122
 
123
- ### 手动部署
124
- 如果需要自定义部署,可以修改以下文件:
125
- - `app.py`: 主应用文件
126
- - `requirements.txt`: Python依赖包
127
- - `README.md`: 空间配置和说明
 
 
128
 
129
  ## 技术架构
130
 
 
75
 
76
  ## 部署到Hugging Face Space
77
 
78
+ ### 快速部署步骤
79
 
80
  1. **创建Space**
81
  - 访问 [Hugging Face Spaces](https://huggingface.co/spaces)
82
  - 点击 "New Space"
83
  - 选择 Gradio SDK
84
+ - 选择硬件(推荐 CPU Basic 或 GPU T4)
85
 
86
+ 2. **上传必需文件**
87
+ - `app.py` - 主应用文件
88
+ - `requirements.txt` - Python依赖
89
+ - `packages.txt` - 系统依赖(ffmpeg等)
90
+ - `README.md` - 项目说明(包含Space配置)
91
 
92
  3. **等待构建**
93
+ - Space会自动安装依赖(约5-10分钟)
94
+ - 自动从Hugging Face Hub下载CosyVoice-300M模型
95
  - 启动应用
96
 
97
  4. **验证部署**
98
  - 检查模型状态指示器(应显示绿色✅)
99
+ - 测试文本转语音功能
100
+ - 测试音频处理功能
101
 
102
+ ### 硬件配置建议
103
 
104
+ | 硬件类型 | 适用场景 | 说明 |
105
+ |---------|---------|------|
106
+ | **CPU Basic(免费)** | 测试和演示 | 推理速度较慢,适合轻量使用 |
107
+ | **GPU T4(推荐)** | 生产环境 | 更快的推理速度,更好的用户体验 |
108
+ | **GPU A10G** | 高并发 | 适合大量用户同时访问 |
109
 
110
+ ### 重要配置说明
111
 
112
+ #### README.md 头部配置
113
+ 确保 README.md 文件顶部包含以下配置:
114
+ ```yaml
115
+ ---
116
+ title: CosyVoice
117
+ emoji: 🌍
118
+ colorFrom: blue
119
+ colorTo: pink
120
+ sdk: gradio
121
+ sdk_version: 6.4.0
122
+ app_file: app.py
123
+ pinned: false
124
+ license: apache-2.0
125
+ ---
126
  ```
127
 
128
+ #### 必需的文件
129
+ - ✅ `app.py` - 主应用
130
+ - ✅ `requirements.txt` - Python依赖
131
+ - ✅ `packages.txt` - 系统依赖(ffmpeg, libsndfile1)
132
+ - ✅ `README.md` - 包含Space配置
133
+
134
+ ### 常见问题解决
135
+
136
+ #### 问题1: 模型加载失败
137
+ **症状**: 界面显示"演示模式"警告
138
+ **解决方案**:
139
+ - 检查网络连接是否正常
140
+ - 确认 `requirements.txt` 中包含 `transformers>=4.35.0`
141
+ - 查看 Space 日志确认模型下载进度
142
+
143
+ #### 问题2: 音频处理错误
144
+ **症状**: 上传音频后报错
145
+ **解决方案**:
146
+ - 确保 `packages.txt` 文件存在并包含 `ffmpeg`
147
+ - 重新构建 Space
148
 
149
+ #### 问题3: 依赖安装失败
150
+ **症状**: 构建过程中出现错误
151
+ **解决方案**:
152
+ - 检查 `requirements.txt` 格式是否正确
153
+ - 移除不必要的依赖(如 modelscope, edge-tts, gTTS)
154
+ - 使用固定版本号避免兼容性问题
155
+
156
+ ### Git 部署方式
157
+
158
+ ```bash
159
+ # 克隆或创建仓库
160
+ git clone https://huggingface.co/spaces/YOUR_USERNAME/YOUR_SPACE_NAME
161
+ cd YOUR_SPACE_NAME
162
+
163
+ # 添加文件
164
+ cp /path/to/app.py .
165
+ cp /path/to/requirements.txt .
166
+ cp /path/to/packages.txt .
167
+ cp /path/to/README.md .
168
+
169
+ # 提交并推送
170
+ git add .
171
+ git commit -m "Initial deployment"
172
+ git push
173
+ ```
174
 
175
+ ### 验证清单
 
 
 
 
176
 
177
+ 部署前请确认:
178
+ - [ ] README.md 包含正确的 YAML 配置
179
+ - [ ] app.py 文件完整无误
180
+ - [ ] requirements.txt 包含所有必需依赖
181
+ - [ ] packages.txt 包含系统依赖
182
+ - [ ] 选择了合适的硬件配置
183
+ - [ ] Space 设置为 Public(如需公开访问)
184
 
185
  ## 技术架构
186
 
app.py CHANGED
@@ -33,228 +33,71 @@ def load_cosyvoice_model():
33
  print("="*60)
34
 
35
  try:
36
- # 方法1: 使用transformers加载(推荐用于Hugging Face Space)
37
- try:
38
- print("\n[方法1] 尝试使用transformers加载...")
39
- from transformers import AutoModel
40
- import torch
41
-
42
- model_name = "FunAudioLLM/CosyVoice-300M"
43
- print(f" 从 {model_name} 加载...")
44
-
45
- # CosyVoice需要trust_remote_code=True来加载自定义模型代码
46
- model = AutoModel.from_pretrained(
47
- model_name,
48
- trust_remote_code=True,
49
- torch_dtype=torch.float32
50
- )
51
-
52
- # 设置为评估模式
53
- model.eval()
54
-
55
- # 详细检查模型类型和方法
56
- print(f" 模型类型: {type(model)}")
57
- print(f" 模型类名: {model.__class__.__name__}")
58
-
59
- # 检查所有可用的方法
60
- all_methods = [m for m in dir(model) if not m.startswith('_') and callable(getattr(model, m, None))]
61
- print(f" 可用方法数量: {len(all_methods)}")
62
- print(f" 前20个方法: {all_methods[:20]}")
63
-
64
- # 检查关键推理方法
65
- has_inference_sft = hasattr(model, 'inference_sft')
66
- has_inference = hasattr(model, 'inference')
67
- has_generate = hasattr(model, 'generate')
68
- has_forward = hasattr(model, 'forward')
69
-
70
- print(f" 推理方法检查:")
71
- print(f" - inference_sft: {has_inference_sft}")
72
- print(f" - inference: {has_inference}")
73
- print(f" - generate: {has_generate}")
74
- print(f" - forward: {has_forward}")
75
-
76
- # 如果模型有这些方法,说明加载成功
77
- has_inference = has_inference_sft or has_inference or has_generate
78
-
79
- if has_inference:
80
- cosyvoice_model = {
81
- 'model': model,
82
- 'type': 'transformers',
83
- 'has_inference': True
84
- }
85
- model_loaded = True
86
- print(" ✓ 成功通过transformers加载CosyVoice模型(有推理方法)")
87
- print("="*60 + "\n")
88
- return cosyvoice_model
89
- else:
90
- print(" ⚠ 模型加载成功但缺少推理方法,尝试下一个方法...")
91
- # 不返回,继续尝试其他方法
92
-
93
- except Exception as e:
94
- print(f" ✗ transformers加载失败: {e}")
95
- import traceback
96
- print(f" 详细错误: {traceback.format_exc()[:300]}")
97
 
98
- # 方法2: 尝试从Hugging Face Hub下载并使用官方CosyVoice
99
- try:
100
- print("\n[方法2] 尝试从Hugging Face Hub下载并使用官方CosyVoice...")
101
- from huggingface_hub import snapshot_download
102
- import torch
103
-
104
- model_id = "FunAudioLLM/CosyVoice-300M"
105
- print(f" 下载模型: {model_id}")
106
-
107
- model_dir = snapshot_download(
108
- repo_id=model_id,
109
- allow_patterns=["*.pt", "*.pth", "*.bin", "*.safetensors", "*.json", "*.txt", "*.yaml", "*.py"],
110
- )
111
- print(f" 模型下载到: {model_dir}")
112
-
113
- # 尝试导入CosyVoice官方包
114
- try:
115
- # 首先尝试直接导入(如果已安装)
116
- from cosyvoice.cli.cosyvoice import CosyVoice
117
- print(" 使用已安装的CosyVoice包")
118
- cosyvoice_model = CosyVoice(model_dir)
119
- model_loaded = True
120
- print(" ✓ 成功使用官方CosyVoice包加载模型")
121
- print("="*60 + "\n")
122
- return cosyvoice_model
123
- except ImportError:
124
- print(" CosyVoice包未安装,尝试从下载的代码加载...")
125
-
126
- # 尝试从下载的模型目录加载代码
127
- if model_dir not in sys.path:
128
- sys.path.insert(0, model_dir)
129
-
130
- # 查找并加载modeling文件
131
- import glob
132
- py_files = glob.glob(os.path.join(model_dir, "**/*.py"), recursive=True)
133
- print(f" 找到Python文件: {len(py_files)}个")
134
-
135
- # 尝试找到CosyVoice类定义
136
- for py_file in py_files:
137
- if 'cosyvoice' in py_file.lower() or 'model' in py_file.lower():
138
- print(f" 检查文件: {os.path.basename(py_file)}")
139
-
140
- # 如果找不到官方包,尝试直接加载模型权重
141
- try:
142
- # 查找模型文件
143
- model_files = glob.glob(os.path.join(model_dir, "**/*.pt"), recursive=True)
144
- model_files += glob.glob(os.path.join(model_dir, "**/*.pth"), recursive=True)
145
- model_files += glob.glob(os.path.join(model_dir, "**/*.bin"), recursive=True)
146
-
147
- if model_files:
148
- print(f" 找到模型文件: {len(model_files)}个")
149
- for mf in model_files[:5]:
150
- print(f" - {os.path.basename(mf)}")
151
-
152
- # 尝试使用transformers的AutoModel加载
153
- print(" 尝试使用AutoModel从本地目录加载...")
154
- from transformers import AutoModel
155
- model = AutoModel.from_pretrained(
156
- model_dir,
157
- trust_remote_code=True,
158
- local_files_only=True,
159
- torch_dtype=torch.float32
160
- )
161
- model.eval()
162
-
163
- # 检查推理方法
164
- print(f" 模型类型: {type(model).__name__}")
165
- has_inference = hasattr(model, 'inference_sft') or hasattr(model, 'inference') or hasattr(model, 'generate')
166
- print(f" 有推理方法: {has_inference}")
167
-
168
- if has_inference:
169
- cosyvoice_model = {
170
- 'model': model,
171
- 'model_dir': model_dir,
172
- 'type': 'transformers'
173
- }
174
- model_loaded = True
175
- print(" ✓ 成功从本地目录加载模型")
176
- print("="*60 + "\n")
177
- return cosyvoice_model
178
- else:
179
- print(" ⚠ 模型加载成功但缺少推理方法")
180
- else:
181
- print(" ✗ 未找到模型文件")
182
-
183
- except Exception as load_err:
184
- print(f" ✗ 加载模型文件失败: {load_err}")
185
- import traceback
186
- print(f" 详细错误: {traceback.format_exc()[:300]}")
187
-
188
- except Exception as e:
189
- print(f" ✗ Hugging Face Hub下载失败: {e}")
190
- import traceback
191
- print(f" 详细错误: {traceback.format_exc()[:300]}")
192
 
193
- # 方法3: 尝试从本地路径加载(用于本地开发)
194
- try:
195
- print("\n[方法3] 尝试从本地路径加载...")
196
- from cosyvoice.cli.cosyvoice import CosyVoice
197
-
198
- possible_paths = [
199
- os.environ.get('COSYVOICE_MODEL_DIR', ''),
200
- 'pretrained_models/CosyVoice-300M',
201
- 'CosyVoice-300M',
202
- './models/CosyVoice-300M',
203
- ]
204
-
205
- for model_dir in possible_paths:
206
- if model_dir and os.path.exists(model_dir):
207
- print(f" 尝试从路径加载: {model_dir}")
208
- try:
209
- cosyvoice_model = CosyVoice(model_dir)
210
- model_loaded = True
211
- print(f" ✓ 成功从 {model_dir} 加载CosyVoice模型")
212
- print("="*60 + "\n")
213
- return cosyvoice_model
214
- except Exception as e:
215
- print(f" ✗ 加载失败: {e}")
216
- continue
217
-
218
- except ImportError as e:
219
- print(f" ✗ CosyVoice包未安装: {e}")
220
- except Exception as e:
221
- print(f" ✗ 方法3失败: {e}")
222
 
223
- # 方法4: 使用ModelScope加载(国内用户备选)
224
- try:
225
- print("\n[方法4] 尝试使用ModelScope加载...")
226
- from modelscope import snapshot_download
227
-
228
- model_dir = snapshot_download('iic/CosyVoice-300M')
229
- print(f" 模型下载到: {model_dir}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
230
 
231
- # 尝试使用下载的模型
232
- try:
233
- sys.path.insert(0, model_dir)
234
- from cosyvoice.cli.cosyvoice import CosyVoice
235
- cosyvoice_model = CosyVoice(model_dir)
236
- model_loaded = True
237
- print(" ✓ 成功通过ModelScope加载CosyVoice模型")
238
- print("="*60 + "\n")
239
- return cosyvoice_model
240
- except ImportError:
241
- cosyvoice_model = {'model_dir': model_dir, 'type': 'downloaded'}
242
- model_loaded = True
243
- print(" ✓ 模型文件已下载(演示模式)")
244
- print("="*60 + "\n")
245
- return cosyvoice_model
246
- except Exception as e:
247
- print(f" ✗ ModelScope加载失败: {e}")
248
 
249
- # 方法5: 演示模式(所有方法都失败)
250
- print("\n[方法5] 所有加载方法失败,使用演示模式")
251
- print(" 演示模式不包含真实的CosyVoice模型")
252
- print(" 要使用完整功能,请确保:")
253
- print(" 1. 网络连接正常,可以访问Hugging Face")
254
- print(" 2. 有足够的磁盘空间(约2GB)")
255
- print(" 3. transformers包版本 >= 4.35.0")
256
- print("\n安装方法:")
257
- print(" pip install transformers>=4.35.0")
258
  print("="*60 + "\n")
259
 
260
  cosyvoice_model = None
@@ -497,129 +340,28 @@ def text_to_speech(text, speaker="中文女"):
497
  return None, f"语音合成失败: {str(e)}"
498
 
499
  def generate_demo_audio(text, speaker, error=None):
500
- """使用备用TTS引擎生成真实语音"""
501
- try:
502
- # 尝试使用edge-tts(微软Edge浏览器的TTS引擎)
503
- import edge_tts
504
- import asyncio
505
- import tempfile
506
-
507
- print(f"使用edge-tts生成语音: {text[:50]}...")
508
-
509
- # 根据说话人选择语音
510
- voice_map = {
511
- "中文女": "zh-CN-XiaoxiaoNeural",
512
- "中文男": "zh-CN-YunxiNeural",
513
- "英文女": "en-US-JennyNeural",
514
- "英文男": "en-US-GuyNeural",
515
- }
516
- voice = voice_map.get(speaker, "zh-CN-XiaoxiaoNeural")
517
-
518
- # 创建临时文件
519
- with tempfile.NamedTemporaryFile(delete=False, suffix='.mp3') as tmp_file:
520
- tmp_path = tmp_file.name
521
-
522
- # 异步生成语音
523
- async def generate():
524
- communicate = edge_tts.Communicate(text, voice)
525
- await communicate.save(tmp_path)
526
-
527
- # 运行异步任务
528
- asyncio.run(generate())
529
-
530
- # 读取生成的音频
531
- import soundfile as sf
532
- from pydub import AudioSegment
533
-
534
- # 转换MP3到WAV
535
- audio = AudioSegment.from_mp3(tmp_path)
536
- wav_path = tmp_path.replace('.mp3', '.wav')
537
- audio.export(wav_path, format='wav')
538
-
539
- # 读取WAV文件
540
- audio_data, sample_rate = sf.read(wav_path)
541
-
542
- # 清理临时文件
543
- os.unlink(tmp_path)
544
- os.unlink(wav_path)
545
-
546
- audio_tuple = (sample_rate, audio_data.astype(np.float32))
547
-
548
- status_msg = f"✓ 语音合成成功(使用Edge TTS)\n文本: {text}\n说话人: {speaker}\n"
549
- if error:
550
- status_msg += f"注意: CosyVoice模型不可用,已使用备用引擎\n"
551
-
552
- print(f" ✓ Edge TTS生成成功")
553
- return audio_tuple, status_msg
554
-
555
- except Exception as e:
556
- print(f" ✗ Edge TTS失败: {e}")
557
-
558
- # 如果edge-tts失败,尝试gTTS
559
- try:
560
- from gtts import gTTS
561
- import tempfile
562
- import soundfile as sf
563
- from pydub import AudioSegment
564
-
565
- print(f"使用gTTS生成语音: {text[:50]}...")
566
-
567
- # 根据说话人选择语言
568
- lang = 'zh-CN' if speaker.startswith('中文') else 'en'
569
-
570
- # 创建临时文件
571
- with tempfile.NamedTemporaryFile(delete=False, suffix='.mp3') as tmp_file:
572
- tmp_path = tmp_file.name
573
-
574
- # 生成语音
575
- tts = gTTS(text=text, lang=lang, slow=False)
576
- tts.save(tmp_path)
577
-
578
- # 转换MP3到WAV
579
- audio = AudioSegment.from_mp3(tmp_path)
580
- wav_path = tmp_path.replace('.mp3', '.wav')
581
- audio.export(wav_path, format='wav')
582
-
583
- # 读取WAV文件
584
- audio_data, sample_rate = sf.read(wav_path)
585
-
586
- # 清理临时文件
587
- os.unlink(tmp_path)
588
- os.unlink(wav_path)
589
-
590
- audio_tuple = (sample_rate, audio_data.astype(np.float32))
591
-
592
- status_msg = f"✓ 语音合成成功(使用Google TTS)\n文本: {text}\n说话人: {speaker}\n"
593
- if error:
594
- status_msg += f"注意: CosyVoice模型不可用,已使用备用引擎\n"
595
-
596
- print(f" ✓ gTTS生成成功")
597
- return audio_tuple, status_msg
598
-
599
- except Exception as e2:
600
- print(f" ✗ gTTS也失败: {e2}")
601
-
602
- # 最后的降级方案:生成演示音频
603
- sample_rate = 22050
604
- duration = min(len(text) * 0.2, 5.0)
605
- t = np.linspace(0, duration, int(sample_rate * duration), False)
606
-
607
- frequency = 440
608
- audio_data = 0.3 * np.sin(2 * np.pi * frequency * t)
609
- audio_data += 0.2 * np.sin(2 * np.pi * frequency * 1.5 * t)
610
-
611
- fade_samples = int(sample_rate * 0.1)
612
- audio_data[:fade_samples] *= np.linspace(0, 1, fade_samples)
613
- audio_data[-fade_samples:] *= np.linspace(1, 0, fade_samples)
614
-
615
- audio_tuple = (sample_rate, audio_data.astype(np.float32))
616
-
617
- status_msg = f"⚠ 演示模式\n文本: {text}\n说话人: {speaker}\n"
618
- if error:
619
- status_msg += f"注意: 所有TTS引擎都不可用\n"
620
- status_msg += "提示: 这是演示音频,不是真实的语音合成结果"
621
-
622
- return audio_tuple, status_msg
623
 
624
  # 在启动时加载模型
625
  load_cosyvoice_model()
 
33
  print("="*60)
34
 
35
  try:
36
+ # 使用transformers加载(推荐用于Hugging Face Space)
37
+ print("\n尝试使用transformers加载...")
38
+ from transformers import AutoModel
39
+ import torch
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
+ model_name = "FunAudioLLM/CosyVoice-300M"
42
+ print(f"从 {model_name} 加载...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
+ # CosyVoice需要trust_remote_code=True来加载自定义模型代码
45
+ model = AutoModel.from_pretrained(
46
+ model_name,
47
+ trust_remote_code=True,
48
+ torch_dtype=torch.float32,
49
+ low_cpu_mem_usage=True
50
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
 
52
+ # 设置为评估模式
53
+ model.eval()
54
+
55
+ # 检查模型类型和方法
56
+ print(f"模型类型: {type(model).__name__}")
57
+
58
+ # 检查关键推理方法
59
+ has_inference_sft = hasattr(model, 'inference_sft')
60
+ has_inference = hasattr(model, 'inference')
61
+ has_generate = hasattr(model, 'generate')
62
+
63
+ print(f"推理方法检查:")
64
+ print(f" - inference_sft: {has_inference_sft}")
65
+ print(f" - inference: {has_inference}")
66
+ print(f" - generate: {has_generate}")
67
+
68
+ # 如果模型有这些方法,说明加载成功
69
+ if has_inference_sft or has_inference or has_generate:
70
+ cosyvoice_model = {
71
+ 'model': model,
72
+ 'type': 'transformers',
73
+ 'has_inference': True
74
+ }
75
+ model_loaded = True
76
+ print("✓ 成功加载CosyVoice模型")
77
+ print("="*60 + "\n")
78
+ return cosyvoice_model
79
+ else:
80
+ print("⚠ 模型加载成功但缺少推理方法")
81
+ cosyvoice_model = {
82
+ 'model': model,
83
+ 'type': 'transformers',
84
+ 'has_inference': False
85
+ }
86
+ model_loaded = True
87
+ print("="*60 + "\n")
88
+ return cosyvoice_model
89
 
90
+ except Exception as e:
91
+ print(f"✗ 模型加载失败: {e}")
92
+ import traceback
93
+ print(f"详细错误:\n{traceback.format_exc()}")
 
 
 
 
 
 
 
 
 
 
 
 
 
94
 
95
+ # 演示模式(加载失败)
96
+ print("\n 使用演示模式")
97
+ print("提示: 要使用完整功能,请确保:")
98
+ print(" 1. 网络连接正常,可以访问Hugging Face")
99
+ print(" 2. 有足够的磁盘空间(约2GB)")
100
+ print(" 3. transformers包版本 >= 4.35.0")
 
 
 
101
  print("="*60 + "\n")
102
 
103
  cosyvoice_model = None
 
340
  return None, f"语音合成失败: {str(e)}"
341
 
342
  def generate_demo_audio(text, speaker, error=None):
343
+ """生成演示音频(当模型不可用时)"""
344
+ # 生成简单的演示音频
345
+ sample_rate = 22050
346
+ duration = min(len(text) * 0.2, 5.0)
347
+ t = np.linspace(0, duration, int(sample_rate * duration), False)
348
+
349
+ frequency = 440
350
+ audio_data = 0.3 * np.sin(2 * np.pi * frequency * t)
351
+ audio_data += 0.2 * np.sin(2 * np.pi * frequency * 1.5 * t)
352
+
353
+ fade_samples = int(sample_rate * 0.1)
354
+ audio_data[:fade_samples] *= np.linspace(0, 1, fade_samples)
355
+ audio_data[-fade_samples:] *= np.linspace(1, 0, fade_samples)
356
+
357
+ audio_tuple = (sample_rate, audio_data.astype(np.float32))
358
+
359
+ status_msg = f"⚠ 演示模式\n文本: {text}\n说话人: {speaker}\n"
360
+ if error:
361
+ status_msg += f"错误: {error}\n"
362
+ status_msg += "提示: 这是演示音频,不是真实的语音合成结果。请确保模型正确加载。"
363
+
364
+ return audio_tuple, status_msg
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
365
 
366
  # 在启动时加载模型
367
  load_cosyvoice_model()
check_deployment.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Hugging Face Space 部署检查脚本
4
+ 检查所有必需的文件和配置是否正确
5
+ """
6
+
7
+ import os
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ def check_file_exists(filepath, required=True):
12
+ """检查文件是否存在"""
13
+ exists = os.path.exists(filepath)
14
+ status = "✅" if exists else ("❌" if required else "⚠️")
15
+ req_text = "必需" if required else "可选"
16
+ print(f"{status} {filepath} ({req_text}): {'存在' if exists else '缺失'}")
17
+ return exists
18
+
19
+ def check_file_content(filepath, required_content):
20
+ """检查文件内容"""
21
+ try:
22
+ with open(filepath, 'r', encoding='utf-8') as f:
23
+ content = f.read()
24
+ for item in required_content:
25
+ if item in content:
26
+ print(f" ✅ 包含: {item}")
27
+ else:
28
+ print(f" ❌ 缺失: {item}")
29
+ return False
30
+ return True
31
+ except Exception as e:
32
+ print(f" ❌ 读取文件失败: {e}")
33
+ return False
34
+
35
+ def main():
36
+ print("="*60)
37
+ print("Hugging Face Space 部署检查")
38
+ print("="*60)
39
+ print()
40
+
41
+ # 检查必需文件
42
+ print("📋 检查必需文件:")
43
+ print("-"*60)
44
+
45
+ files_ok = True
46
+ files_ok &= check_file_exists("app.py", required=True)
47
+ files_ok &= check_file_exists("requirements.txt", required=True)
48
+ files_ok &= check_file_exists("packages.txt", required=True)
49
+ files_ok &= check_file_exists("README.md", required=True)
50
+
51
+ print()
52
+
53
+ # 检查可选文件
54
+ print("📋 检查可选文件:")
55
+ print("-"*60)
56
+ check_file_exists("config.py", required=False)
57
+ check_file_exists(".gitignore", required=False)
58
+
59
+ print()
60
+
61
+ # 检查 README.md 配置
62
+ print("📋 检查 README.md 配置:")
63
+ print("-"*60)
64
+ if os.path.exists("README.md"):
65
+ readme_items = [
66
+ "title:",
67
+ "sdk: gradio",
68
+ "app_file: app.py",
69
+ ]
70
+ check_file_content("README.md", readme_items)
71
+
72
+ print()
73
+
74
+ # 检查 requirements.txt
75
+ print("📋 检查 requirements.txt:")
76
+ print("-"*60)
77
+ if os.path.exists("requirements.txt"):
78
+ req_items = [
79
+ "gradio",
80
+ "torch",
81
+ "transformers",
82
+ "huggingface_hub",
83
+ ]
84
+ check_file_content("requirements.txt", req_items)
85
+
86
+ print()
87
+
88
+ # 检查 packages.txt
89
+ print("📋 检查 packages.txt:")
90
+ print("-"*60)
91
+ if os.path.exists("packages.txt"):
92
+ pkg_items = [
93
+ "ffmpeg",
94
+ ]
95
+ check_file_content("packages.txt", pkg_items)
96
+
97
+ print()
98
+
99
+ # 检查 app.py
100
+ print("📋 检查 app.py:")
101
+ print("-"*60)
102
+ if os.path.exists("app.py"):
103
+ app_items = [
104
+ "import gradio",
105
+ "AutoModel.from_pretrained",
106
+ "FunAudioLLM/CosyVoice-300M",
107
+ "demo.launch()",
108
+ ]
109
+ check_file_content("app.py", app_items)
110
+
111
+ print()
112
+ print("="*60)
113
+
114
+ if files_ok:
115
+ print("✅ 所有必需文件检查通过!")
116
+ print()
117
+ print("📦 下一步:")
118
+ print("1. 访问 https://huggingface.co/spaces")
119
+ print("2. 创建新的 Space,选择 Gradio SDK")
120
+ print("3. 上传以下文件:")
121
+ print(" - app.py")
122
+ print(" - requirements.txt")
123
+ print(" - packages.txt")
124
+ print(" - README.md")
125
+ print("4. 等待构建完成(约5-10分钟)")
126
+ print("5. 测试应用功能")
127
+ else:
128
+ print("❌ 检查失败!请修复上述问题后重试。")
129
+ sys.exit(1)
130
+
131
+ print("="*60)
132
+
133
+ if __name__ == "__main__":
134
+ main()
packages.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ ffmpeg
2
+ libsndfile1
requirements.txt CHANGED
@@ -7,7 +7,7 @@ librosa>=0.10.0
7
  soundfile>=0.12.0
8
  scipy>=1.10.0
9
  huggingface_hub>=0.19.0
10
- modelscope
11
  pydub
12
- gTTS
13
- edge-tts
 
 
7
  soundfile>=0.12.0
8
  scipy>=1.10.0
9
  huggingface_hub>=0.19.0
 
10
  pydub
11
+ accelerate
12
+ sentencepiece
13
+ protobuf