【小沐学AI】Python实现语音识别(whisper+HuggingFace)

news2024/10/5 18:24:43

文章目录

  • 1、简介
    • 1.1 whisper
  • 2、HuggingFace
    • 2.1 安装transformers
    • 2.2 Pipeline 简介
    • 2.3 Tasks 简介
      • 2.3.1 sentiment-analysis
      • 2.3.2 zero-shot-classification
      • 2.3.3 text-generation
      • 2.3.4 fill-mask
      • 2.3.5 ner
      • 2.3.6 question-answering
      • 2.3.7 summarization
      • 2.3.8 translation
  • 3、测试
  • 结语

1、简介

1.1 whisper

https://arxiv.org/pdf/2212.04356
https://github.com/openai/whisper

Whisper 是一种通用语音识别模型。它是在各种音频的大型数据集上训练的,也是一个多任务模型,可以执行多语言语音识别、语音翻译和语言识别。
在这里插入图片描述
Transformer 序列到序列模型针对各种语音处理任务进行训练,包括多语言语音识别、语音翻译、口语识别和语音活动检测。这些任务共同表示为解码器要预测的一系列标记,从而允许单个模型取代传统语音处理管道的许多阶段。多任务训练格式使用一组特殊标记作为任务说明符或分类目标。

2、HuggingFace

https://www.hugging-face.org/models/

Hugging Face AI 是一个致力于机器学习和数据科学的平台和社区,帮助用户构建、部署和训练 ML 模型。它为在实际应用程序中演示、运行和实施 AI 提供了必要的基础设施。该平台使用户能够探索和利用其他人上传的模型和数据集。Hugging Face AI 通常被比作机器学习的 GitHub,它鼓励对开发人员的工作进行公开共享和测试。
在这里插入图片描述
该平台以其 Transformers Python 库而闻名,该库简化了访问和训练 ML 模型的过程。该库为开发人员提供了一种有效的方法,可以将 Hugging Face 中的 ML 模型集成到他们的项目中并建立 ML 管道。它是适用于 PyTorch、TensorFlow 和 JAX 的最先进的机器学习。

Hugging Face 提供了两种方式来访问大模型:

  • Inference API (Serverless) :通过 API 进行推理。
