昇思25天学习打卡营第9天 |昇思MindSpore 基于MindNLP+MusicGen生成自己的个性化音乐

一、MusicGen 模型原理

MusicGen 是由 Meta AI 的 Jade Copet 等人提出的基于单个语言模型(LM)的音乐生成模型。它能够依据文本描述或音频提示生成高质量的音乐样本,相关研究成果可参考论文《Simple and Controllable Music Generation》。

MusicGen 模型基于 Transformer 结构,可分解为以下三个阶段:

阶段描述
文本编码用户输入的文本描述被传递给固定的文本编码器模型(如谷歌的 t5-base),以获取一系列隐性状态表示。
音频 token 预测训练 MusicGen 解码器来预测离散的隐性状态音频 token。
音频解码使用音频压缩模型(如 EnCodec 32kHz)对音频 token 进行解码,以恢复音频波形。

MusicGen 解码器是针对音乐生成任务从零开始训练的语言模型架构。其创新之处在于音频代码的预测方式,采用单个 stage 的 Transformer LM 结合高效的 token 交织模式,取消了多层级的多个模型结构,如分层或上采样,从而能够生成单声道和立体声的高质量音乐样本,并提供更好的生成输出控制。此外,MusicGen 不仅能生成符合文本描述的音乐,还能通过旋律条件控制生成的音调结构。

二、下载模型

MusicGen 提供了 small、medium 和 big 三种规格的预训练权重文件,本指南默认使用 small 规格的权重。

操作代码
卸载旧版本 MindSpore!pip uninstall mindspore -y
安装指定版本 MindSpore!pip install -i https://pypi.mirrors.ustc.edu.cn/simple mindspore==2.2.14
安装其他所需库!pip install -i https://pypi.mirrors.ustc.edu.cn/simple mindnlp jieba soundfile librosa
查看 MindSpore 版本!pip show mindspore
导入模型from mindnlp.transformers import MusicgenForConditionalGeneration
model = MusicgenForConditionalGeneration.from_pretrained("facebook/musicgen-small")

三、生成音乐

MusicGen 支持贪心(greedy)和采样(sampling)两种生成模式,采样模式的结果通常优于贪心模式,默认启用采样模式,可在调用 MusicgenForConditionalGeneration.generate 时设置 do_sample=True 来显式指定。

  1. 无提示生成
操作代码
获取随机输入unconditional_inputs = model.get_unconditional_inputs(num_samples=1)
生成音频audio_values = model.generate(**unconditional_inputs, do_sample=True, max_new_tokens=256)
保存音频import scipy
sampling_rate = model.config.audio_encoder.sampling_rate
scipy.io.wavfile.write("musicgen_out.wav", rate=sampling_rate, data=audio_values[0, 0].asnumpy())

音频输出格式为 a Torch tensor of shape (batch_size, num_channels, sequence_length)

参数计算方式
生成音频长度(秒)audio_length_in_s = 256 / model.config.audio_encoder.frame_rate
  1. 文本提示生成
操作代码
预处理输入from mindnlp.transformers import AutoProcessor
processor = AutoProcessor.from_pretrained("facebook/musicgen-small")
inputs = processor(text=["80s pop track with bassy drums and synth", "90s rock song with loud guitars and heavy drums"], padding=True, return_tensors="ms")
生成音频audio_values = model.generate(**inputs, do_sample=True, guidance_scale=3, max_new_tokens=256)
保存音频scipy.io.wavfile.write("musicgen_out_text.wav", rate=sampling_rate, data=audio_values[0, 0].asnumpy())
  1. 音频提示生成
