Skip to content

Commit

Permalink
#1499 Добавляет методы Asr (#1506)
Browse files Browse the repository at this point in the history
* Исправляет параметры метода Messages.Send

* Добавляет метод Asr.CheckStatus

* Добавляет метод Asr.GetUploadUrl

* Добавляет метод Asr.Process
  • Loading branch information
Panuchi authored Apr 20, 2023
1 parent f9651ac commit e5ef1b3
Show file tree
Hide file tree
Showing 15 changed files with 359 additions and 0 deletions.
58 changes: 58 additions & 0 deletions VkNet.Tests/Categories/Asr/AsrCategoryTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
using System;
using FluentAssertions;
using VkNet.Enums.StringEnums;
using VkNet.Tests.Infrastructure;
using Xunit;

namespace VkNet.Tests.Categories.Asr;

public class AsrCategoryTest : CategoryBaseTest
{
protected override string Folder => "Asr";

[Fact]
public void CheckStatus()
{
Url = "https://api.vk.com/method/asr.checkStatus";

ReadCategoryJsonPath(nameof(CheckStatus));

var result = Api.Asr.CheckStatus("7ee0fa8e-64ac-4391-af7a-5c98a6330866");

result.Id.Should()
.Be("7ee0fa8e-64ac-4391-af7a-5c98a6330866");

result.Text.Should()
.Be("Это тестовая запись для сервиса распознавания речи ВКонтакте.");

result.Status.Should()
.Be(AsrStatus.Finished);
}

[Fact]
public void GetUploadUrl()
{
Url = "https://api.vk.com/method/asr.getUploadUrl";

ReadCategoryJsonPath(nameof(GetUploadUrl));

var result = Api.Asr.GetUploadUrl();

result.UploadUrl.Should()
.Be(new Uri(
"https://pu.vk.com/gu/speech/v2/upload?token=eyJ0e13iOiJKV1QiLCJhbGmdOiJIUzI1NiJ9.eyqlmAQiOjE2NjM1OTAzNDYsInZrX3VzZXJfaWQiOjgxNDI3MDksInZrX2FwcF9pZCI6ODE0MjcwOSwidmtfdXBsb2FkX3R5cGUiOiJzcGVlY2gifQ.9PStNUU8cf-rlFdPhM5hKQ2xSjhbxzxy7SRKYHvXC_M"));
}

[Fact]
public void Process()
{
Url = "https://api.vk.com/method/asr.process";

ReadCategoryJsonPath(nameof(Process));

var result = Api.Asr.Process("asd", AsrProcessModel.Neutral);

result.TaskId.Should()
.Be("7ee0fa8e-64ac-4391-af7a-5c98a6330866");
}
}
7 changes: 7 additions & 0 deletions VkNet.Tests/TestData/Categories/Asr/CheckStatus.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"response": {
"id": "7ee0fa8e-64ac-4391-af7a-5c98a6330866",
"status": "finished",
"text": "Это тестовая запись для сервиса распознавания речи ВКонтакте."
}
}
5 changes: 5 additions & 0 deletions VkNet.Tests/TestData/Categories/Asr/GetUploadUrl.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"response":{
"upload_url": "https://pu.vk.com/gu/speech/v2/upload?token=eyJ0e13iOiJKV1QiLCJhbGmdOiJIUzI1NiJ9.eyqlmAQiOjE2NjM1OTAzNDYsInZrX3VzZXJfaWQiOjgxNDI3MDksInZrX2FwcF9pZCI6ODE0MjcwOSwidmtfdXBsb2FkX3R5cGUiOiJzcGVlY2gifQ.9PStNUU8cf-rlFdPhM5hKQ2xSjhbxzxy7SRKYHvXC_M"
}
}
5 changes: 5 additions & 0 deletions VkNet.Tests/TestData/Categories/Asr/Process.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"response":{
"task_id": "7ee0fa8e-64ac-4391-af7a-5c98a6330866"
}
}
57 changes: 57 additions & 0 deletions VkNet/Abstractions/Category/Async/IAsrCategoryAsync.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
using System.Threading;
using System.Threading.Tasks;
using VkNet.Enums.StringEnums;
using VkNet.Model.Results.Asr;

namespace VkNet.Abstractions;

