Skip to content

Commit

Permalink
Add WebAPI app (#6)
Browse files Browse the repository at this point in the history
  • Loading branch information
justinyoo authored Oct 1, 2023
1 parent 694b188 commit 2fa1e87
Show file tree
Hide file tree
Showing 7 changed files with 242 additions and 1 deletion.
9 changes: 8 additions & 1 deletion YouTubeSummariser.sln
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{F0754B28-F0B
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "YouTubeSummariser.ApiApp", "src\YouTubeSummariser.ApiApp\YouTubeSummariser.ApiApp.csproj", "{D2B6ACCD-125F-4AB8-B072-0F3C104AEBB2}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "YouTubeSummariser.Services", "src\YouTubeSummariser.Services\YouTubeSummariser.Services.csproj", "{47F2E24C-23E7-4E07-B52A-7A33C5165645}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "YouTubeSummariser.ApiApp2", "src\YouTubeSummariser.ApiApp2\YouTubeSummariser.ApiApp2.csproj", "{CEB81668-3BE6-4BBC-BA78-7AD7F64F80C6}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "YouTubeSummariser.Services", "src\YouTubeSummariser.Services\YouTubeSummariser.Services.csproj", "{47F2E24C-23E7-4E07-B52A-7A33C5165645}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "YouTubeSummariser.WebApp.Wasm", "src\YouTubeSummariser.WebApp.Wasm\YouTubeSummariser.WebApp.Wasm.csproj", "{BA0E2490-C014-4325-85C3-5132FEBE1844}"
EndProject
Expand All @@ -23,6 +25,10 @@ Global
{D2B6ACCD-125F-4AB8-B072-0F3C104AEBB2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D2B6ACCD-125F-4AB8-B072-0F3C104AEBB2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D2B6ACCD-125F-4AB8-B072-0F3C104AEBB2}.Release|Any CPU.Build.0 = Release|Any CPU
{CEB81668-3BE6-4BBC-BA78-7AD7F64F80C6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CEB81668-3BE6-4BBC-BA78-7AD7F64F80C6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CEB81668-3BE6-4BBC-BA78-7AD7F64F80C6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CEB81668-3BE6-4BBC-BA78-7AD7F64F80C6}.Release|Any CPU.Build.0 = Release|Any CPU
{47F2E24C-23E7-4E07-B52A-7A33C5165645}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{47F2E24C-23E7-4E07-B52A-7A33C5165645}.Debug|Any CPU.Build.0 = Debug|Any CPU
{47F2E24C-23E7-4E07-B52A-7A33C5165645}.Release|Any CPU.ActiveCfg = Release|Any CPU
Expand All @@ -41,6 +47,7 @@ Global
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{D2B6ACCD-125F-4AB8-B072-0F3C104AEBB2} = {F0754B28-F0B2-414C-83DB-06854DBF508E}
{CEB81668-3BE6-4BBC-BA78-7AD7F64F80C6} = {F0754B28-F0B2-414C-83DB-06854DBF508E}
{47F2E24C-23E7-4E07-B52A-7A33C5165645} = {F0754B28-F0B2-414C-83DB-06854DBF508E}
{BA0E2490-C014-4325-85C3-5132FEBE1844} = {F0754B28-F0B2-414C-83DB-06854DBF508E}
{8F0B64D6-E1A2-487F-8978-AA91A2732AF3} = {F0754B28-F0B2-414C-83DB-06854DBF508E}
Expand Down
90 changes: 90 additions & 0 deletions src/YouTubeSummariser.ApiApp2/Controllers/SummariseController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
using System.Net;
using System.Net.Mime;

using Microsoft.AspNetCore.Mvc;

using YouTubeSummariser.Services;
using YouTubeSummariser.Services.Models;

namespace YouTubeSummariser.ApiApp2.Controllers;
[ApiController]
[Route("api")]
public class SummariseController : ControllerBase
{
private readonly IOpenAIService _openai;
private readonly IYouTubeService _youtube;
private readonly ILogger<SummariseController> _logger;

public SummariseController(IOpenAIService openai, IYouTubeService youtube, ILogger<SummariseController> logger)
{
this._openai = openai ?? throw new ArgumentNullException(nameof(openai));
this._youtube = youtube ?? throw new ArgumentNullException(nameof(youtube));
this._logger = logger;
}

[HttpPost("summarise", Name = "summarise")]
[Consumes(typeof(SummariseRequestModel), MediaTypeNames.Application.Json)]
[Produces(typeof(string))]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
[ProducesResponseType((int)HttpStatusCode.InternalServerError)]
public async Task<IActionResult> SummariseAsync([FromBody] SummariseRequestModel req)
{
this._logger.LogInformation("C# HTTP trigger function processed a request.");

Check warning on line 32 in src/YouTubeSummariser.ApiApp2/Controllers/SummariseController.cs

View workflow job for this annotation

GitHub Actions / Build Test

For improved performance, use the LoggerMessage delegates instead of calling 'LoggerExtensions.LogInformation(ILogger, string?, params object?[])' (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1848)

var response = default(IActionResult);
var payload = req;
if (payload == null)
{
this._logger.LogError("Payload is null.");

Check warning on line 38 in src/YouTubeSummariser.ApiApp2/Controllers/SummariseController.cs

View workflow job for this annotation

GitHub Actions / Build Test

For improved performance, use the LoggerMessage delegates instead of calling 'LoggerExtensions.LogError(ILogger, string?, params object?[])' (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1848)

response = new StatusCodeResult((int)HttpStatusCode.BadRequest);
return response;
}
if (string.IsNullOrWhiteSpace(payload.VideoUrl) == true)
{
this._logger.LogError("Video URL is null or empty.");

Check warning on line 45 in src/YouTubeSummariser.ApiApp2/Controllers/SummariseController.cs

View workflow job for this annotation

GitHub Actions / Build Test

For improved performance, use the LoggerMessage delegates instead of calling 'LoggerExtensions.LogError(ILogger, string?, params object?[])' (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1848)

response = new StatusCodeResult((int)HttpStatusCode.BadRequest);
return response;
}
if (string.IsNullOrWhiteSpace(payload.VideoLanguageCode) == true)
{
payload.VideoLanguageCode = "en";
}
if (string.IsNullOrWhiteSpace(payload.SummaryLanguageCode) == true)
{
payload.SummaryLanguageCode = payload.VideoLanguageCode;
}

try
{
var result = new ContentResult() { ContentType = MediaTypeNames.Text.Plain, StatusCode = (int)HttpStatusCode.OK };

var transcript = await this._youtube.GetTranscriptAsync(payload.VideoUrl, payload.VideoLanguageCode);
if (string.IsNullOrWhiteSpace(transcript) == true)
{
var message = "The given YouTube video doesn't provide transcripts.";
this._logger.LogInformation(message);

Check warning on line 67 in src/YouTubeSummariser.ApiApp2/Controllers/SummariseController.cs

View workflow job for this annotation

GitHub Actions / Build Test

For improved performance, use the LoggerMessage delegates instead of calling 'LoggerExtensions.LogInformation(ILogger, string?, params object?[])' (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1848)

result.Content = message;
response = result;

return response;
}

var completion = await this._openai.GetCompletionsAsync(transcript, payload.SummaryLanguageCode);

result.Content = completion;
response = result;

return response;
}
catch (Exception ex)
{
this._logger.LogError(ex, ex.Message);

response = new StatusCodeResult((int)HttpStatusCode.InternalServerError);
return response;
}
}
}
54 changes: 54 additions & 0 deletions src/YouTubeSummariser.ApiApp2/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
using Aliencube.YouTubeSubtitlesExtractor;
using Aliencube.YouTubeSubtitlesExtractor.Abstractions;

using Azure;
using Azure.AI.OpenAI;

using YouTubeSummariser.Services;
using YouTubeSummariser.Services.Configurations;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var openAISettings = builder.Configuration
.GetSection(OpenAISettings.Name)
.Get<OpenAISettings>();
builder.Services.AddSingleton(openAISettings);

Check warning on line 22 in src/YouTubeSummariser.ApiApp2/Program.cs

View workflow job for this annotation

GitHub Actions / Build Test

The type 'YouTubeSummariser.Services.Configurations.OpenAISettings?' cannot be used as type parameter 'TService' in the generic type or method 'ServiceCollectionServiceExtensions.AddSingleton<TService>(IServiceCollection, TService)'. Nullability of type argument 'YouTubeSummariser.Services.Configurations.OpenAISettings?' doesn't match 'class' constraint.

var promptSettings = builder.Configuration
.GetSection(PromptSettings.Name)
.Get<PromptSettings>();
builder.Services.AddSingleton(promptSettings);

Check warning on line 27 in src/YouTubeSummariser.ApiApp2/Program.cs

View workflow job for this annotation

GitHub Actions / Build Test

The type 'YouTubeSummariser.Services.Configurations.PromptSettings?' cannot be used as type parameter 'TService' in the generic type or method 'ServiceCollectionServiceExtensions.AddSingleton<TService>(IServiceCollection, TService)'. Nullability of type argument 'YouTubeSummariser.Services.Configurations.PromptSettings?' doesn't match 'class' constraint.

var endpoint = new Uri(openAISettings.Endpoint);

Check warning on line 29 in src/YouTubeSummariser.ApiApp2/Program.cs

View workflow job for this annotation

GitHub Actions / Build Test

Dereference of a possibly null reference.

Check warning on line 29 in src/YouTubeSummariser.ApiApp2/Program.cs

View workflow job for this annotation

GitHub Actions / Build Test

Possible null reference argument for parameter 'uriString' in 'Uri.Uri(string uriString)'.
var credential = new AzureKeyCredential(openAISettings.ApiKey);

Check warning on line 30 in src/YouTubeSummariser.ApiApp2/Program.cs

View workflow job for this annotation

GitHub Actions / Build Test

Possible null reference argument for parameter 'key' in 'AzureKeyCredential.AzureKeyCredential(string key)'.
var client = new OpenAIClient(endpoint, credential);
builder.Services.AddScoped<OpenAIClient>(_ => client);

builder.Services.AddHttpClient();
builder.Services.AddScoped<IYouTubeVideo, YouTubeVideo>();
builder.Services.AddScoped<IYouTubeService, YouTubeService>();
builder.Services.AddScoped<IOpenAIService, OpenAIService>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();
41 changes: 41 additions & 0 deletions src/YouTubeSummariser.ApiApp2/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:5000",
"sslPort": 5001
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
17 changes: 17 additions & 0 deletions src/YouTubeSummariser.ApiApp2/YouTubeSummariser.ApiApp2.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<AssemblyName>YouTubeSummariser.ApiApp2</AssemblyName>
<RootNamespace>YouTubeSummariser.ApiApp2</RootNamespace>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.11" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\YouTubeSummariser.Services\YouTubeSummariser.Services.csproj" />
</ItemGroup>

</Project>
13 changes: 13 additions & 0 deletions src/YouTubeSummariser.ApiApp2/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"OpenAI": {
"Endpoint": "https://aoai-summariser4276.openai.azure.com/",
"ApiKey": "48774d2dadd14214ac79c0997ce87f0c",
"DeploymentId": "model-gpt432k"
}
}
19 changes: 19 additions & 0 deletions src/YouTubeSummariser.ApiApp2/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"OpenAI": {
"Endpoint": "{{AOAI_ENDPOINT_URL}}",
"ApiKey": "{{AOAI_API_KEY}}",
"DeploymentId": "{{AOAI_DEPLOYMENT_ID}}"
},
"Prompt": {
"System": "You are the expert of summarising long contents. You are going to summarise the following YouTube video transcript in a given language code.",
"MaxTokens": 3000,
"Temperature": 0.7
},
"AllowedHosts": "*"
}

0 comments on commit 2fa1e87

Please sign in to comment.