操作代码
数据准备和预处理from datasets import load_dataset
processor = AutoProcessor.from_pretrained("facebook/musicgen-small")
dataset = load_dataset("sanchit-gandhi/gtzan", split="train", streaming=True)
sample = next(iter(dataset))["audio"]
# take the first half of the audio sample
sample["array"] = sample["array"][: len(sample["array"]) // 2]
inputs = processor(audio=sample["array"], sampling_rate=sample["sampling_rate"], text=["80s blues track with groovy saxophone"], padding=True, return_tensors="ms")
生成音频audio_values = model.generate(**inputs, do_sample=True, guidance_scale=3, max_new_tokens=256)
保存音频scipy.io.wavfile.write("musicgen_out_audio.wav", rate=sampling_rate, data=audio_values[0, 0].asnumpy())

为演示批量音频提示生成,可对样本音频进行不同比例的切片,并在传递给模型前进行填充处理。

四、生成配置

参数默认值可修改值
采样模式do_sample=True可改为 do_sample=False
指导比例guidance_scale=3可增大,如 guidance_scale=4.0
最大生成 token 数max_new_tokens=1500可修改,如 max_new_tokens=256
Softmax 采样温度temperature可修改,如 temperature=1.5

控制生成过程的默认参数(如采样、指导比例和生成的令牌数量)可在模型的生成配置中找到并按需更新。

model.generation_config

# increase the guidance scale to 4.0
model.generation_config.guidance_scale = 4.0

# set the max new tokens to 256
model.generation_config.max_new_tokens = 256

# set the softmax sampling temperature to 1.5
model.generation_config.temperature = 1.5

audio_values = model.generate(**inputs)

需注意,传递给 generate 方法的参数会取代生成配置中的参数。

综上所述,通过上述步骤和配置,我们能够基于 MindNLP 和 MusicGen 生成个性化的音乐。在实际应用中,可根据具体需求灵活调整参数和输入,以获得满意的音乐生成效果。

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 以下是一个简单的微信小程序制作学习计划打记录页面的代码。 在 wxml 文件中,我们可以设置页面的布局和样式,以及与用户进行交互的组件,例如按钮、输入框等。 ```html <view class="container"> <view class="header"> <text class="title">学习计划打记录</text> </view> <view class="card"> <view class="card-heading"> <text class="card-title">Day 1</text> <text class="card-date">2021-01-01</text> </view> <view class="card-body"> <text class="card-label">学习时间:</text> <input class="card-input" type="number" placeholder="请输入学习时间(单位:小时)" /> </view> <view class="card-footer"> <button class="card-button">提交</button> </view> </view> <!-- Day 2、Day 3 等的片同上 --> </view> ``` 在 wxss 文件中,我们可以设置页面的样式,例如字体、颜色、边距等。 ```css .container { padding: 20rpx; } .header { text-align: center; margin-bottom: 20rpx; } .title { font-size: 36rpx; font-weight: bold; color: #333333; } .card { background-color: #ffffff; border-radius: 10rpx; box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.1); margin-bottom: 20rpx; } .card-heading { display: flex; justify-content: space-between; align-items: center; padding: 20rpx; border-bottom: 1rpx solid #f2f2f2; } .card-title { font-size: 28rpx; font-weight: bold; color: #333333; } .card-date { font-size: 24rpx; color: #999999; } .card-body { display: flex; align-items: center; padding: 20rpx; } .card-label { font-size: 28rpx; color: #333333; } .card-input { flex: 1; margin-left: 20rpx; font-size: 28rpx; color: #999999; border: none; } .card-footer { text-align: center; padding: 20rpx; } .card-button { font-size: 28rpx; color: #ffffff; background-color: #007aff; border-radius: 5rpx; padding: 10rpx 20rpx; } ``` 在 js 文件中,我们可以编写页面的逻辑代码。 ```javascript Page({ data: { days: [ { title: 'Day 1', date: '2021-01-01', time: null }, { title: 'Day 2', date: '2021-01-02', time: null }, { title: 'Day 3', date: '2021-01-03', time: null } // Day 4、Day 5 等的数据同上 ] }, handleInput: function(event) { // 获取输入框的值 let index = event.currentTarget.dataset.index; let value = event.detail.value; // 更新数据 let days = this.data.days; days[index].time = value; this.setData({ days: days }); }, handleSubmit: function(event) { // 获取提交按钮的索引 let index = event.currentTarget.dataset.index; // 获取对应的数据 let days = this.data.days; let day = days[index]; // 判断是否填写了学习时间 if (day.time === null || day.time === '') { wx.showToast({ title: '请填写学习时间', icon: 'none' }); return; } // 提交数据 wx.cloud.callFunction({ name: 'submit', data: { date: day.date, time: day.time }, success: res => { wx.showToast({ title: '提交成功' }); }, fail: err => { wx.showToast({ title: '提交失败', icon: 'none' }); } }); } }) ``` 以上代码是一个简单的微信小程序制作学习计划打记录页面的示例,仅供参考。具体实现方式可能因个人需求而异。 ### 回答2: 微信小程序制作学习计划打记录页面包含前几天的学习时间的全部代码如下: 首先,在小程序中创建一个page,命名为"studyRecord",在studyRecord.json文件中进行配置,设置"navigationBarTitleText"为"学习",并设置"usingComponents"引入相关组件: ``` { "navigationBarTitleText": "学习", "usingComponents": {} } ``` 接下来,在studyRecord.wxml文件中编写页面结构,包括一个日期选择器和一个列表用于展示打记录: ``` <view class="container"> <view class="header"> <picker mode="date" bindchange="dateChange"> <view class="date-picker">{{ currentDate }}</view> </picker> </view> <view class="record-list"> <block wx:for="{{ studyRecords }}" wx:key="index"> <view class="record-item"> <view class="item-date">{{ item.date }}</view> <view class="item-duration">{{ item.duration }}</view> </view> </block> </view> </view> ``` 我们在studyRecord.js文件中定义相关的事件处理函数和数据: ``` Page({ data: { currentDate: '', // 当前选择的日期 studyRecords: [] // 学习记录 }, onLoad: function () { // 获取最近几天的学习记录 this.getStudyRecords(); }, dateChange: function (event) { this.setData({ currentDate: event.detail.value }); // 根据选择日期的变化更新学习记录 this.getStudyRecords(); }, getStudyRecords: function () { // 根据当前日期获取学习记录,假设获取到的数据格式为[{ date: '2022/01/01', duration: '2小时' }, ...] // 可以通过调用接口或其他方式获取数据 const currentDate = this.data.currentDate; const studyRecords = this.getStudyRecordsByDate(currentDate); this.setData({ studyRecords: studyRecords }); }, getStudyRecordsByDate: function (date) { // 根据日期获取学习记录的逻辑实现 // ... return studyRecords; // 返回按日期查询到的学习记录 } }) ``` 在studyRecord.wxss文件中定义样式: ``` .container { padding: 10px; } .header { margin-bottom: 10px; } .date-picker { font-size: 18px; color: #333; padding: 10px; background-color: #f5f5f5; border-radius: 4px; text-align: center; } .record-list { background-color: #fff; border-radius: 4px; } .record-item { padding: 10px; border-bottom: solid 1px #eee; } .item-date { font-size: 14px; color: #666; } .item-duration { font-size: 16px; color: #333; } ``` 这样,一个包含前几天学习时间的微信小程序制作学习计划打记录页面的代码就完成了。 ### 回答3: 要制作微信小程序的学习计划打记录页面,可以按照以下步骤进行: 1. 首先,需要在微信开发者工具中创建一个新的小程序项目,并在app.json文件中配置页面路由信息。 2. 在项目的根目录下创建一个新的文件夹,用于存放页面相关的文件,比如study-record文件夹。 3. 在study-record文件夹中创建一个study-record.wxml文件用于编写页面的结构。 4. 在study-record文件夹中创建一个study-record.wxss文件用于编写页面的样式。 5. 在study-record文件夹中创建一个study-record.js文件用于编写页面的逻辑代码。 6. 在study-record.js中定义一个数据对象,用于存储前几天的学习时间。可以使用数组来存储每一天的学习时间,比如每个元素都是一个包含日期和学习时间的对象。 7. 在study-record.js中编写一个函数来获取前几天的学习时间。可以使用Date对象和相关的方法来计算前几天的日期,然后根据日期从数据对象中获取对应的学习时间。 8. 在study-record.js中编写一个函数来更新学习时间。可以通过用户输入的方式来更新某一天的学习时间,并将更新后的数据保存到数据对象中。 9. 在study-record.wxml中使用wx:for循环来遍历数据对象中的学习时间,并将日期和学习时间显示在页面上。 10. 在study-record.wxml中添加一个按钮,用于触发更新学习时间的函数。 11. 在study-record.js中监听按钮的点击事件,并在点击时触发更新学习时间的函数。 12. 在study-record.wxss中设置页面的样式,比如学习时间的字体大小、颜色等。 通过以上步骤,就可以完成微信小程序的学习计划打记录页面的制作。在页面中包含了前几天的学习时间,并提供了更新学习时间的功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值