【人工智能】使用NLP进行语音到文本的转换和主题的提取项目实践及案例分析二

使用自然语言处理(NLP)技术进行语音到文本的转换以及主题提取是一个非常实用的应用场景,尤其适用于会议记录、访谈转录等领域。在这个项目中,我们将分为两个主要部分:语音识别(Speech Recognition)和主题提取(Topic Extraction)。

项目概述

  1. 语音识别:将音频文件转换为文本。
  2. 主题提取:从转换后的文本中提取关键主题。

架构设计和技术栈

1. 语音识别
  • 工具:使用Google Cloud Speech-to-Text API或Whisper模型。
  • 技术栈:Python, Google Cloud SDK, OpenAI Whisper API
2. 主题提取
  • 技术:使用TF-IDF和LDA(Latent Dirichlet Allocation)进行主题建模。
  • 技术栈:Python, Scikit-learn, Gensim

示例代码

1. 语音识别

假设你已经有一个音频文件 speech.wav,我们将使用Google Cloud Speech-to-Text API进行语音识别。

# 导入所需的库
from google.cloud import speech_v1p1beta1 as speech
import io

# 设置Google Cloud凭证
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "path/to/your/credentials.json"

# 初始化客户端
client = speech.SpeechClient()

# 加载音频文件
with io.open("speech.wav", "rb") as audio_file:
    content = audio_file.read()
audio = speech.RecognitionAudio(content=content)

config = speech.RecognitionConfig(
    encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,
    sample_rate_hertz=16000,
    language_code="en-US",
)

# 调用API进行语音识别
response = client.recognize(config=config, audio=audio)

# 输出识别结果
for result in response.results:
    print("Transcript: {}".format(result.alternatives[0].transcript))

 如果你选择使用OpenAI的Whisper模型,你可以使用如下代码:

import whisper

# 加载Whisper模型
model = whisper.load_model("base")

# 语音文件路径
audio_file = "speech.wav"

# 识别音频文件
result = model.transcribe(audio_file)

# 输出识别结果
print(result["text"])
2. 主题提取

一旦我们有了文本数据,就可以进行主题提取。这里我们使用TF-IDF和LDA进行主题建模。

from gensim import corpora, models
from gensim.parsing.preprocessing import preprocess_string
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import LatentDirichletAllocation
import numpy as np

# 假设我们已经有了转换后的文本列表 `transcripts`
transcripts = [
    "This is the first sentence of the first transcript.",
    "This is another sentence from the second transcript.",
    "And this is yet another sentence."
]

# 文本预处理
processed_transcripts = [preprocess_string(doc) for doc in transcripts]

# 创建词典
dictionary = corpora.Dictionary(processed_transcripts)

# 创建文档-词频矩阵
corpus = [dictionary.doc2bow(text) for text in processed_transcripts]

# 使用TF-IDF转换
tfidf = models.TfidfModel(corpus)
corpus_tfidf = tfidf[corpus]

# 使用LDA进行主题建模
lda = models.LdaModel(corpus_tfidf, id2word=dictionary, num_topics=3)

# 输出主题
topics = lda.print_topics(num_words=5)
for topic in topics:
    print(topic)

完整代码

将上述片段整合成一个完整的脚本:

import os
import whisper
from gensim import corpora, models
from gensim.parsing.preprocessing import preprocess_string
from google.cloud import speech_v1p1beta1 as speech
import io

# 使用Google Cloud Speech-to-Text API
def transcribe_audio_google_cloud(audio_file):
    os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "path/to/your/credentials.json"
    client = speech.SpeechClient()
    
    with io.open(audio_file, "rb") as audio_file:
        content = audio_file.read()
    audio = speech.RecognitionAudio(content=content)
    
    config = speech.RecognitionConfig(
        encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,
        sample_rate_hertz=16000,
        language_code="en-US",
    )
    
    response = client.recognize(config=config, audio=audio)
    
    transcript = ""
    for result in response.results:
        transcript += result.alternatives[0].transcript
    
    return transcript

# 使用Whisper模型
def transcribe_audio_whisper(audio_file):
    model = whisper.load_model("base")
    result = model.transcribe(audio_file)
    return result["text"]

# 主题提取
def extract_topics(transcripts):
    processed_transcripts = [preprocess_string(doc) for doc in transcripts]
    dictionary = corpora.Dictionary(processed_transcripts)
    corpus = [dictionary.doc2bow(text) for text in processed_transcripts]
    tfidf = models.TfidfModel(corpus)
    corpus_tfidf = tfidf[corpus]
    lda = models.LdaModel(corpus_tfidf, id2word=dictionary, num_topics=3)
    topics = lda.print_topics(num_words=5)
    return topics

# 主函数
def main():
    # 语音识别
    transcript = transcribe_audio_google_cloud("speech.wav")
    # transcript = transcribe_audio_whisper("speech.wav")
    
    # 主题提取
    topics = extract_topics([transcript])
    print(topics)

