From 8c0a2e45be96f633100698384444b88ed2e7f6b3 Mon Sep 17 00:00:00 2001 From: cmendible <266546+cmendible@users.noreply.github.com> Date: Fri, 1 Dec 2023 10:02:21 +0100 Subject: [PATCH] .NET 8, dockerfile, global usings & formating issues --- src/AIHub/AIHub.csproj | 2 +- .../Controllers/BrandAnalyzerController.cs | 84 +++----- src/AIHub/Controllers/CallCenterController.cs | 36 +--- .../Controllers/ContentSafetyController.cs | 21 +- .../Controllers/FormAnalyzerController.cs | 22 -- src/AIHub/Controllers/HomeController.cs | 14 +- .../Controllers/ImageAnalyzerController.cs | 202 ++++++++---------- src/AIHub/Dockerfile | 15 ++ src/AIHub/GlobalUsings.cs | 13 ++ src/AIHub/Models/BrandAnalyzerModel.cs | 5 +- src/AIHub/Models/CallCenterModel.cs | 5 +- src/AIHub/Models/ContentSafetyModel.cs | 5 +- src/AIHub/Models/FormAnalyzer.cs | 5 +- src/AIHub/Models/ImageAnalyzerModel.cs | 5 +- src/AIHub/SampleCode.cs | 55 ++--- .../Views/BrandAnalyzer/BrandAnalyzer.cshtml | 2 +- src/AIHub/Views/CallCenter/CallCenter.cshtml | 4 +- .../Views/ContentSafety/TextModerator.cshtml | 32 +-- .../Views/FormAnalyzer/FormAnalyzer.cshtml | 8 +- src/AIHub/Views/Home/Index.cshtml | 105 +++++---- src/AIHub/Views/Home/Privacy.cshtml | 3 +- src/AIHub/Views/Shared/Error.cshtml | 6 +- 22 files changed, 312 insertions(+), 337 deletions(-) create mode 100644 src/AIHub/Dockerfile create mode 100644 src/AIHub/GlobalUsings.cs diff --git a/src/AIHub/AIHub.csproj b/src/AIHub/AIHub.csproj index 83cd451..86e3b75 100644 --- a/src/AIHub/AIHub.csproj +++ b/src/AIHub/AIHub.csproj @@ -1,7 +1,7 @@ - net7.0 + net8.0 enable enable diff --git a/src/AIHub/Controllers/BrandAnalyzerController.cs b/src/AIHub/Controllers/BrandAnalyzerController.cs index 530ff17..e1b745b 100644 --- a/src/AIHub/Controllers/BrandAnalyzerController.cs +++ b/src/AIHub/Controllers/BrandAnalyzerController.cs @@ -1,19 +1,3 @@ -using System.Diagnostics; -using Microsoft.AspNetCore.Mvc; -using MVCWeb.Models; -using Azure.AI.ContentSafety; -using Azure; -using ContentSafetySampleCode; -using System; -using Azure.Storage.Blobs; -using Azure.Identity; -using Azure.AI.OpenAI; -using System; -using System.Collections.Generic; -using System.Net.Http; -using System.Net.Http.Headers; -using Newtonsoft.Json; - namespace MVCWeb.Controllers; public class BrandAnalyzerController : Controller @@ -31,10 +15,10 @@ public class BrandAnalyzerController : Controller public BrandAnalyzerController(IConfiguration config) { _config = config; - Bingendpoint= _config.GetValue("BrandAnalyzer:BingEndpoint"); - BingsubscriptionKey= _config.GetValue("BrandAnalyzer:BingKey"); - AOAIendpoint= _config.GetValue("BrandAnalyzer:OpenAIEndpoint"); - AOAIsubscriptionKey= _config.GetValue("BrandAnalyzer:OpenAISubscriptionKey"); + Bingendpoint = _config.GetValue("BrandAnalyzer:BingEndpoint"); + BingsubscriptionKey = _config.GetValue("BrandAnalyzer:BingKey"); + AOAIendpoint = _config.GetValue("BrandAnalyzer:OpenAIEndpoint"); + AOAIsubscriptionKey = _config.GetValue("BrandAnalyzer:OpenAISubscriptionKey"); model = new BrandAnalyzerModel(); } @@ -50,31 +34,31 @@ public async Task AnalyzeCompany() model.CompanyName = HttpContext.Request.Form["companyName"]; model.Prompt = HttpContext.Request.Form["prompt"]; - string input_context=""; + string input_context = ""; - if (CheckNullValues(model.CompanyName)) + if (CheckNullValues(model.CompanyName)) { ViewBag.Message = "You must enter a value for Company name"; return View("BrandAnalyzer"); } - - string query_bing = model.CompanyName+" opiniones de usuarios"; - HttpClient client = new HttpClient(); - client.BaseAddress = new Uri(Bingendpoint); - - // Add an Accept header for JSON format. - client.DefaultRequestHeaders.Accept.Add( - new MediaTypeWithQualityHeaderValue("application/json")); - client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", BingsubscriptionKey); - string uri=Bingendpoint+"?q="+query_bing+"&mkt=es-ES&count=100"; - // List data response. - HttpResponseMessage response = client.GetAsync(uri).Result; // Blocking call! Program will wait here until a response is received or a timeout occurs. - response.EnsureSuccessStatusCode(); - string responseBody = await response.Content.ReadAsStringAsync(); + + string query_bing = model.CompanyName + " opiniones de usuarios"; + HttpClient client = new HttpClient(); + client.BaseAddress = new Uri(Bingendpoint); + + // Add an Accept header for JSON format. + client.DefaultRequestHeaders.Accept.Add( + new MediaTypeWithQualityHeaderValue("application/json")); + client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", BingsubscriptionKey); + string uri = Bingendpoint + "?q=" + query_bing + "&mkt=es-ES&count=100"; + // List data response. + HttpResponseMessage response = client.GetAsync(uri).Result; // Blocking call! Program will wait here until a response is received or a timeout occurs. + response.EnsureSuccessStatusCode(); + string responseBody = await response.Content.ReadAsStringAsync(); // Above three lines can be replaced with new helper method below // string responseBody = await client.GetStringAsync(uri); - response.EnsureSuccessStatusCode(); + response.EnsureSuccessStatusCode(); // Parse the response as JSON try @@ -86,22 +70,22 @@ public async Task AnalyzeCompany() // Iterate over the news items and print them foreach (var i in news) { - input_context=input_context+i.name+"\n"+i.snippet+"\n"+i.url+"\n"+"-------"; + input_context = input_context + i.name + "\n" + i.snippet + "\n" + i.url + "\n" + "-------"; } } catch (Exception e) { Console.WriteLine(e.Message); } - - client.Dispose(); - + + client.Dispose(); + try { - - OpenAIClient client_oai = new OpenAIClient( - new Uri(AOAIendpoint), - new AzureKeyCredential(AOAIsubscriptionKey)); + + OpenAIClient client_oai = new OpenAIClient( + new Uri(AOAIendpoint), + new AzureKeyCredential(AOAIsubscriptionKey)); // ### If streaming is not selected Response responseWithoutStream = await client_oai.GetChatCompletionsAsync( @@ -121,9 +105,9 @@ public async Task AnalyzeCompany() }); ChatCompletions completions = responseWithoutStream.Value; - ChatChoice results_analisis= completions.Choices[0]; - ViewBag.Message = - //"Hate severity: " + (response.Value.HateResult?.Severity ?? 0); + ChatChoice results_analisis = completions.Choices[0]; + ViewBag.Message = + //"Hate severity: " + (response.Value.HateResult?.Severity ?? 0); results_analisis.Message.Content ; } @@ -135,7 +119,7 @@ public async Task AnalyzeCompany() return View("BrandAnalyzer", model); } - [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] + [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); @@ -146,7 +130,7 @@ private bool CheckNullValues(string companyName) if (string.IsNullOrEmpty(companyName)) { return true; - } + } return false; } } \ No newline at end of file diff --git a/src/AIHub/Controllers/CallCenterController.cs b/src/AIHub/Controllers/CallCenterController.cs index 5a2c1ff..4257957 100644 --- a/src/AIHub/Controllers/CallCenterController.cs +++ b/src/AIHub/Controllers/CallCenterController.cs @@ -1,19 +1,3 @@ -using System.Diagnostics; -using Microsoft.AspNetCore.Mvc; -using MVCWeb.Models; -using Azure.AI.ContentSafety; -using Azure; -using ContentSafetySampleCode; -using System; -using Azure.Storage.Blobs; -using Azure.Identity; -using Azure.AI.OpenAI; -using System; -using System.Collections.Generic; -using System.Net.Http; -using System.Net.Http.Headers; -using Newtonsoft.Json; - namespace MVCWeb.Controllers; public class CallCenterController : Controller @@ -29,8 +13,8 @@ public class CallCenterController : Controller public CallCenterController(IConfiguration config) { _config = config; - endpoint= _config.GetValue("CallCenter:OpenAIEndpoint"); - subscriptionKey= _config.GetValue("CallCenter:OpenAISubscriptionKey"); + endpoint = _config.GetValue("CallCenter:OpenAIEndpoint"); + subscriptionKey = _config.GetValue("CallCenter:OpenAISubscriptionKey"); model = new CallCenterModel(); } @@ -53,10 +37,10 @@ public async Task AnalyzeCall() } try { - - OpenAIClient client_oai = new OpenAIClient( - new Uri(endpoint), - new AzureKeyCredential(subscriptionKey)); + + OpenAIClient client_oai = new OpenAIClient( + new Uri(endpoint), + new AzureKeyCredential(subscriptionKey)); // ### If streaming is not selected Response responseWithoutStream = await client_oai.GetChatCompletionsAsync( @@ -76,9 +60,9 @@ public async Task AnalyzeCall() }); ChatCompletions completions = responseWithoutStream.Value; - ChatChoice results_analisis= completions.Choices[0]; - System.Console.WriteLine(results_analisis); - ViewBag.Message = + ChatChoice results_analisis = completions.Choices[0]; + System.Console.WriteLine(results_analisis); + ViewBag.Message = results_analisis.Message.Content ; } @@ -105,7 +89,7 @@ private bool CheckNullValues(string companyName, string prompt) if (string.IsNullOrEmpty(prompt)) { return true; - } + } return false; } } \ No newline at end of file diff --git a/src/AIHub/Controllers/ContentSafetyController.cs b/src/AIHub/Controllers/ContentSafetyController.cs index b554f0a..2ec992b 100644 --- a/src/AIHub/Controllers/ContentSafetyController.cs +++ b/src/AIHub/Controllers/ContentSafetyController.cs @@ -1,14 +1,3 @@ -using System.Diagnostics; -using Microsoft.AspNetCore.Mvc; -using MVCWeb.Models; -using Azure.AI.ContentSafety; -using Azure; -using ContentSafetySampleCode; -using System; -using Azure.Storage.Blobs; -using Azure.Storage.Blobs.Models; -using Azure.Identity; - namespace MVCWeb.Controllers; public class ContentSafetyController : Controller @@ -58,8 +47,8 @@ public ContentSafetyController(IConfiguration config, ILogger lo sasUri = containerClient.GenerateSasUri(Azure.Storage.Sas.BlobContainerSasPermissions.Read, DateTimeOffset.UtcNow.AddHours(1)); // Obtiene una lista de blobs en el contenedor blobs = containerClient.GetBlobs(); - model = new ContentSafetyModel(); - + model = new ContentSafetyModel(); + } public IActionResult TextModerator() @@ -115,7 +104,7 @@ public IActionResult EvaluateImage(string imageUrl) "SelfHarm severity: " + (response.Value.SelfHarmResult?.Severity ?? 0) + "\n" + "Sexual severity: " + (response.Value.SexualResult?.Severity ?? 0) + "\n" + "Violence severity: " + (response.Value.ViolenceResult?.Severity ?? 0); - ViewBag.Image=imageUrl + sasUri.Query; + ViewBag.Image = imageUrl + sasUri.Query; } catch (RequestFailedException ex) { @@ -130,7 +119,7 @@ public IActionResult EvaluateImage(string imageUrl) [HttpPost] public IActionResult EvaluateText() { - if(CheckNullValues(HttpContext)) + if (CheckNullValues(HttpContext)) { ViewBag.Message = "You must enter a value for each threshold"; return View("TextModerator", model); @@ -147,7 +136,7 @@ public IActionResult EvaluateText() model.Hate = Convert.ToInt32(HttpContext.Request.Form["hatetext"]); model.Text = HttpContext.Request.Form["text"]; model.Approve = true; - + ContentSafetyClient client = new ContentSafetyClient(new Uri(endpoint), new AzureKeyCredential(subscriptionKey)); var request = new AnalyzeTextOptions(model.Text); diff --git a/src/AIHub/Controllers/FormAnalyzerController.cs b/src/AIHub/Controllers/FormAnalyzerController.cs index d67c318..709e277 100644 --- a/src/AIHub/Controllers/FormAnalyzerController.cs +++ b/src/AIHub/Controllers/FormAnalyzerController.cs @@ -1,25 +1,3 @@ -using System.Diagnostics; -using Microsoft.AspNetCore.Mvc; -using MVCWeb.Models; -using Azure.AI.ContentSafety; -using Azure; -using ContentSafetySampleCode; -using System; -using Azure.Storage.Blobs; -using Azure.Storage.Blobs.Models; -using Azure.Identity; -using Azure.AI.OpenAI; -using System; -using System.Collections.Generic; -using System.Net.Http; -using System.Net.Http.Headers; -using Newtonsoft.Json; -using System.Text; -using System.Text.Json; -using System.Threading.Tasks; -using System.Runtime.InteropServices; - - namespace MVCWeb.Controllers; public class FormAnalyzerController : Controller diff --git a/src/AIHub/Controllers/HomeController.cs b/src/AIHub/Controllers/HomeController.cs index cf42446..a6aa9a4 100644 --- a/src/AIHub/Controllers/HomeController.cs +++ b/src/AIHub/Controllers/HomeController.cs @@ -1,21 +1,11 @@ -using System.Diagnostics; -using Microsoft.AspNetCore.Mvc; -using MVCWeb.Models; -using Azure.AI.ContentSafety; -using Azure; -using ContentSafetySampleCode; -using System; -using Azure.Storage.Blobs; -using Azure.Identity; - -namespace MVCWeb.Controllers; +namespace MVCWeb.Controllers; public class HomeController : Controller { private readonly ILogger _logger; private readonly IConfiguration _config; private readonly ContentSafetyClient _client; - + private string endpoint; private string subscriptionKey; private string storageconnstring; diff --git a/src/AIHub/Controllers/ImageAnalyzerController.cs b/src/AIHub/Controllers/ImageAnalyzerController.cs index a3d3ced..7a80c44 100644 --- a/src/AIHub/Controllers/ImageAnalyzerController.cs +++ b/src/AIHub/Controllers/ImageAnalyzerController.cs @@ -1,25 +1,3 @@ -using System.Diagnostics; -using Microsoft.AspNetCore.Mvc; -using MVCWeb.Models; -using Azure.AI.ContentSafety; -using Azure; -using ContentSafetySampleCode; -using System; -using Azure.Storage.Blobs; -using Azure.Storage.Blobs.Models; -using Azure.Identity; -using Azure.AI.OpenAI; -using System; -using System.Collections.Generic; -using System.Net.Http; -using System.Net.Http.Headers; -using Newtonsoft.Json; -using System.Text; -using System.Text.Json; -using System.Threading.Tasks; -using System.Runtime.InteropServices; - - namespace MVCWeb.Controllers; public class ImageAnalyzerController : Controller @@ -28,7 +6,7 @@ public class ImageAnalyzerController : Controller private readonly IConfiguration _config; private string Visionendpoint; private string OCRendpoint; - private string VisionsubscriptionKey; + private string VisionsubscriptionKey; private string AOAIendpoint; private string AOAIsubscriptionKey; private string storageconnstring; @@ -50,11 +28,11 @@ public class ImageAnalyzerController : Controller public ImageAnalyzerController(IConfiguration config) { _config = config; - Visionendpoint= _config.GetValue("ImageAnalyzer:VisionEndpoint"); - OCRendpoint=_config.GetValue("ImageAnalyzer:OCREndpoint"); - VisionsubscriptionKey= _config.GetValue("ImageAnalyzer:VisionSubscriptionKey"); - AOAIendpoint= _config.GetValue("ImageAnalyzer:OpenAIEndpoint"); - AOAIsubscriptionKey= _config.GetValue("ImageAnalyzer:OpenAISubscriptionKey"); + Visionendpoint = _config.GetValue("ImageAnalyzer:VisionEndpoint"); + OCRendpoint = _config.GetValue("ImageAnalyzer:OCREndpoint"); + VisionsubscriptionKey = _config.GetValue("ImageAnalyzer:VisionSubscriptionKey"); + AOAIendpoint = _config.GetValue("ImageAnalyzer:OpenAIEndpoint"); + AOAIsubscriptionKey = _config.GetValue("ImageAnalyzer:OpenAISubscriptionKey"); storageconnstring = _config.GetValue("Storage:ConnectionString"); BlobServiceClient blobServiceClient = new BlobServiceClient(storageconnstring); containerClient = blobServiceClient.GetBlobContainerClient(_config.GetValue("Storage:ContainerName")); @@ -63,7 +41,7 @@ public ImageAnalyzerController(IConfiguration config) blobs = containerClient.GetBlobs(); model = new ImageAnalyzerModel(); } - + public IActionResult ImageAnalyzer() { return View(); @@ -72,37 +50,37 @@ public IActionResult ImageAnalyzer() [HttpPost] public async Task DenseCaptionImage(string image_url) { - + //1. Get Image model.Image = image_url; - //2. Dense Captioning + //2. Dense Captioning string output_result = ""; - HttpClient client = new HttpClient(); - client.BaseAddress = new Uri(Visionendpoint); + HttpClient client = new HttpClient(); + client.BaseAddress = new Uri(Visionendpoint); - // Add an Accept header for JSON format. - client.DefaultRequestHeaders.Accept.Add( - new MediaTypeWithQualityHeaderValue("application/json")); - client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", VisionsubscriptionKey); + // Add an Accept header for JSON format. + client.DefaultRequestHeaders.Accept.Add( + new MediaTypeWithQualityHeaderValue("application/json")); + client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", VisionsubscriptionKey); - var content = new - { - url = model.Image + sasUri.Query - }; - - var json = System.Text.Json.JsonSerializer.Serialize(content); - - // Crear un HttpContent con el JSON y el tipo de contenido - HttpContent content_body = new StringContent(json, Encoding.UTF8, "application/json"); - // List data response. - HttpResponseMessage response = await client.PostAsync(Visionendpoint, content_body); // Blocking call! Program will wait here until a response is received or a timeout occurs. - response.EnsureSuccessStatusCode(); - string responseBody = await response.Content.ReadAsStringAsync(); + var content = new + { + url = model.Image + sasUri.Query + }; + + var json = System.Text.Json.JsonSerializer.Serialize(content); + + // Crear un HttpContent con el JSON y el tipo de contenido + HttpContent content_body = new StringContent(json, Encoding.UTF8, "application/json"); + // List data response. + HttpResponseMessage response = await client.PostAsync(Visionendpoint, content_body); // Blocking call! Program will wait here until a response is received or a timeout occurs. + response.EnsureSuccessStatusCode(); + string responseBody = await response.Content.ReadAsStringAsync(); // Above three lines can be replaced with new helper method below // string responseBody = await client.GetStringAsync(uri); - response.EnsureSuccessStatusCode(); + response.EnsureSuccessStatusCode(); // Parse the response as JSON try @@ -114,45 +92,45 @@ public async Task DenseCaptionImage(string image_url) // Iterate over the news items and print them foreach (var i in dense_descriptions) { - output_result=output_result+i.text; + output_result = output_result + i.text; }; } catch (Exception e) { Console.WriteLine(e.Message); } - - client.Dispose(); - - + + client.Dispose(); + + //3. OCR string output_result_2 = ""; - HttpClient client2 = new HttpClient(); - client2.BaseAddress = new Uri(OCRendpoint); + HttpClient client2 = new HttpClient(); + client2.BaseAddress = new Uri(OCRendpoint); - // Add an Accept header for JSON format. - client2.DefaultRequestHeaders.Accept.Add( - new MediaTypeWithQualityHeaderValue("application/json")); - client2.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", VisionsubscriptionKey); + // Add an Accept header for JSON format. + client2.DefaultRequestHeaders.Accept.Add( + new MediaTypeWithQualityHeaderValue("application/json")); + client2.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", VisionsubscriptionKey); - var content2 = new - { - url = model.Image + sasUri.Query - }; - - var json2 = System.Text.Json.JsonSerializer.Serialize(content2); - - // Crear un HttpContent con el JSON y el tipo de contenido - HttpContent content_body2 = new StringContent(json2, Encoding.UTF8, "application/json"); - // List data response. - HttpResponseMessage response2 = await client2.PostAsync(OCRendpoint, content_body2); // Blocking call! Program will wait here until a response is received or a timeout occurs. - response2.EnsureSuccessStatusCode(); - string responseBody2 = await response2.Content.ReadAsStringAsync(); + var content2 = new + { + url = model.Image + sasUri.Query + }; + + var json2 = System.Text.Json.JsonSerializer.Serialize(content2); + + // Crear un HttpContent con el JSON y el tipo de contenido + HttpContent content_body2 = new StringContent(json2, Encoding.UTF8, "application/json"); + // List data response. + HttpResponseMessage response2 = await client2.PostAsync(OCRendpoint, content_body2); // Blocking call! Program will wait here until a response is received or a timeout occurs. + response2.EnsureSuccessStatusCode(); + string responseBody2 = await response2.Content.ReadAsStringAsync(); // Above three lines can be replaced with new helper method below // string responseBody = await client.GetStringAsync(uri); - response2.EnsureSuccessStatusCode(); + response2.EnsureSuccessStatusCode(); // Parse the response as JSON try @@ -161,8 +139,8 @@ public async Task DenseCaptionImage(string image_url) Console.WriteLine(responsejson2.ToString()); // Get the web pages from the response var ocr = responsejson2.readResult.content; - if (ocr!="")output_result_2=ocr; - else output_result_2="there is no text in the image"; + if (ocr != "") output_result_2 = ocr; + else output_result_2 = "there is no text in the image"; // Iterate over the news items and print them } @@ -170,8 +148,8 @@ public async Task DenseCaptionImage(string image_url) { Console.WriteLine(e.Message); } - - client.Dispose(); + + client.Dispose(); //4. Tags @@ -185,10 +163,10 @@ public async Task DenseCaptionImage(string image_url) //7. Describe Image GPT4 try { - - OpenAIClient client_oai = new OpenAIClient( - new Uri(AOAIendpoint), - new AzureKeyCredential(AOAIsubscriptionKey)); + + OpenAIClient client_oai = new OpenAIClient( + new Uri(AOAIendpoint), + new AzureKeyCredential(AOAIsubscriptionKey)); // ### If streaming is not selected Response responseWithoutStream = await client_oai.GetChatCompletionsAsync( @@ -208,48 +186,48 @@ public async Task DenseCaptionImage(string image_url) }); ChatCompletions completions = responseWithoutStream.Value; - ChatChoice results_analisis= completions.Choices[0]; - ViewBag.Message = - //"Hate severity: " + (response.Value.HateResult?.Severity ?? 0); + ChatChoice results_analisis = completions.Choices[0]; + ViewBag.Message = + //"Hate severity: " + (response.Value.HateResult?.Severity ?? 0); results_analisis.Message.Content ; - ViewBag.Image=model.Image + sasUri.Query; + ViewBag.Image = model.Image + sasUri.Query; Console.WriteLine(ViewBag.Message); Console.WriteLine(ViewBag.Image); - /* result_image_front=image; - Console.WriteLine("1) "+result_image_front); - Console.WriteLine("2) "+result_message_front); - /* ViewBag.Message = - results_analisis.Message.Content - ; */ - //ViewBag.Image=result_image_front+".jpg"; + /* result_image_front=image; + Console.WriteLine("1) "+result_image_front); + Console.WriteLine("2) "+result_message_front); + /* ViewBag.Message = + results_analisis.Message.Content + ; */ + //ViewBag.Image=result_image_front+".jpg"; } catch (RequestFailedException ex) { throw; } - + // var result = await _service.GetBuildingHomeAsync(); // return Ok(result); return View("ImageAnalyzer", model); } - //Upload a file to my azure storage account + //Upload a file to my azure storage account [HttpPost] public async Task UploadFile(IFormFile imageFile) { //Check no image - if (CheckNullValues(imageFile)) + if (CheckNullValues(imageFile)) { ViewBag.Message = "You must upload an image"; return View("ImageAnalyzer"); } //Upload file to azure storage account - string url= imageFile.FileName.ToString(); + string url = imageFile.FileName.ToString(); Console.WriteLine(url); //url= url.Replace(" ", "")+Stopwatch.GetTimestamp(); @@ -258,7 +236,7 @@ public async Task UploadFile(IFormFile imageFile) //Get the url of the file Uri blobUrl = blobClient.Uri; - + if (CheckImageExtension(blobUrl.ToString())) { ViewBag.Message = "You must upload an image with .jpg, .jpeg or .png extension"; @@ -268,34 +246,34 @@ public async Task UploadFile(IFormFile imageFile) //Call EvaluateImage with the url await DenseCaptionImage(blobUrl.ToString()); - ViewBag.Waiting=null; + ViewBag.Waiting = null; return View("ImageAnalyzer"); } - [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] + [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } - private bool CheckNullValues(IFormFile imageFile) + private bool CheckNullValues(IFormFile imageFile) { - if (imageFile==null) + if (imageFile == null) { return true; - } + } return false; } - private bool CheckImageExtension(string blobUri) + private bool CheckImageExtension(string blobUri) { - string jpg= ".jpg"; - string jpeg=".jpeg"; - string png= ".png"; - string uri_lower= blobUri; + string jpg = ".jpg"; + string jpeg = ".jpeg"; + string png = ".png"; + string uri_lower = blobUri; if (uri_lower.Contains(jpg, StringComparison.OrdinalIgnoreCase)) { return false; @@ -303,11 +281,11 @@ private bool CheckImageExtension(string blobUri) if (uri_lower.Contains(jpeg, StringComparison.OrdinalIgnoreCase)) { return false; - } + } if (uri_lower.Contains(png, StringComparison.OrdinalIgnoreCase)) { return false; - } + } return true; } } \ No newline at end of file diff --git a/src/AIHub/Dockerfile b/src/AIHub/Dockerfile new file mode 100644 index 0000000..5f4d4cd --- /dev/null +++ b/src/AIHub/Dockerfile @@ -0,0 +1,15 @@ +FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build +WORKDIR /src + +COPY ./AIHub.csproj ./AIHub.csproj +RUN dotnet restore ./AIHub.csproj + +# Copy everything else and build website +COPY ./ ./app/ +WORKDIR /src/app/ +RUN dotnet publish -c release + +# Final stage / image +FROM mcr.microsoft.com/dotnet/aspnet:8.0 +COPY --from=build /src/app/bin/Release/net8.0/publish ./ +ENTRYPOINT ["dotnet", "AIHub.dll"] \ No newline at end of file diff --git a/src/AIHub/GlobalUsings.cs b/src/AIHub/GlobalUsings.cs new file mode 100644 index 0000000..4951a6e --- /dev/null +++ b/src/AIHub/GlobalUsings.cs @@ -0,0 +1,13 @@ +global using System.Diagnostics; +global using Microsoft.AspNetCore.Mvc; +global using MVCWeb.Models; +global using Azure.AI.ContentSafety; +global using Azure; +global using Azure.Storage.Blobs; +global using Azure.Storage.Blobs.Models; +global using Azure.AI.OpenAI; +global using System.Net.Http.Headers; +global using Newtonsoft.Json; +global using System.Text; +global using System.Text.Json; +global using System.Text.Json.Serialization; diff --git a/src/AIHub/Models/BrandAnalyzerModel.cs b/src/AIHub/Models/BrandAnalyzerModel.cs index c32c633..6c911a7 100644 --- a/src/AIHub/Models/BrandAnalyzerModel.cs +++ b/src/AIHub/Models/BrandAnalyzerModel.cs @@ -1,7 +1,8 @@ namespace MVCWeb.Models; -public class BrandAnalyzerModel{ - +public class BrandAnalyzerModel +{ + public int? Severity { get; set; } public int? Violence { get; set; } public int? SelfHarm { get; set; } diff --git a/src/AIHub/Models/CallCenterModel.cs b/src/AIHub/Models/CallCenterModel.cs index 3ea3cc6..0e17725 100644 --- a/src/AIHub/Models/CallCenterModel.cs +++ b/src/AIHub/Models/CallCenterModel.cs @@ -1,7 +1,8 @@ namespace MVCWeb.Models; -public class CallCenterModel{ - +public class CallCenterModel +{ + public int? Severity { get; set; } public int? Violence { get; set; } public int? SelfHarm { get; set; } diff --git a/src/AIHub/Models/ContentSafetyModel.cs b/src/AIHub/Models/ContentSafetyModel.cs index e3150b2..ffca137 100644 --- a/src/AIHub/Models/ContentSafetyModel.cs +++ b/src/AIHub/Models/ContentSafetyModel.cs @@ -1,7 +1,8 @@ namespace MVCWeb.Models; -public class ContentSafetyModel{ - +public class ContentSafetyModel +{ + public ContentSafetyModel() { Severity = 1; // Default value diff --git a/src/AIHub/Models/FormAnalyzer.cs b/src/AIHub/Models/FormAnalyzer.cs index 6b13004..2cd326b 100644 --- a/src/AIHub/Models/FormAnalyzer.cs +++ b/src/AIHub/Models/FormAnalyzer.cs @@ -1,7 +1,8 @@ namespace MVCWeb.Models; -public class FormAnalyzerModel{ - +public class FormAnalyzerModel +{ + public int? Severity { get; set; } public int? Violence { get; set; } public int? SelfHarm { get; set; } diff --git a/src/AIHub/Models/ImageAnalyzerModel.cs b/src/AIHub/Models/ImageAnalyzerModel.cs index 2d51376..af4bb8d 100644 --- a/src/AIHub/Models/ImageAnalyzerModel.cs +++ b/src/AIHub/Models/ImageAnalyzerModel.cs @@ -1,7 +1,8 @@ namespace MVCWeb.Models; -public class ImageAnalyzerModel{ - +public class ImageAnalyzerModel +{ + public int? Severity { get; set; } public int? Violence { get; set; } public int? SelfHarm { get; set; } diff --git a/src/AIHub/SampleCode.cs b/src/AIHub/SampleCode.cs index e6a6eb9..140ce84 100644 --- a/src/AIHub/SampleCode.cs +++ b/src/AIHub/SampleCode.cs @@ -2,7 +2,6 @@ // Copyright (c) Microsoft. All rights reserved. // To learn more, please visit the documentation - Quickstart: Azure Content Safety: https://aka.ms/acsstudiodoc // - using System.Text; using System.Text.Json; using System.Text.Json.Serialization; @@ -162,7 +161,7 @@ public class DetectionResult /// public class ImageDetectionResult : DetectionResult { - + } /// @@ -272,8 +271,11 @@ public class ContentSafety /// The JSON serializer options. /// public static readonly JsonSerializerOptions options = - new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, - Converters = { new JsonStringEnumConverter() } }; + new JsonSerializerOptions + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + Converters = { new JsonStringEnumConverter() } + }; /// /// Initializes a new instance of the class. @@ -295,12 +297,12 @@ public string BuildUrl(MediaType mediaType) { switch (mediaType) { - case MediaType.Text: - return $"{Endpoint}/contentsafety/text:analyze?api-version={API_VERSION}"; - case MediaType.Image: - return $"{Endpoint}/contentsafety/image:analyze?api-version={API_VERSION}"; - default: - throw new ArgumentException($"Invalid Media Type {mediaType}"); + case MediaType.Text: + return $"{Endpoint}/contentsafety/text:analyze?api-version={API_VERSION}"; + case MediaType.Image: + return $"{Endpoint}/contentsafety/image:analyze?api-version={API_VERSION}"; + default: + throw new ArgumentException($"Invalid Media Type {mediaType}"); } } @@ -315,12 +317,12 @@ public DetectionRequest BuildRequestBody(MediaType mediaType, string content, st { switch (mediaType) { - case MediaType.Text: - return new TextDetectionRequest(content, blocklists); - case MediaType.Image: - return new ImageDetectionRequest(content); - default: - throw new ArgumentException($"Invalid Media Type {mediaType}"); + case MediaType.Text: + return new TextDetectionRequest(content, blocklists); + case MediaType.Image: + return new ImageDetectionRequest(content); + default: + throw new ArgumentException($"Invalid Media Type {mediaType}"); } } @@ -334,12 +336,12 @@ public DetectionRequest BuildRequestBody(MediaType mediaType, string content, st { switch (mediaType) { - case MediaType.Text: - return JsonSerializer.Deserialize(json, options); - case MediaType.Image: - return JsonSerializer.Deserialize(json, options); - default: - throw new ArgumentException($"Invalid Media Type {mediaType}"); + case MediaType.Text: + return System.Text.Json.JsonSerializer.Deserialize(json, options); + case MediaType.Image: + return System.Text.Json.JsonSerializer.Deserialize(json, options); + default: + throw new ArgumentException($"Invalid Media Type {mediaType}"); } } @@ -354,7 +356,7 @@ public async Task Detect(MediaType mediaType, string content, s { string url = BuildUrl(mediaType); DetectionRequest requestBody = BuildRequestBody(mediaType, content, blocklists); - string payload = JsonSerializer.Serialize(requestBody, requestBody.GetType(), options); + string payload = System.Text.Json.JsonSerializer.Serialize(requestBody, requestBody.GetType(), options); var msg = new HttpRequestMessage(HttpMethod.Post, url); msg.Content = new StringContent(payload, Encoding.UTF8, "application/json"); @@ -372,8 +374,7 @@ public async Task Detect(MediaType mediaType, string content, s if (!response.IsSuccessStatusCode) { - DetectionErrorResponse? error = - JsonSerializer.Deserialize(responseText, options); + DetectionErrorResponse? error = System.Text.Json.JsonSerializer.Deserialize(responseText, options); if (error == null || error.error == null || error.error.code == null || error.error.message == null) { throw new DetectionException(response.StatusCode.ToString(), @@ -489,8 +490,8 @@ static async Task Main(string[] args) // Set the media type and blocklists MediaType mediaType = MediaType.Image; - string[] blocklists = {}; - + string[] blocklists = { }; + // Set the content to be tested string content = ""; diff --git a/src/AIHub/Views/BrandAnalyzer/BrandAnalyzer.cshtml b/src/AIHub/Views/BrandAnalyzer/BrandAnalyzer.cshtml index e90e3bb..ca7c42b 100644 --- a/src/AIHub/Views/BrandAnalyzer/BrandAnalyzer.cshtml +++ b/src/AIHub/Views/BrandAnalyzer/BrandAnalyzer.cshtml @@ -36,7 +36,7 @@ - + \ No newline at end of file diff --git a/src/AIHub/Views/CallCenter/CallCenter.cshtml b/src/AIHub/Views/CallCenter/CallCenter.cshtml index 9203913..d2fc42f 100644 --- a/src/AIHub/Views/CallCenter/CallCenter.cshtml +++ b/src/AIHub/Views/CallCenter/CallCenter.cshtml @@ -51,7 +51,7 @@ style="width: 100%; resize: none; overflow: auto; height: 100px;">Hola, acabo de tenir un accident de cotxe i volia denunciar-ho. D'acord, espero que estiguis bé, què ha passat? Conduïa per la I-18 i vaig xocar amb un altre cotxe. Estàs bé? Sí, només estic una mica alterat. Això és comprensible. Em pots donar el teu nom complet? Per descomptat, és Sarah Standl. Saps què va provocar l'accident? Crec que podria haver topat amb un sot. D'acord, on va tenir lloc l'accident? A l'autopista I-18. Algú més va resultar ferit? No ho crec. Però no n'estic segur. Bé, haurem de fer una investigació. Em pots donar la informació dels altres conductors? Per descomptat, es diu John Radley. I el teu número d'assegurança. D'ACORD. Dona'm un minut. D'acord, és 546452. D'acord, quin tipus de desperfectes té el cotxe? Els fars estan trencats i els airbags s'han apagat. Seràs capaç de conduir-lo? No ho sé. L'hauré de remolcar. Bé, haurem d'inspeccionar-lo. Seguiré endavant i començaré la reclamació i ho solucionarem tot. Gràcies. -
+
@@ -72,7 +72,7 @@
- +
diff --git a/src/AIHub/Views/ContentSafety/TextModerator.cshtml b/src/AIHub/Views/ContentSafety/TextModerator.cshtml index 81ff4b9..68e87eb 100644 --- a/src/AIHub/Views/ContentSafety/TextModerator.cshtml +++ b/src/AIHub/Views/ContentSafety/TextModerator.cshtml @@ -3,9 +3,14 @@ }
- + + +