/// <summary>
/// Методы для работы с ASR
/// </summary>
public interface IAsrCategoryAsync
{
/// <summary>
/// Метод проверяет статус задачи на обработку аудиозаписи и возвращает текстовую расшифровку аудиозаписи
/// </summary>
/// <param name="taskId">
/// Идентификатор созданной задачи на обработку аудиозаписи в формате UUID.
/// </param>
/// <param name="token">Токен отмены</param>
/// <returns>
/// Возвращает объект задачи на обработку аудиозаписи.
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте https://dev.vk.com/method/asr.checkStatus
/// </remarks>
public Task<AudioRecordingTask> CheckStatusAsync(string taskId,
CancellationToken token = default);

/// <summary>
/// Метод возвращает ссылку на адрес сервера для загрузки аудиозаписи.
/// Обратите внимание! Ссылка доступна в течение 24 часов.
/// </summary>
/// <param name="token">Токен отмены</param>
/// <returns>
/// Возвращает параметр — ссылку на адрес сервера для загрузки аудиозаписи
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте https://dev.vk.com/method/asr.getUploadUrl
/// </remarks>
public Task<UploadUrlResult> GetUploadUrlAsync(CancellationToken token = default);

/// <summary>
/// Метод выполняет распознавание речи из загруженного файла аудиозаписи.
/// </summary>
/// <param name="model">Модель распознавания речи, которую нужно использовать</param>
/// <param name="token">Токен отмены</param>
/// <param name="audio">JSON-ответ из запроса на отправку файла аудиозаписи на адрес сервера загрузки.</param>
/// <returns>
/// Возвращает параметр — идентификатор созданной задачи на обработку аудиозаписи в формате UUID
/// </returns>
/// <remarks>
/// Страница документации ВКонтакте https://dev.vk.com/method/asr.process
/// </remarks>
public Task<TaskIdResult> ProcessAsync(string audio,
AsrProcessModel model,
CancellationToken token = default);
}
17 changes: 17 additions & 0 deletions VkNet/Abstractions/Category/IAsrCategory.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using VkNet.Enums.StringEnums;
using VkNet.Model.Results.Asr;

namespace VkNet.Abstractions;

/// <inheritdoc cref="IAsrCategoryAsync"/>
public interface IAsrCategory : IAsrCategoryAsync
{
/// <inheritdoc cref = "IAsrCategoryAsync.CheckStatusAsync"/>
AudioRecordingTask CheckStatus(string taskId);

/// <inheritdoc cref = "IAsrCategoryAsync.GetUploadUrlAsync"/>
UploadUrlResult GetUploadUrl();

/// <inheritdoc cref = "IAsrCategoryAsync.ProcessAsync"/>
TaskIdResult Process(string audio, AsrProcessModel model);
}
5 changes: 5 additions & 0 deletions VkNet/Abstractions/Core/IVkApiCategories.cs
Original file line number Diff line number Diff line change
Expand Up @@ -223,4 +223,9 @@ public interface IVkApiCategories
/// Donut
/// </summary>
IDownloadedGamesCategory DownloadedGames { get; }

/// <summary>
/// Asr
/// </summary>
IAsrCategory Asr { get; }
}
46 changes: 46 additions & 0 deletions VkNet/Categories/AsrCategory.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
using VkNet.Abstractions;
using VkNet.Enums.StringEnums;
using VkNet.Model.Results.Asr;
using VkNet.Utils;

namespace VkNet.Categories;

/// <inheritdoc />
public partial class AsrCategory : IAsrCategory
{
/// <summary>
/// API.
/// </summary>
private readonly IVkApiInvoke _vk;

/// <summary>
/// api vk.com
/// </summary>
/// <param name="vk"> API. </param>
public AsrCategory(IVkApiInvoke vk) => _vk = vk;

/// <inheritdoc />
public AudioRecordingTask CheckStatus(string taskId) => _vk.Call<AudioRecordingTask>("asr.checkStatus",
new()
{
{
"task_id", taskId
}
});

/// <inheritdoc />
public UploadUrlResult GetUploadUrl() => _vk.Call<UploadUrlResult>("asr.getUploadUrl",
VkParameters.Empty);

/// <inheritdoc />
public TaskIdResult Process(string audio, AsrProcessModel model) => _vk.Call<TaskIdResult>("asr.process",
new()
{
{
"audio", audio
},
{
"model", model
}
});
}
27 changes: 27 additions & 0 deletions VkNet/Categories/Async/AsrCategoryAsync.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
using System.Threading;
using System.Threading.Tasks;
using VkNet.Enums.StringEnums;
using VkNet.Model.Results.Asr;
using VkNet.Utils;