if __name__ == "__main__":
    main()

注意事项

  • 你需要根据自己的需求选择合适的语音识别工具和服务。
  • 对于主题提取,你可能需要根据文本的具体内容调整LDA模型的参数。
  • 上述代码使用了简单的文本数据进行示例,实际应用中你需要使用真实的数据集。
  • 如果你打算在生产环境中部署这个应用,你可能需要考虑更复杂的预处理步骤和更高级的模型。

通过这个示例,你应该能够理解如何使用NLP技术进行语音到文本的转换以及主题提取的基本流程,接下来我们可以进一步完善这个项目,使其更加实用和高效。这包括以下几个方面:

  1. 增强语音识别:考虑使用更先进的模型,比如Whisper,以及对模型进行微调以提高准确性。
  2. 增强前端界面:添加更多的交互元素和样式,提升用户体验。
  3. 优化模型:考虑使用更先进的模型和参数调整以提高准确性。
  4. 集成API:为前端应用提供一个与后端API交互的界面。
  5. 部署到服务器:将前端和后端部署到云服务器上,使其对外界可用。

1. 增强语音识别

我们可以考虑使用更先进的模型,比如Whisper。Whisper是由OpenAI开发的一个强大的语音识别模型,它在多种语言和应用场景下都表现出了优秀的性能。

1.1 使用Whisper进行语音识别
import whisper

def transcribe_audio_whisper(audio_file):
    # 加载Whisper模型
    model = whisper.load_model("medium")
    
    # 识别音频文件
    result = model.transcribe(audio_file)
    
    # 输出识别结果
    return result["text"]

2. 增强前端界面

我们可以使用HTML和JavaScript来创建一个用户友好的前端界面,让用户能够上传音频文件并查看转换后的文本以及提取的主题。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Speech to Text and Topic Extraction</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      max-width: 800px;
      margin: 0 auto;
      padding: 20px;
    }
    h1 {
      color: #333;
    }
    form {
      margin-bottom: 20px;
    }
    button {
      padding: 10px 20px;
      background-color: #007BFF;
      color: white;
      border: none;
      cursor: pointer;
    }
    button:hover {
      background-color: #0056b3;
    }
    #transcription, #topics {
      margin-top: 20px;
      padding: 10px;
      background-color: #f8f9fa;
      border: 1px solid #dee2e6;
    }
  </style>
</head>
<body>
  <h1>Speech to Text and Topic Extraction</h1>
  
  <form id="uploadForm" enctype="multipart/form-data">
    <input type="file" name="audio" accept=".wav,.mp3" required />
    <button type="submit">Upload and Transcribe</button>
  </form>
  
  <div id="transcription"></div>
  <div id="topics"></div>
  
  <script>
    const uploadForm = document.getElementById('uploadForm');
    const transcriptionDiv = document.getElementById('transcription');
    const topicsDiv = document.getElementById('topics');

    uploadForm.addEventListener('submit', async (event) => {
      event.preventDefault();
      
      const formData = new FormData(event.target);
      const audioFile = formData.get('audio');
      
      if (!audioFile) {
        alert('Please select an audio file.');
        return;
      }
      
      // Upload the audio file to the server
      const response = await fetch('/transcribe', {
        method: 'POST',
        body: formData
      });
      
      if (!response.ok) {
        alert('There was a problem with the transcription.');
        return;
      }
      
      const transcription = await response.json();
      transcriptionDiv.textContent = `Transcription: ${transcription.transcription}`;
      
      // Extract topics from the transcription
      const topicsResponse = await fetch('/extract-topics', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ transcripts: [transcription.transcription] })
      });
      
      if (!topicsResponse.ok) {
        alert('There was a problem extracting topics.');
        return;
      }
      
      const topics = await topicsResponse.json();
      topicsDiv.textContent = `Topics: \n${topics.topics.map(topic => topic[1]).join('\n')}`;
    });
  </script>
</body>
</html>

2. 优化模型

我们可以考虑使用更先进的模型,比如Whisper的不同版本,并调整LDA模型的参数以提高主题提取的质量。

2.1 使用更先进的Whisper模型
import whisper

def transcribe_audio_whisper(audio_file):
    # 加载Whisper模型
    model = whisper.load_model("large-v2")
    
    # 识别音频文件
    result = model.transcribe(audio_file)
    
    # 输出识别结果
    return result["text"]
 2.2 调整LDA模型的参数
from gensim import corpora, models
from gensim.parsing.preprocessing import preprocess_string, strip_punctuation, strip_numeric, strip_non_alphanum, remove_stopwords, strip_short