Text Moderator

-

Moderate text by adding the thresholds for different flags, with threshold levels from 1 to 6, being 6 the most restricted content filter.

+

Moderate text by adding the thresholds for different flags, with threshold levels from 1 + to 6, being 6 the most restricted content filter.

Learn about Detect Harmful materials.

@@ -22,30 +27,31 @@ }
- +
+ value="@(Model?.Severity ?? 1)" style="width: 10%;" /> + value="@(Model?.Violence ?? 1)" style="width: 10%;" /> - + - -
+ + -
- +
+
- +
diff --git a/src/AIHub/Views/FormAnalyzer/FormAnalyzer.cshtml b/src/AIHub/Views/FormAnalyzer/FormAnalyzer.cshtml index 7fe175b..5a36286 100644 --- a/src/AIHub/Views/FormAnalyzer/FormAnalyzer.cshtml +++ b/src/AIHub/Views/FormAnalyzer/FormAnalyzer.cshtml @@ -23,12 +23,12 @@
-
-
- } +} @*
diff --git a/src/AIHub/Views/Home/Index.cshtml b/src/AIHub/Views/Home/Index.cshtml index c728329..b05a692 100644 --- a/src/AIHub/Views/Home/Index.cshtml +++ b/src/AIHub/Views/Home/Index.cshtml @@ -4,54 +4,74 @@ }
-

