Merge branch 'Datenbank'

This commit is contained in:
Simon Lübeß
2023-10-10 20:20:02 +02:00
26 changed files with 506 additions and 128 deletions

View File

@ -0,0 +1,12 @@
{
"version": 1,
"isRoot": true,
"tools": {
"dotnet-ef": {
"version": "7.0.9",
"commands": [
"dotnet-ef"
]
}
}
}

View File

@ -20,4 +20,8 @@
<PackageReference Include="SixLabors.ImageSharp" Version="3.0.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DataAccess\DataAccess.csproj" />
</ItemGroup>
</Project>

View File

@ -4,11 +4,16 @@
@using OpenAI_API.Chat
@using OpenAI_API.Models
@using System.Diagnostics
@using DataAccess.Data
@using DataAccess.Models
@inject IConfiguration Config
@inject TooltipService TooltipService
@inject DialogService DialogService
@inject BildInfoData BildInfoData;
@inject WunschInfoData WunschInfoData;
<PageTitle>AiArt</PageTitle>
<section class="about_section layout_padding" style="background-image: url('images/5KeineAngstvorFehlern2014.jpeg'); background-size: cover; background-repeat: no-repeat; background-blend-mode:lighten">
@ -244,7 +249,7 @@
private string _inferenceApiKey = "";
private string _openAiApiKey = "";
protected override Task OnInitializedAsync()
protected override async Task OnInitializedAsync()
{
_inferenceApiKey = Config.GetValue<string>("API:HF_Inference");
_openAiApiKey = Config.GetValue<string>("API:OpenAI");
@ -258,74 +263,37 @@
_client.DefaultRequestHeaders.Clear();
_client.DefaultRequestHeaders.Add("Authorization", $"Bearer {_inferenceApiKey}");
return base.OnInitializedAsync();
// BildInfoModel bildInfo = new()
// {
// BildBeschreibung = "Test",
// BildPrompt = "Tost",
// Dateiname = "Task",
// Datum = DateTime.Now,
// GPTModel = "Geht dich nichts an",
// ImageModel = "Jup",
// Wunsch = request
// };
// try
// {
// //await BildInfoData.AddBildInfo(bildInfo);
// }
// catch (Exception e)
// {
// Console.WriteLine(e);
// throw;
// }
await base.OnInitializedAsync();
}
/// <summary>
/// Geneiert das Bild für den aktuellen <see cref="_imagePrompt"/>
/// </summary>
public async Task GenerateImageAsync()
{
var postData = new
{
inputs = _imagePrompt
};
JsonContent content = JsonContent.Create(postData);
async Task FailedToDrawImage()
{
bool? retry = await DialogService.Confirm("Leider konnte das Bild nicht gemalt werden. Möchtest du es noch eimal versuchen?", "Ups, ein Fehler ist aufgetreten...",
new ConfirmOptions { OkButtonText = "Ja", CancelButtonText = "Nein" });
if (retry == true)
await GenerateImageAsync();
}
try
{
var inferenceModelUrl = "https://api-inference.huggingface.co/models/Nacken/kkkk-sdxl-5000";
var response = await _client.PostAsync(inferenceModelUrl, content);
if (response?.IsSuccessStatusCode == true)
{
await using Stream imageStream = await response.Content.ReadAsStreamAsync();
using Image image = await Image.LoadAsync(imageStream);
string imgUrl = $"generated_images/{DateTime.Now:dd_MM_yyyy_hh_mm_s}.jpg";
string mapPath = $"./wwwroot/{imgUrl}";
await image.SaveAsJpegAsync(mapPath);
_imageUrl = imgUrl;
}
else
{
Console.WriteLine($"Image conversion failed: {response}");
if (Debugger.IsAttached)
Debugger.Break();
await FailedToDrawImage();
}
}
catch (Exception exception)
{
Console.WriteLine($"Image request failed: {exception}");
if (Debugger.IsAttached)
Debugger.Break();
await FailedToDrawImage();
}
}
/// <summary>
/// Geneiert das Bild für den aktuellen <see cref="_imagePrompt"/>
/// </summary>
public async Task<string?> GenerateImageAsync(string prompt, bool isRetry = false)
public async Task<string?> GenerateImageAsync(string prompt, WunschInfoModel wunschInfo, bool isRetry = false)
{
var postData = new
{
@ -354,7 +322,7 @@
if (retry == true)
{
return await GenerateImageAsync(prompt, true);
return await GenerateImageAsync(prompt, wunschInfo, true);
}
return null;
@ -362,7 +330,9 @@
try
{
var inferenceModelUrl = "https://api-inference.huggingface.co/models/Nacken/kkkk-sdxl-5000";
const string modelName = "Nacken/kkkk-sdxl-5000";
var inferenceModelUrl = $"https://api-inference.huggingface.co/models/{modelName}";
var response = await _client.PostAsync(inferenceModelUrl, content);
@ -372,16 +342,25 @@
using Image image = await Image.LoadAsync(imageStream);
string imgUrl = $"generated_images/{DateTime.Now:dd_MM_yyyy_hh_mm_s_fffffff}.jpg";
DateTime imageDate = DateTime.Now;
BildInfoModel bildInfo = new()
{
Dateiname = "PlaceHolder",
Datum = imageDate,
ImageModel = modelName,
WunschId = wunschInfo.Id
};
await BildInfoData.AddBildInfoAsync(bildInfo);
string imgUrl = $"generated_images/Image_{bildInfo.Id}.jpg";
string mapPath = $"./wwwroot/{imgUrl}";
await image.SaveAsJpegAsync(mapPath);
// Hier speichern wir die Daten in die 'info_texts.txt'-Datei
string infoTextsPath = Path.Combine(_environment.WebRootPath, "generated_images", "info_texts.txt");
string desc = _imageDescription.Replace("\r\n", "").Replace("\n", "").Replace("\r", "");
string newLine = $"{imgUrl}: {request}, {desc}\n";
await File.AppendAllTextAsync(infoTextsPath, newLine);
bildInfo.Dateiname = imgUrl;
await BildInfoData.UpdateBildInfoDateinameAsync(bildInfo);
return imgUrl;
}
@ -463,11 +442,23 @@
_imageDescription = await converse.GetResponseFromChatbotAsync();
await UpdateBusyMessage("Kirstens Assistent hat eine Idee! Er wird sie nun malen...");
WunschInfoModel wunschInfo = new()
{
BildBeschreibung = _imageDescription,
BildPrompt = _imagePrompt,
Datum = DateTime.Now,
GPTModel = converse.Model,
Wunsch = request
};
// TODO: Try
await WunschInfoData.AddWunschInfoAsync(wunschInfo);
// Vier Bilder generieren
for (int i = 0; i < 4; i++)
{
_imageUrls[i] = await GenerateImageAsync(_imagePrompt);
_imageUrls[i] = await GenerateImageAsync(_imagePrompt, wunschInfo);
_imageStates[i] = ImageState.FadeIn;
await InvokeAsync(StateHasChanged);
}

View File

@ -1,5 +1,11 @@
@page "/gallery"
@using DataAccess.Data
@using DataAccess.Models
@inject BildInfoData BildInfoData;
@inject WunschInfoData WunschInfoData;
<style>
.image-grid {
background-color: white; /* Hintergrund der RadzenDataList weiß machen */
@ -57,12 +63,12 @@
</style>
<div>
<RadzenDataList WrapItems="@true" AllowPaging="true" Data="@imagePaths" PageSize="20" PagerHorizontalAlign="HorizontalAlign.Left" ShowPagingSummary="true" class="image-grid">
<Template Context="imagePath">
<RadzenDataList WrapItems="@true" AllowPaging="true" Data="@_bildInfos" PageSize="20" PagerHorizontalAlign="HorizontalAlign.Left" ShowPagingSummary="true" class="image-grid">
<Template Context="bildInfo">
<div class="image-grid-item">
<RadzenCard Style="width: 200px; height: 200px; padding: 0; border: none;">
<RadzenButton Click="@(args => ShowImageInfo(imagePath))">
<RadzenImage Src="@imagePath" Style="width: 100%; height: 100%; object-fit: cover;" />
<RadzenButton Click="@(args => ShowImageInfo(bildInfo))">
<RadzenImage Src="@bildInfo.Dateiname" Style="width: 100%; height: 100%; object-fit: cover;" />
</RadzenButton>
</RadzenCard>
</div>
@ -83,63 +89,26 @@
</div>
@code {
List<string> imagePaths = new List<string>();
string selectedImage;
string infoText = "Info Text";
string popupStyle = "display: none;";
IEnumerable<BildInfoModel>? _bildInfos;
protected override async Task OnInitializedAsync()
{
await base.OnInitializedAsync();
// Get the physical path to the folder
string folderPath = Path.Combine(_environment.WebRootPath, "generated_images");
if (Directory.Exists(folderPath))
{
// Load the image file names from the folder
var imageFiles = Directory.GetFiles(folderPath, "*.jpg");
// Get the relative paths to the images
imagePaths = imageFiles.Select(file => file.Replace(_environment.WebRootPath, "").Replace("\\", "/")).ToList();
}
_bildInfos = await BildInfoData.GetAllBildInfosAsync();
}
private async void ShowImageInfo(string imagePath)
private async void ShowImageInfo(BildInfoModel bildInfo)
{
selectedImage = imagePath;
selectedImage = bildInfo.Dateiname;
popupStyle = "display: block;";
infoText = await GetInfoTextForImageAsync(imagePath);
}
private async Task<string> GetInfoTextForImageAsync(string imagePath)
{
// Bestimme den Ordnerpfad, in dem sich die Bilder und die info_texts.txt Datei befinden
string folderPath = Path.Combine(_environment.WebRootPath, "generated_images");
// Bestimme den Pfad zur info_texts.txt Datei
string infoTextsFilePath = Path.Combine(folderPath, "info_texts.txt");
// Überprüfe, ob die Datei existiert
if (!File.Exists(infoTextsFilePath))
return $"Kein Infotext für {imagePath} gefunden.";
// Lies alle Zeilen der Datei
var lines = await File.ReadAllLinesAsync(infoTextsFilePath);
string adaptedImagePath = imagePath.Substring(1) + ":";
// Durchsuche jede Zeile nach dem gegebenen imagePath
foreach (var line in lines)
{
if (line.StartsWith(adaptedImagePath)) // Überprüft, ob die Zeile mit dem Dateinamen des Bildes beginnt
{
// Trenne den Dateinamen und den Infotext und gib den Infotext zurück
return line.Split(new[] { ':' }, 2).LastOrDefault()?.Trim();
}
}
return $"Kein Infotext für {imagePath} gefunden.";
WunschInfoModel wunschInfo = await WunschInfoData.GetWunschInfoAsync(bildInfo.WunschId);
infoText = wunschInfo.BildBeschreibung;
}
private void CloseImageInfo()

View File

@ -1,3 +1,5 @@
using DataAccess.Data;
using DataAccess.DbAccess;
using Radzen;
var builder = WebApplication.CreateBuilder(args);
@ -8,6 +10,9 @@ builder.Services.AddServerSideBlazor();
builder.Services.AddScoped<TooltipService>();
builder.Services.AddScoped<DialogService>();
builder.Services.AddScoped<NotificationService>();
builder.Services.AddSingleton<ISqlDataAccess, SqlDataAccess>();
builder.Services.AddSingleton<BildInfoData>();
builder.Services.AddSingleton<WunschInfoData>();
var app = builder.Build();

View File

@ -36,7 +36,7 @@
<span class="nav-link">Über Kirsten Klöckner</span>
</NavLink>
<NavLink class="nav-item" href="gallery" Match="NavLinkMatch.All">
<span class="nav-link">Galerier</span>
<span class="nav-link">Galerie</span>
</NavLink>
</ul>
</div>

View File

@ -1,9 +1,12 @@
{
"DetailedErrors": true,
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
"DetailedErrors": true,
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"ConnectionStrings": {
"Default": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=KiKunstDatenbank;Integrated Security=True;Connect Timeout=60;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
}
}
}

View File

@ -9,5 +9,8 @@
"API": {
"OpenAI": "<put OpenAI Key here>",
"HF_Inference": "<put Hugging Face inference API Key here>"
},
"ConnectionStrings": {
"Default": "<put Connection String here>"
}
}