SeemGen/Components/Pages/Home.razorOLD

382 lines
12 KiB
Plaintext

@page "/home_old"
@using BLAIzor.Models
@using BLAIzor.Services
@using Google.Cloud.Speech.V1
@using Microsoft.AspNetCore.Identity.UI.Services
@inject AIService ChatGptService
@rendermode InteractiveServer
@inject IJSRuntime jsRuntime;
@inject IConfiguration configuration
@inject ContentService _contentService
@inject ScopedContentService _scopedContentService
@inject IEmailSender _emailService
@inject NavigationManager _navigationManager
<PageTitle>Home</PageTitle>
@* <label for="search_bar">Search</label> *@
@{
if(isEmailFormVisible)
{
<div class="contactform-overlay">
<div class="contactform-close-overlay">
</div>
<div class="contactform-popup-content">
<h1>Contact us!</h1>
<EditForm Model="@ContactFormModel" OnValidSubmit="HandleValidSubmit">
<DataAnnotationsValidator />
<ValidationSummary />
<div class="mb-3">
<label for="name" class="form-label">Your Name</label>
<InputText id="name" class="form-control" @bind-Value="ContactFormModel.Name" placeholder="Enter your name" />
<ValidationMessage For="@(() => ContactFormModel.Name)" />
</div>
<div class="mb-3">
<label for="email" class="form-label">Your Email</label>
<InputText id="email" class="form-control" @bind-Value="ContactFormModel.Email" placeholder="Enter your email" />
<ValidationMessage For="@(() => ContactFormModel.Email)" />
</div>
<div class="mb-3">
<label for="message" class="form-label">Your Message</label>
<InputTextArea id="message" class="form-control" @bind-Value="ContactFormModel.Message" placeholder="Enter your message" rows="5" />
<ValidationMessage For="@(() => ContactFormModel.Message)" />
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</EditForm>
<button @onclick="CancelEmail" class="btn btn-primary">Cancel</button>
</div>
<div class="contactform-popup-close"></div>
</div>
}
}
<div class="searchBox">
<input @oninput="(e) => UserInput = e.Value.ToString()"
@onkeydown="@Enter" class="searchInput" type="text" name="" value="@UserInput" placeholder="Ask any question">
<button class="searchButton border-0" @onclick="ProcessWordFile" href="#">
<i class="fa-solid fa-magnifying-glass"></i>
</button>
</div>
@* <input @oninput="(e) => UserInput = e.Value.ToString()"
@onkeydown="@Enter"
class="search_bar"
name="search_bar"
type="text"
placeholder="Ask me something"
value="@UserInput" /> *@
<button id="recButton" class="btn btn-primary voicebutton" onclick="startRecording()"><i class="fa-solid fa-microphone"></i></button>
<button id="stopButton" class="btn btn-primary voicebutton" onclick="stopRecording()" hidden><i class="fa-solid fa-microphone-slash"></i></button>
<p id="recordingText"></p>
@{
if (!string.IsNullOrEmpty(HtmlContent))
{
<div class="pt-5"> @((MarkupString)HtmlContent)</div>
}
else
{
<div class="text-center row" style="height: 70vh;">
<p>Working...</p>
<div class="mydiv"></div>
<div class="mydiv"></div>
<div class="mydiv"></div>
<div class="mydiv"></div>
<div class="mydiv"></div>
@*<svg class="position-absolute top-50 start-50 translate-middle" version="1.1" id="L3" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 100 100" enable-background="new 0 0 0 0" xml:space="preserve">
<circle fill="none" stroke="#fff" stroke-width="4" cx="50" cy="50" r="44" style="opacity:0.5;" />
<circle fill="#fff" stroke="#e74c3c" stroke-width="3" cx="8" cy="54" r="6">
<animateTransform attributeName="transform"
dur="2s"
type="rotate"
from="0 50 48"
to="360 50 52"
repeatCount="indefinite" />
</circle>
</svg>*@
</div>
}
}
<script>
function callAI(inputString) {
DotNet.invokeMethodAsync('BLAIzor', 'CallCSharpMethod', inputString)
.then(response => console.log(response))
.catch(error => console.error(error));
}
</script>
<script>
var mediaRecorder;
var audioChunks = [];
var recButton = document.getElementById("recButton");
var stopButton = document.getElementById("stopButton");
var recText = document.getElementById("recordingText");
async function startRecording() {
if (recButton) {
recButton.hidden = true;
stopButton.hidden = false;
recText.textContent = "recording...";
}
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
mediaRecorder = new MediaRecorder(stream);
mediaRecorder.ondataavailable = event => audioChunks.push(event.data);
mediaRecorder.onstop = () => {
const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
audioChunks = [];
console.log("media stopped");
const reader = new FileReader();
reader.onload = () => {
const base64Audio = reader.result.split(',')[1];
DotNet.invokeMethodAsync('BLAIzor', 'ProcessAudio', base64Audio);
};
reader.readAsDataURL(audioBlob);
};
mediaRecorder.start();
}
function stopRecording() {
mediaRecorder.stop();
var recButton = document.getElementById("recButton");
var stopButton = document.getElementById("stopButton");
var recText = document.getElementById("recordingText");
if (stopButton) {
stopButton.hidden = true;
recButton.hidden = false;
recText.textContent = "";
}
}
</script>
<script>
function openCalendar(calendlyUserName) {
console.log(calendlyUserName);
Calendly.initPopupWidget({
url: 'https://calendly.com/' + calendlyUserName + '?name=JohnDoe&email=john.doe@example.com'
});
}
</script>
<script>
function openContactForm(emailAddress) {
console.log(emailAddress);
if (emailAddress) {
DotNet.invokeMethodAsync('BLAIzor', 'OpenEmailForm', emailAddress)
}
}
</script>
<button class="btn btn-primary" @onclick="HomeClick"><i class="fa-solid fa-rotate"></i></button>
@code {
public static Home myHome;
private string HtmlContent = "";
private string UserInput = string.Empty;
private string ChatGptResponse = string.Empty;
private bool isRecording = false;
private bool isEmailFormVisible = false;
private ContactFormModel ContactFormModel = new();
private string? SuccessMessage;
private string? ErrorMessage;
private string? DocumentEmailAddress = "";
public void HomeClick()
{
_navigationManager.Refresh(true);
}
private async Task HandleValidSubmit()
{
try
{
// Simulate sending an email
await ((EmailService)_emailService).SendEmailAsync(ContactFormModel);
SuccessMessage = "Thank you for contacting us! Your message has been sent.";
ErrorMessage = null;
// Clear the form
ContactFormModel = new();
}
catch (Exception ex)
{
ErrorMessage = "An error occurred while sending your message. Please try again later.";
SuccessMessage = null;
}
}
private void CancelEmail()
{
isEmailFormVisible = false;
StateHasChanged();
}
public Home()
{
myHome = this; // Set the static reference to the current instance
}
[JSInvokable("OpenEmailForm")]
public static void OpenEmailForm(string emailAddress)
{
if (myHome != null)
{
myHome.DisplayEmailForm(emailAddress);
}
Console.Write("openEmail with: " + emailAddress);
}
public void DisplayEmailForm(string emailAddress)
{
isEmailFormVisible = true;
DocumentEmailAddress = emailAddress;
StateHasChanged();
}
[JSInvokable("CallCSharpMethod")]
public static async Task CallCSharpMethod(string input)
{
if (myHome != null)
{
await myHome.HandleJsCall(input);
}
Console.Write("Button clicked:" + input);
}
[JSInvokable("ProcessAudio")]
public static async Task ProcessAudio(string base64Audio)
{
Console.Write("audio incoming");
if (myHome != null)
{
var languageCode = "hu-HU";
if (myHome._scopedContentService.SelectedLanguage == "Hungarian")
{
languageCode = "hu-HU";
}
else if (myHome._scopedContentService.SelectedLanguage == "English")
{
languageCode = "en-US";
}
else if (myHome._scopedContentService.SelectedLanguage == "German")
{
languageCode = "de-DE";
}
var credentialsPath = myHome.configuration.GetSection("GoogleAPI").GetValue<string>("CredentialsPath");
Console.Write(credentialsPath);
var builder = new SpeechClientBuilder
{
CredentialsPath = credentialsPath
};
var speech = builder.Build();
byte[] audioBytes = Convert.FromBase64String(base64Audio);
myHome.HtmlContent = "";
var response = await speech.RecognizeAsync(new RecognitionConfig
{
Encoding = RecognitionConfig.Types.AudioEncoding.Mp3,
SampleRateHertz = 48000, // Match the actual sample rate
LanguageCode = languageCode
}, RecognitionAudio.FromBytes(audioBytes));
Console.Write("BILLED: " + response.TotalBilledTime);
foreach (var result in response.Results)
{
//Console.Write("RESULT: " + result.Alternatives.Count);
foreach (var alternative in result.Alternatives)
{
//Console.WriteLine($"Transcription: {alternative.Transcript}");
await myHome.HandleVoiceCommand(alternative.Transcript);
}
}
}
}
private async Task SendMessage()
{
Console.WriteLine("Button clicked!");
ChatGptResponse = await ChatGptService.Reasoning(UserInput);
UserInput = string.Empty;
}
protected override async Task OnInitializedAsync()
{
Console.Write("------------------------");
ChatGptService.OnContentReceived += UpdateContent;
if (string.IsNullOrEmpty(HtmlContent))
{
HtmlContent = await ChatGptService.GetChatGptWelcomeMessage();
}
UserInput = string.Empty;
}
private void UpdateContent(string content)
{
HtmlContent = content;
InvokeAsync(StateHasChanged); // Ensures UI updates dynamically
}
public async Task Enter(KeyboardEventArgs e)
{
if (e.Code == "Enter" || e.Code == "NumpadEnter")
{
HtmlContent = string.Empty;
HtmlContent = await ChatGptService.Reasoning(UserInput);
UserInput = string.Empty;
}
}
public async Task HandleVoiceCommand(string input)
{
// HtmlContent = string.Empty;
UserInput = input;
await InvokeAsync(StateHasChanged);
await ProcessWordFile();
//UserInput = string.Empty;
}
public async Task HandleJsCall(string input)
{
HtmlContent = string.Empty;
await InvokeAsync(StateHasChanged);
UserInput = "Summarize " + input;
await ProcessWordFile();
UserInput = string.Empty;
await InvokeAsync(StateHasChanged);
}
private async Task ProcessWordFile()
{
if (!string.IsNullOrEmpty(UserInput))
{
HtmlContent = string.Empty;
HtmlContent = await ChatGptService.Reasoning(UserInput);
UserInput = string.Empty;
}
}
}