Alma Bank Demo Suite

-

Hello! Welcome to Alma Bank Demo Suite, please choose a demo...

+

Alma Bank Demo Suite

+

Hello! Welcome to Alma Bank Demo Suite, please choose a demo...

@@ -59,21 +79,30 @@
  • -
  • -
    - -

    Content Safety

    -

    Image Moderator: Moderate images by adding the thresholds for different flags

    -
    +
    + + + +

    Content Safety

    +

    Image Moderator: Moderate images by adding the thresholds for different + flags

    +
  • - diff --git a/src/AIHub/Views/Home/Privacy.cshtml b/src/AIHub/Views/Home/Privacy.cshtml index 214fee2..4a7ad50 100644 --- a/src/AIHub/Views/Home/Privacy.cshtml +++ b/src/AIHub/Views/Home/Privacy.cshtml @@ -3,4 +3,5 @@ }

    @ViewData["Title"]

    -

    For any comments about the site, please contact the authors: Roberto Arocha, Hector Blasco, Monica Calleja, Ane Iturzaeta

    +

    For any comments about the site, please contact the authors: Roberto Arocha, Hector Blasco, Monica Calleja, Ane + Iturzaeta

    diff --git a/src/AIHub/Views/Shared/Error.cshtml b/src/AIHub/Views/Shared/Error.cshtml index a1e0478..6876388 100644 --- a/src/AIHub/Views/Shared/Error.cshtml +++ b/src/AIHub/Views/Shared/Error.cshtml @@ -15,11 +15,13 @@

    Development Mode

    - Swapping to Development environment will display more detailed information about the error that occurred. + Swapping to Development environment will display more detailed information about the error that + occurred.

    The Development environment shouldn't be enabled for deployed applications. It can result in displaying sensitive information from exceptions to end users. - For local debugging, enable the Development environment by setting the ASPNETCORE_ENVIRONMENT environment variable to Development + For local debugging, enable the Development environment by setting the + ASPNETCORE_ENVIRONMENT environment variable to Development and restarting the app.