import requests
API_URL = "https://api-inference.huggingface.co/models/meta-llama/Llama-2-7b-hf"  
headers = {"Authorization": "Bearer xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}  
  
def query(payload):  
    response = requests.post(API_URL, headers=headers, json=payload)  
    return response.json()  
  
output = query({  
    "inputs": "Can you please let us know more details about your ",  
})

  • 本地执行 :使用 Hugging Face 的 pipeline 来进行高级操作。
from transformers import pipeline
pipe = pipeline("text-generation", model="meta-llama/Llama-2-7b-hf")

2.1 安装transformers

pip install transformers

在这里插入图片描述

2.2 Pipeline 简介

Pipeline将数据预处理、模型调用、结果后处理三部分组装成的流水线,使我们能够直接输入文本便获得最终的答案。
在这里插入图片描述

Pipeline的创建与使用方式:

# 1、根据任务类型直接创建Pipeline
pipe = pipeline("text-classification")

# 2、指定任务类型,再指定模型,创建基于指定模型的Pipeline
pipe = pipeline("text-classification", model="uer/roberta-base-finetuned-dianping-chinese")

# 3、预先加载模型,再创建Pipeline
# 必须同时指定model和tokenizer
model = AutoModelForSequenceClassification.from_pretrained("uer/roberta-base-finetuned-dianping-chinese")
tokenizer = AutoTokenizer.from_pretrained("uer/roberta-base-finetuned-dianping-chinese")
pipe = pipeline("text-classification", model=model, tokenizer=tokenizer)

# 4、使用GPU进行推理加速
pipe = pipeline("text-classification", model="uer/roberta-base-finetuned-dianping-chinese", device=0)

2.3 Tasks 简介

在这里插入图片描述
在这里插入图片描述
查看Pipeline支持的任务类型:

from transformers.pipelines import SUPPORTED_TASKS

print(SUPPORTED_TASKS.items())

在这里插入图片描述

for k, v in SUPPORTED_TASKS.items():
    print(k, v)

在这里插入图片描述

2.3.1 sentiment-analysis

from transformers import pipeline

classifier = pipeline("sentiment-analysis")
text = classifier("I've been waiting for a HuggingFace course my whole life.")
print(text)

text = classifier([
    "I've been waiting for a HuggingFace course my whole life.", 
    "I hate this so much!"
])
print(text)

在这里插入图片描述

2.3.2 zero-shot-classification

from transformers import pipeline

classifier = pipeline("zero-shot-classification")
text = classifier(
    "This is a course about the Transformers library",
    candidate_labels=["education", "politics", "business"],
)
print(text)

在这里插入图片描述

2.3.3 text-generation

from transformers import pipeline

generator = pipeline("text-generation")
text = generator("In this course, we will teach you how to")
print(text)

在这里插入图片描述

from transformers import pipeline

generator = pipeline("text-generation", model="distilgpt2")
text = generator(
    "In this course, we will teach you how to",
    max_length=30,
    num_return_sequences=2,
)
print(text)

在这里插入图片描述

2.3.4 fill-mask

from transformers import pipeline

unmasker = pipeline("fill-mask")
text = unmasker("This course will teach you all about <mask> models.", top_k=2)
print(text)

在这里插入图片描述

2.3.5 ner

from transformers import pipeline

ner = pipeline("ner", grouped_entities=True)
text = ner("My name is Sylvain and I work at Hugging Face in Brooklyn.")
print(text)

在这里插入图片描述

2.3.6 question-answering

from transformers import pipeline

question_answerer = pipeline("question-answering")
text = question_answerer(
    question="Where do I work?",
    context="My name is Sylvain and I work at Hugging Face in Brooklyn"
)
print(text)

在这里插入图片描述

2.3.7 summarization

from transformers import pipeline

summarizer = pipeline("summarization")
text = summarizer("""
    America has changed dramatically during recent years. Not only has the number of 
    graduates in traditional engineering disciplines such as mechanical, civil, 
    electrical, chemical, and aeronautical engineering declined, but in most of 
    the premier American universities engineering curricula now concentrate on 
    and encourage largely the study of engineering science. As a result, there 
    are declining offerings in engineering subjects dealing with infrastructure, 
    the environment, and related issues, and greater concentration on high 
    technology subjects, largely supporting increasingly complex scientific 
    developments. While the latter is important, it should not be at the expense 
    of more traditional engineering.

    Rapidly developing economies such as China and India, as well as other 
    industrial countries in Europe and Asia, continue to encourage and advance 
    the teaching of engineering. Both China and India, respectively, graduate 
    six and eight times as many traditional engineers as does the United States. 
    Other industrial countries at minimum maintain their output, while America 
    suffers an increasingly serious decline in the number of engineering graduates 
    and a lack of well-educated engineers.
""")
print(text)

在这里插入图片描述

2.3.8 translation

pip install sentencepiece
from transformers import pipeline

# translator = pipeline("translation", model="Helsinki-NLP/opus-mt-fr-en")
translator = pipeline("translation", model="Helsinki-NLP/opus-mt-en-zh")
text=translator("To support symlinks on Windows, you either need to activate Developer Mode or to run Python as an administrator.")
print(text)

在这里插入图片描述
使用HuggingFace的中译英模型和英译中模型。

  • (1)中译英
    中译英模型的模型名称为:opus-mt-zh-en,下载网址为:https://huggingface.co/Helsinki-NLP/opus-mt-zh-en/tree/main
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
from transformers import pipeline
 
model_path = './zh-en/'  
#创建tokenizer
tokenizer = AutoTokenizer.from_pretrained(model_path) 
#创建模型 
model = AutoModelForSeq2SeqLM.from_pretrained(model_path) 
#创建pipeline
pipeline = pipeline("translation", model=model, tokenizer=tokenizer)
 
 
chinese="""
中国男子篮球职业联赛(Chinese Basketball Association),简称中职篮(CBA),是由中国篮球协会所主办的跨年度主客场制篮球联赛,中国最高等级的篮球联赛,其中诞生了如姚明、王治郅、易建联、朱芳雨等球星。"""
result = pipeline(chinese)
print(result[0]['translation_text'])
  • (2)英译中
    英译中模型的模型名称为opus-mt-en-zh,下载网址为:https://huggingface.co/Helsinki-NLP/opus-mt-en-zh/tree/main
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
from transformers import pipeline
 
model_path = './en-zh/'  
#创建tokenizer
tokenizer = AutoTokenizer.from_pretrained(model_path) 
#创建模型 
model = AutoModelForSeq2SeqLM.from_pretrained(model_path) 
#创建pipeline
pipeline = pipeline("translation", model=model, tokenizer=tokenizer)
 
 
english="""
The official site of the National Basketball Association. Follow the action on NBA scores, schedules, stats, news, Team and Player news.
"""
result = pipeline(english)
print(result[0]['translation_text'])

3、测试

pipeline() 提供了在任何语言、计算机视觉、音频和多模态任务上使用 Hub 中的任何模型进行推理的简单方法。即使您对某个具体模态没有经验或者不熟悉模型背后的代码,您仍然可以使用 pipeline() 进行推理!

from transformers import pipeline

# 首先创建一个 pipeline() 并指定一个推理任务:
generator = pipeline(task="automatic-speech-recognition")

# 将输入文本传递给 pipeline():
text = generator("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac")
print(text)

在这里插入图片描述

  • 视觉任务的 pipeline
    对于视觉任务,使用 pipeline() 几乎是相同的。指定您的任务并将图像传递给分类器。图像可以是链接或图像的本地路径。例如,下面显示的是哪个品种的猫?
from transformers import pipeline

vision_classifier = pipeline(model="google/vit-base-patch16-224")
preds = vision_classifier(
    images="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
)
preds = [{"score": round(pred["score"], 4), "label": pred["label"]} for pred in preds]
print(preds)

在这里插入图片描述

  • 文本任务的 pipeline
    对于自然语言处理(NLP)任务,使用 pipeline() 几乎是相同的。
from transformers import pipeline

# 该模型是一个 `zero-shot-classification (零样本分类)` 模型。
# 它会对文本进行分类,您可以传入你能想到的任何标签
classifier = pipeline(model="facebook/bart-large-mnli")
text = classifier(
    "I have a problem with my iphone that needs to be resolved asap!!",
    candidate_labels=["urgent", "not urgent", "phone", "tablet", "computer"],
)
print(text)

在这里插入图片描述

  • 语音转文字
import os
from transformers import pipeline
import subprocess
import argparse
import json

os.environ["HF_ENDPOINT"] = "https://hf-mirror.com"
os.environ["CUDA_VISIBLE_DEVICES"] = "2"
os.environ["TF_ENABLE_ONEDNN_OPTS"] = "0"
 

def speech2text(speech_file):
    transcriber = pipeline(task="automatic-speech-recognition", model="openai/whisper-medium")
    text_dict = transcriber(speech_file)
    return text_dict
 

def main():
    # parser = argparse.ArgumentParser(description="语音转文本")
    # parser.add_argument("--audio","-a", type=str, help="输出音频文件路径")
 
    # args = parser.parse_args()
    # print(args) 
 
    # text_dict = speech2text(args.audio)
    text_dict = speech2text("test.mp3")
    print("语音识别的文本是:\n" +  text_dict["text"])
    print("语音识别的文本是:\n"+ json.dumps(text_dict,indent=4, ensure_ascii=False))
 
if __name__=="__main__":
    main()

在这里插入图片描述

更多AI信息如下:
在这里插入图片描述
2024第四届人工智能、自动化与高性能计算国际会议(AIAHPC 2024)将于2024年7月19-21日在中国·珠海召开。
大会网站:更多会议详情
时间地点:中国珠海-中山大学珠海校区|2024年7月19-21日

结语

如果您觉得该方法或代码有一点点用处,可以给作者点个赞,或打赏杯咖啡;╮( ̄▽ ̄)╭
如果您感觉方法或代码不咋地//(ㄒoㄒ)//,就在评论处留言,作者继续改进;o_O???
如果您需要相关功能的代码定制化开发,可以留言私信作者;(✿◡‿◡)
感谢各位大佬童鞋们的支持!( ´ ▽´ )ノ ( ´ ▽´)っ!!!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1878771.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

SM2258XT量产工具,SM2258XT开卡三星SSV4颗粒成功分享,SM2259XT量产参考教程,威刚ADATA SP580开卡记录

前两天拆了笔记本上的威刚ADATA SP580 240GB&#xff0c;准备做移动硬盘用&#xff0c;装入移动硬盘盒之后接入电脑&#xff0c;发现系统可认盘&#xff0c;SMART显示正常&#xff0c;Windows的磁盘管理能显示正确容量&#xff0c;但处于未初始化状态&#xff0c;且始终无法初始…

鸿蒙系统——强大的分布式系统

鸿蒙相比较于传统安卓最最最主要的优势是微内核分布式操作系统&#xff0c;具有面向未来&#xff0c;跨设备无缝协作&#xff0c;数据共享的全场景体验。下面简单来感受一下鸿蒙系统的多端自由流转。 自由流转概述 场景介绍 随着全场景多设备的生活方式不断深入&#xff0c;…

SSM网上旅游信息管理系统-计算机毕业设计源码06975

目 录 摘要 1 绪论 1.1 研究背景 1.2 研究意义 1.3论文结构与章节安排 2 系统分析 2.1 可行性分析 2.2 系统流程分析 2.2.1 数据新增流程 2.2.2 数据删除流程 2.3 系统功能分析 2.3.1 功能性分析 2.3.2 非功能性分析 2.4 系统用例分析 2.5本章小结 3 系统总体设…

计算神经网络中梯度的核心机制 - 反向传播(backpropagation)算法(1)

计算神经网络中梯度的核心机制 - 反向传播&#xff08;backpropagation&#xff09;算法&#xff08;1&#xff09; flyfish 链式法则在深度学习中的主要应用是在反向传播&#xff08;backpropagation&#xff09;算法中。 从简单的开始 &#xff0c;文本说的就是链式法则 R …

酒店客房管理系统(Java+MySQL)

技术栈 Java: 作为主要编程语言。Swing GUI: 用于开发图形用户界面。MySQL: 作为数据库管理系统。JDBC: 用于连接和操作MySQL数据库。 功能要点 管理登录认证 系统提供管理员登录认证功能。通过用户名和密码验证身份&#xff0c;确保只有授权的用户可以访问和管理酒店客房信…

如何利用react框架快速创建一个electron项目

1、搭建electron项目 创建一个electron入门项目还是很容易的&#xff0c;基体方法可以参考&#xff1a;eletron入门教程 -- 快速写一个electron demo程序 但是如果要利用react框架搭建一个electron项目&#xff0c;但是有一点麻烦&#xff0c;不过可以利用工具包来进行创建&am…

opengl 实现反锯齿

// 启用混合 //glEnable(GL_BLEND); // 设置混合函数 //glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); //glEnable(GL_POINT_SMOOTH); // 启用点平滑 //glHint(GL_POINT_SMOOTH_HINT, GL_NICEST); // 选择最佳点平滑 glEnable(GL_BLEND); glBlendFu…

这四款软件很好用,可以提升工作、学习效率

TableConvert TableConvert是一个基于Web的在线表格转换工具&#xff0c;能够将多种格式的表格数据进行快速转换。它支持将Excel、URL、HTML、JSON、CSV等格式转换为Markdown表、CSV/TSV、XML、YAML、插入SQL、HTML、Excel和LaTeX等格式。用户只需将表格数据粘贴到编辑器&#…

pikachu靶场 利用Rce上传一句话木马案例(工具:中国蚁剑)

目录 一、准备靶场&#xff0c;进入RCE 二、测试写入文件 三、使用中国蚁剑 一、准备靶场&#xff0c;进入RCE 我这里用的是pikachu 打开pikachu靶场&#xff0c;选择 RCE > exec "ping" 测试是否存在 Rce 漏洞 因为我们猜测在这个 ping 功能是直接调用系统…

驱动开发:配置Visual Studio驱动开发环境

100编程书屋_孔夫子旧书网 配置驱动开发环境配置驱动开发模板配置驱动双机调试 在正式开始驱动开发之前&#xff0c;需要自行搭建驱动开发的必要环境&#xff0c;首先我们需要安装Visual Studio 2013这款功能强大的程序开发工具&#xff0c;在课件内请双击ISO文件并运行内部的…

【单片机毕业设计选题24038】-基于STM32的木材厂环境监测系统

系统功能: 系统上电后根据采集到的传感器值自动控制&#xff0c;温度过高后自动开启风扇通风降温&#xff0c;湿度过 高后自动开启风扇除湿&#xff0c;光照过低后自动开启补光&#xff0c;雨量过高蜂鸣器报警&#xff0c;火焰传感器检 测到火灾后蜂鸣器报警并打开水泵灭火。…

(漏洞检查项) | 任意文件包含漏洞 file-include

(漏洞检查项)|任意文件包含漏洞 file-include 漏洞场景 1.含有动态包含语句 2.有类似于文件读取的url 漏洞描述 攻击者可以利用任意文件包含漏洞&#xff0c;读取任意文件&#xff0c;对服务器造成危害。 程序开发人员为了代码的灵活性&#xff0c;常常会将包含文件的路径…

c++重载(运算符)

1&#xff09;C入门级小知识&#xff0c;分享给将要学习或者正在学习C开发的同学。 2&#xff09;内容属于原创&#xff0c;若转载&#xff0c;请说明出处。 3&#xff09;提供相关问题有偿答疑和支持。 对于系统的所有操作符&#xff0c;一般情况下&#xff0c;只支持基本数…

算法:链表

目录 链表的技巧和操作总结 常用技巧&#xff1a; 链表中的常用操作 题目一&#xff1a;反转一个单链表 题目二&#xff1a;链表的中间结点 题目三&#xff1a;返回倒数第k个结点 题目四&#xff1a;合并两个有序链表 题目五&#xff1a;移除链表元素 题目六&#xff…

【快速排序】| 详解快速排序 力扣912

&#x1f397;️ 主页&#xff1a;小夜时雨 &#x1f397;️专栏&#xff1a;快速排序 &#x1f397;️如何活着&#xff0c;是我找寻的方向 目录 1. 题目解析2. 代码 1. 题目解析 题目链接: https://leetcode.cn/problems/sort-an-array/ 我们上道题讲过快速排序的核心代码&a…

三元表达式解析器

题意&#xff1a;其实本质上就是三目运算 &#xff0c;只不过跟我们以往的三目运算不同的是&#xff0c;这一系列的运算可以把T 和 F 都参与到运算中。设x5 表达式 x>2?T:F 最终返回T. 思路&#xff1a; 1.从后往前遍历字符数组 2.如果遇到的是 非&#xff1f;和 非&…

[C++][设计模式][中介者模式]详细讲解

目录 1.动机2.模式定义3.要点总结 1.动机 在软件构建过程中&#xff0c;经常会出现多个对象相互关联的情况&#xff0c;对象之间常常会维持一种复杂的引用关系&#xff0c;如果遇到一些需求的更改&#xff0c;这种直接的引用关系将面临不断的变化在这种情况下&#xff0c;可以…

2-自动驾驶关键技术框架

框架 来自《自动驾驶汽车决策与控制》这本书 三大技术 车载平台的关键技术&#xff1a; 环境感知技术&#xff1a;这是自动驾驶车辆能够“看”和“感知”周围世界的技术。它包括使用摄像头、雷达、激光雷达&#xff08;Lidar&#xff09;和超声波传感器来检测和识别道路、障…

Efficient Unified Demosaicing for Bayer and Non-Bayer Patterned Image Sensors

这篇文章是 2023 ICCV 的一篇文章&#xff0c;主要介绍一套统一的去马赛克的算法框架的 由于手机 Camera 上 CMOS 的单个 pixel size 比较小&#xff0c;所以现在很多手机的 Camera CMOS 会采用一些独特的非 Bayer 模式的 CFA (Quad, Nona 以及 Q X Q) 等&#xff0c;这类非 B…

redis实战-添加商户缓存

为什么要使用缓存 言简意赅&#xff1a;速度快&#xff0c;好用缓存数据存储于代码中&#xff0c;而代码运行在内存中&#xff0c;内存的读写性能远高于磁盘&#xff0c;缓存可以大大降低用户访问并发量带来的服务器读写压力实际开发中&#xff0c;企业的数据量&#xff0c;少…