namespace VkNet.Categories;

/// <inheritdoc />
public partial class AsrCategory
{
/// <inheritdoc />
public Task<AudioRecordingTask> CheckStatusAsync(string taskId,
CancellationToken token = default) =>
TypeHelper.TryInvokeMethodAsync(() =>
CheckStatus(taskId), token);

/// <inheritdoc />
public Task<UploadUrlResult> GetUploadUrlAsync(CancellationToken token = default) =>
TypeHelper.TryInvokeMethodAsync(GetUploadUrl, token);

/// <inheritdoc />
public Task<TaskIdResult> ProcessAsync(string audio, AsrProcessModel model, CancellationToken token = default) =>
TypeHelper.TryInvokeMethodAsync(() =>
Process(audio, model), token);

}
23 changes: 23 additions & 0 deletions VkNet/Enums/StringEnums/AsrProcessModel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;

namespace VkNet.Enums.StringEnums;

/// <summary>
/// Модель распознавания речи, которую нужно использовать
/// </summary>
[StringEnum]
[JsonConverter(typeof(StringEnumConverter), typeof(SnakeCaseNamingStrategy))]
public enum AsrProcessModel
{
/// <summary>
/// Распознавание разборчивой речи, как в интервью или телешоу.
/// </summary>
Neutral,

/// <summary>
/// Распознавание речи со сленгом и ненормативной лексикой.
/// </summary>
Spontaneous
}
40 changes: 40 additions & 0 deletions VkNet/Enums/StringEnums/AsrStatus.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;

namespace VkNet.Enums.StringEnums;

/// <summary>
/// Права пользователя в рекламном кабинете.
/// </summary>
[StringEnum]
[JsonConverter(typeof(StringEnumConverter), typeof(SnakeCaseNamingStrategy))]
public enum AsrStatus
{
/// <summary>
/// Аудиозапись обрабатывается
/// </summary>
Processing,

/// <summary>
/// Обработка аудиозаписи закончена.
/// </summary>
Finished,

/// <summary>
/// Внутренние ошибки сервиса распознавания речи ВКонтакте.
/// </summary>
InternalError,

/// <summary>
/// Ошибка перекодирования аудиозаписи во внутренний формат.
/// Попробуйте загрузить аудиозапись в другом поддерживаемом формате.
/// </summary>
TranscodingError ,

/// <summary>
/// Ошибка распознавания речи, сложности в распознавании.
/// Попробуйте говорить чётче или снизить фоновые шумы.
/// </summary>
RecognitionError
}
30 changes: 30 additions & 0 deletions VkNet/Model/Results/Asr/AudioRecordingTask.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using System;
using Newtonsoft.Json;
using VkNet.Enums.StringEnums;

namespace VkNet.Model.Results.Asr;

/// <summary>
/// Объект задачи на обработку аудиозаписи
/// </summary>
[Serializable]
public class AudioRecordingTask
{
/// <summary>
/// Идентификатор созданной задачи на обработку аудиозаписи в формате UUID.
/// </summary>
[JsonProperty("id")]
public string Id { get; set; }

/// <summary>
/// Статус задачи на обработку аудиозаписи.
/// </summary>
[JsonProperty("status")]
public AsrStatus Status { get; set; }

/// <summary>
/// Расшифровка текста. Имеет значение, если параметр status имеет значение finished.
/// </summary>
[JsonProperty("text")]
public string Text { get; set; }
}
17 changes: 17 additions & 0 deletions VkNet/Model/Results/Asr/TaskIdResult.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using System;
using Newtonsoft.Json;

namespace VkNet.Model.Results.Asr;

/// <summary>
/// Объект TaskId
/// </summary>
[Serializable]
public class TaskIdResult
{
/// <summary>
/// Идентификатор созданной задачи на обработку аудиозаписи в формате UUID
/// </summary>
[JsonProperty("task_id")]
public string TaskId { get; set; }
}
17 changes: 17 additions & 0 deletions VkNet/Model/Results/Asr/UploadUrlResult.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using System;
using Newtonsoft.Json;

namespace VkNet.Model.Results.Asr;

/// <summary>
/// Объект UploadUrl
/// </summary>
[Serializable]
public class UploadUrlResult
{
/// <summary>
/// Ссылка на адрес сервера для загрузки аудиозаписи
/// </summary>
[JsonProperty("upload_url")]
public Uri UploadUrl { get; set; }
}
Loading

0 comments on commit e5ef1b3

Please sign in to comment.