LiuPengNGP commited on
Commit
eb4b4ff
·
1 Parent(s): cb51d0f
Files changed (1) hide show
  1. app.py +37 -10
app.py CHANGED
@@ -3,9 +3,10 @@ import os
3
  import soundfile as sf
4
  from pydub import AudioSegment
5
  import numpy as np
 
 
6
 
7
  def record_audio(audio):
8
- # 获取音频文件路径
9
  audio_file = audio
10
 
11
  # 读取音频文件
@@ -27,20 +28,46 @@ def record_audio(audio):
27
  filename = "voice.wav"
28
  sf.write(filename, audio_data, sample_rate)
29
 
30
- return "录音成功!已保存为 " + filename, audio
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
 
32
  # 创建 Gradio 界面
33
  with gr.Blocks() as demo:
34
- gr.Markdown("### 录音功能")
35
-
36
- with gr.Row():
37
- record_button = gr.Audio(label="录音", type="filepath")
38
- submit_button = gr.Button("提交录音")
39
-
40
- message = gr.Textbox(label="消息")
41
 
 
 
 
 
 
 
42
  # 设置提交按钮的回调
43
- submit_button.click(record_audio, inputs=record_button, outputs=[message, record_button])
 
44
 
45
  # 启动 Gradio 应用
46
  demo.launch()
 
3
  import soundfile as sf
4
  from pydub import AudioSegment
5
  import numpy as np
6
+ from transformers import Wav2Vec2Processor
7
+ import torch
8
 
9
  def record_audio(audio):
 
10
  audio_file = audio
11
 
12
  # 读取音频文件
 
28
  filename = "voice.wav"
29
  sf.write(filename, audio_data, sample_rate)
30
 
31
+ return filename # 返回保存的文件路径
32
+
33
+ def voice_sentiment(voice):
34
+ MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn"
35
+ processor = Wav2Vec2Processor.from_pretrained(MODEL_ID)
36
+
37
+ model_path = 'sentiment_rnn_model.pth' # 已训练好的模型路径
38
+ input_size = 200000 # 根据最大特征长度设定
39
+ hidden_size = 128
40
+ num_layers = 2
41
+
42
+ # 加载模型
43
+ model = load_model(model_path, input_size, hidden_size, num_layers)
44
+
45
+ # 读取音频文件进行情感预测
46
+ audio_data, sample_rate = sf.read(voice)
47
+
48
+ # 进行情感预测
49
+ max_length = input_size
50
+ predicted_value, predicted_class = predict(voice, processor, model, max_length)
51
+
52
+ # 输出结果
53
+ if predicted_value is not None:
54
+ return f'Predicted value: {predicted_value}, Predicted class: {"Positive" if predicted_class == 1 else "Negative"}'
55
+ else:
56
+ return "预测失败,未能处理音频文件。"
57
 
58
  # 创建 Gradio 界面
59
  with gr.Blocks() as demo:
60
+ gr.Markdown("### 录音与情感分析")
 
 
 
 
 
 
61
 
62
+ with gr.Row("音频情感分析"):
63
+ with gr.Column():
64
+ record_button = gr.Audio(label="录音", type="filepath")
65
+ submit_button = gr.Button("提交录音")
66
+ voice_output = gr.Textbox(label="情感数据")
67
+
68
  # 设置提交按钮的回调
69
+ submit_button.click(record_audio, inputs=record_button, outputs=voice_output)
70
+ voice_output.change(voice_sentiment, inputs=voice_output, outputs=voice_output)
71
 
72
  # 启动 Gradio 应用
73
  demo.launch()