def extract_topics(transcripts):
    # 预处理文本
    processed_transcripts = [preprocess_text(doc) for doc in transcripts]
    
    # 创建词典
    dictionary = corpora.Dictionary(processed_transcripts)
    
    # 创建文档-词频矩阵
    corpus = [dictionary.doc2bow(text) for text in processed_transcripts]
    
    # 使用TF-IDF转换
    tfidf = models.TfidfModel(corpus)
    corpus_tfidf = tfidf[corpus]
    
    # 使用LDA进行主题建模
    lda = models.LdaModel(corpus_tfidf, id2word=dictionary, num_topics=5, passes=20, iterations=400)
    
    # 输出主题
    topics = lda.print_topics(num_words=10)
    return topics

3. 集成API

为了让前端应用能够调用后端API,我们需要确保API能够正常工作并与前端进行交互。

3.1 创建API (Node.js + Express)
const express = require('express');
const bodyParser = require('body-parser');
const multer = require('multer');
const fs = require('fs');
const path = require('path');
const whisper = require('whisper');

const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// Set up storage for uploaded files
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './uploads/')
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + '-' + file.originalname)
  }
});

const upload = multer({ storage: storage });

// Transcribe audio using Whisper
async function transcribeAudioWhisper(audioFilePath) {
  const model = whisper.loadModel("large-v2");
  const result = await model.transcribe(audioFilePath);
  return result.text;
}

// Extract topics from the text
function extractTopics(transcripts) {
  // ... existing code for topic extraction ...
}

// Upload and transcribe audio endpoint
app.post('/transcribe', upload.single('audio'), async (req, res) => {
  try {
    const filePath = path.join(__dirname, 'uploads', req.file.filename);
    const transcription = await transcribeAudioWhisper(filePath);
    fs.unlinkSync(filePath); // Delete the uploaded file after processing
    res.json({ transcription: transcription });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: 'Error transcribing audio' });
  }
});

// Extract topics from text endpoint
app.post('/extract-topics', async (req, res) => {
  try {
    const transcripts = req.body.transcripts;
    const topics = extractTopics(transcripts);
    res.json({ topics: topics });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: 'Error extracting topics' });
  }
});

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

4. 部署到服务器

你可以将前端和后端分别部署到云服务器上,例如使用Heroku或AWS。这里就不详细展开部署过程了,但你可以参考各个云服务商的文档来进行部署。

完整代码

将上述片段整合成一个完整的脚本:

import whisper
from gensim import corpora, models
from gensim.parsing.preprocessing import preprocess_string, strip_punctuation, strip_numeric, strip_non_alphanum, remove_stopwords, strip_short

# 使用Whisper模型
def transcribe_audio_whisper(audio_file):
    model = whisper.load_model("large-v2")
    result = model.transcribe(audio_file)
    return result["text"]

# 文本预处理
def preprocess_text(text):
    custom_filters = [
        lambda x: x.lower(),
        strip_punctuation,
        strip_numeric,
        strip_non_alphanum,
        remove_stopwords,
        strip_short
    ]
    processed_text = preprocess_string(text, custom_filters)
    return processed_text

# 主题提取
def extract_topics(transcripts):
    processed_transcripts = [preprocess_text(doc) for doc in transcripts]
    dictionary = corpora.Dictionary(processed_transcripts)
    corpus = [dictionary.doc2bow(text) for text in processed_transcripts]
    tfidf = models.TfidfModel(corpus)
    corpus_tfidf = tfidf[corpus]
    lda = models.LdaModel(corpus_tfidf, id2word=dictionary, num_topics=5, passes=20, iterations=400)
    topics = lda.print_topics(num_words=10)
    return topics

# 主函数
def main():
    # 语音识别
    transcript = transcribe_audio_whisper("speech.wav")
    
    # 主题提取
    topics = extract_topics([transcript])
    print(topics)

if __name__ == "__main__":
    main()

注意事项

  • 你需要安装Whisper库,可以通过 pip install git+https://github.com/openai/whisper.git 来安装。
  • 对于主题提取,你可能需要根据文本的具体内容调整LDA模型的参数。
  • 上述代码使用了简单的文本数据进行示例,实际应用中你需要使用真实的数据集。
  • 如果你打算在生产环境中部署这个应用,你可能需要考虑更复杂的预处理步骤和更高级的模型。

通过这些步骤,你将能够构建一个功能完整的声音到文本转换及主题提取应用,其中包括了先进的Whisper模型以及一个用户友好的前端界面和可被其他应用程序调用的API。希望这个项目对你有所帮助!如果有任何疑问或需要进一步的帮助,请随时告诉我。

 如果文章内容对您有所触动,别忘了点赞、关注,收藏! 

  人工智能相关文章推荐阅读
【人工智能】TensorFlow和机器学习概述

【人工智能】TensorFlow简介,应用场景,使用方法以及项目实践及案例分析,附带源代码

【人工智能】常用的人工智能框架、模型、使用方法、应用场景以及代码实例的概述

【人工智能】图像识别:计算机视觉领域的识别与处理资源概览

【人工智能】人工智能可解释性和透明度的详细探讨

  • 17
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@我们的天空

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值