interstellar_ai/app/backend/InputOutputHandler.tsx

275 lines
8.5 KiB
TypeScript
Raw Normal View History

2024-09-19 13:02:56 +02:00
"use client"
2024-09-27 10:57:18 +02:00
import React, { use, useEffect, useRef, useState } from "react";
2024-09-20 10:34:16 +02:00
import ConversationFrontend from "../components/ConversationFrontend";
import InputFrontend from "../components/InputFrontend";
2024-09-25 12:33:52 +02:00
import VoiceSend from "./voice_backend"
2024-09-26 08:57:28 +02:00
import { AudioRecorder } from "./AudioRecorder";
2024-09-23 11:11:45 +02:00
import axios from "axios";
2024-09-26 13:42:22 +02:00
import { resolve } from "path";
2024-09-27 10:57:18 +02:00
import { FFmpeg } from "@ffmpeg/ffmpeg";
import { fetchFile, toBlobURL } from "@ffmpeg/util"
2024-09-24 09:51:16 +02:00
2024-09-25 12:33:52 +02:00
2024-09-19 13:02:56 +02:00
const InputOutputBackend: React.FC = () => {
2024-09-23 16:34:55 +02:00
type Message = {
role: string
2024-09-24 16:42:36 +02:00
content: string
2024-09-23 16:34:55 +02:00
}
/* Variables for System-prompt */
const [preferredCurrency, setPreferredCurrency] = useState(localStorage.getItem("preferredCurrency") || "")
const [preferredLanguage, setPreferredLanguage] = useState(localStorage.getItem("preferredLanguage") || "")
const [timeFormat, setTimeFormat] = useState(localStorage.getItem("timeFormat") || "")
const [preferredMeasurement, setPreferredMeasurement] = useState(localStorage.getItem("preferredMeasurement") || "")
const [timeZone, setTimeZone] = useState(localStorage.getItem("timeZone") || "")
const [dateFormat, setDateFormat] = useState(localStorage.getItem("dateFormat") || "")
2024-09-26 13:42:22 +02:00
const [copyClicked, setCopyClicked] = useState(false)
2024-09-23 11:11:45 +02:00
const [accessToken, setAccessToken] = useState("")
2024-09-24 16:42:36 +02:00
const postWorkerRef = useRef<Worker | null>(null)
2024-09-23 11:11:45 +02:00
const getWorkerRef = useRef<Worker | null>(null)
const [messages, setMessages] = useState<Message[]>([{ role: "system",
content: `You are in the timezone: ${timeZone}.
You use the time format ${timeFormat}.
You use the date format ${dateFormat} for all references of dates.
You use the ${preferredMeasurement} system. You use the currency ${preferredCurrency}.
You will anwser in ${preferredLanguage}.`
},{ role: "assistant", content: "Hello! How can I help you?" }])
2024-09-23 11:11:45 +02:00
const [liveMessage, setLiveMessage] = useState("")
2024-09-24 16:42:36 +02:00
const [inputMessage, setInputMessage] = useState<string>("")
2024-09-24 13:50:46 +02:00
const [inputDisabled, setInputDisabled] = useState(false)
2024-09-26 08:57:28 +02:00
const [isRecording, setIsRecording] = useState(false)
const [audioURL, setAudioURL] = useState<string | null>(null)
const mediaRecorderRef = useRef<MediaRecorder | null>(null)
const audioChunks = useRef<Blob[]>([])
2024-09-25 12:33:52 +02:00
2024-09-23 11:11:45 +02:00
2024-09-23 16:34:55 +02:00
console.log(messages);
2024-09-24 16:42:36 +02:00
2024-09-23 16:34:55 +02:00
2024-09-23 11:11:45 +02:00
useEffect(() => {
2024-09-24 16:42:36 +02:00
getNewToken()
2024-09-23 11:11:45 +02:00
postWorkerRef.current = new Worker(new URL("./threads/PostWorker.js", import.meta.url))
postWorkerRef.current.onmessage = (event) => {
const status = event.data.status
if (status == 200) {
2024-09-24 13:50:46 +02:00
setInputDisabled(false)
2024-09-23 11:11:45 +02:00
endGetWorker()
} else if (status == 500) {
2024-09-24 13:50:46 +02:00
setInputDisabled(false)
2024-09-23 11:11:45 +02:00
if (getWorkerRef.current) {
addMessage("assistant", "There was an Error with the AI response")
getWorkerRef.current.postMessage("terminate")
getWorkerRef.current.terminate()
}
}
}
2024-09-24 16:42:36 +02:00
2024-09-23 11:11:45 +02:00
return () => {
if (postWorkerRef.current) {
postWorkerRef.current.terminate()
}
if (getWorkerRef.current) {
getWorkerRef.current.postMessage("terminate")
getWorkerRef.current.terminate()
}
}
2024-09-24 16:42:36 +02:00
}, [])
const getNewToken = () => {
console.log("getting access");
axios.get("http://localhost:5000/interstellar_ai/api/ai_create")
.then(response => {
setAccessToken(response.data.access_token)
console.log(response.data.access_token);
})
.catch(error => {
console.log("error:", error.message);
})
}
2024-09-23 11:11:45 +02:00
const startGetWorker = () => {
if (!getWorkerRef.current) {
getWorkerRef.current = new Worker(new URL("./threads/GetWorker.js", import.meta.url))
2024-09-24 16:42:36 +02:00
getWorkerRef.current.postMessage({ action: "start", access_token: accessToken })
addMessage("assistant", "")
2024-09-23 11:11:45 +02:00
getWorkerRef.current.onmessage = (event) => {
const data = event.data
2024-09-24 16:42:36 +02:00
2024-09-23 14:54:13 +02:00
if (event.data == "error") {
2024-09-24 16:42:36 +02:00
setLiveMessage("error getting AI response: " + data.error)
2024-09-23 11:11:45 +02:00
} else {
console.log("Received data:", data);
2024-09-23 16:34:55 +02:00
editLastMessage(data.response)
2024-09-23 11:11:45 +02:00
}
}
getWorkerRef.current.onerror = (error) => {
console.error("Worker error:", error)
}
2024-09-24 16:42:36 +02:00
}
2024-09-23 11:11:45 +02:00
}
const endGetWorker = () => {
if (getWorkerRef.current) {
2024-09-24 16:42:36 +02:00
getWorkerRef.current.postMessage({ action: "terminate" })
2024-09-23 11:11:45 +02:00
getWorkerRef.current.terminate()
2024-09-24 10:58:14 +02:00
getWorkerRef.current = null
2024-09-23 14:54:13 +02:00
console.log(messages);
2024-09-23 11:11:45 +02:00
}
}
2024-09-23 16:34:55 +02:00
const editLastMessage = (newContent: string) => {
2024-09-24 10:58:14 +02:00
if (newContent == "") {
2024-09-24 13:50:46 +02:00
newContent = "Generating answer..."
2024-09-24 10:58:14 +02:00
}
2024-09-24 16:42:36 +02:00
setMessages((prevMessages) => {
const updatedMessages = prevMessages.slice(); // Create a shallow copy of the current messages
if (updatedMessages.length > 0) {
const lastMessage = updatedMessages[updatedMessages.length - 1];
updatedMessages[updatedMessages.length - 1] = {
...lastMessage, // Keep the existing role and other properties
content: newContent, // Update only the content
};
}
return updatedMessages; // Return the updated array
});
};
2024-09-23 16:34:55 +02:00
2024-09-27 10:57:18 +02:00
useEffect(() => {
},[preferredCurrency, preferredLanguage, timeFormat, preferredMeasurement, timeZone, dateFormat])
2024-09-23 16:34:55 +02:00
2024-09-23 11:11:45 +02:00
const addMessage = (role: string, content: string) => {
2024-09-24 16:42:36 +02:00
setMessages(previous => [...previous, { role, content }])
}
const handleSendClick = (inputValue: string, override: boolean) => {
2024-09-24 10:22:50 +02:00
if (inputValue != "") {
2024-09-24 16:42:36 +02:00
if (!inputDisabled || override) {
2024-09-24 13:50:46 +02:00
setInputDisabled(true)
2024-09-24 10:22:50 +02:00
if (postWorkerRef.current) {
addMessage("user", inputValue)
2024-09-24 16:42:36 +02:00
console.log("input:", inputValue);
postWorkerRef.current.postMessage({ messages: [...messages, { role: "user", content: inputValue }], ai_model: "llama3.2", access_token: accessToken })
2024-09-24 10:22:50 +02:00
startGetWorker()
}
2024-09-24 09:51:16 +02:00
}
2024-09-23 11:11:45 +02:00
}
}
2024-09-19 15:56:26 +02:00
2024-09-25 12:33:52 +02:00
const startRecording = async () => {
2024-09-26 08:57:28 +02:00
const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
const mediaRecorder = new MediaRecorder(stream)
mediaRecorderRef.current = mediaRecorder
mediaRecorder.ondataavailable = (event) => {
audioChunks.current.push(event.data)
}
2024-09-27 10:57:18 +02:00
mediaRecorder.onstop = async () => {
2024-09-26 13:08:29 +02:00
const audioBlob = new Blob(audioChunks.current, { type: "audio/ogg" })
2024-09-26 08:57:28 +02:00
audioChunks.current = []
2024-09-27 13:59:27 +02:00
// console.log(audioBlob);
// const url = URL.createObjectURL(audioBlob)
// const audio = new Audio(url);
// audio.play().catch(error => console.error("Error playing audio:", error));
2024-09-26 08:57:28 +02:00
const remote = new VoiceSend()
2024-09-27 13:59:27 +02:00
remote.sendToVoiceRecognition(audioBlob)
2024-09-26 08:57:28 +02:00
}
2024-09-25 12:33:52 +02:00
2024-09-26 08:57:28 +02:00
mediaRecorder.start()
setIsRecording(true)
2024-09-27 10:57:18 +02:00
}
const ffmpegRef = useRef<FFmpeg | null>(null)
const audioRef = useRef("")
const loadFFmpeg = async () => {
if (!ffmpegRef.current) {
ffmpegRef.current = new FFmpeg()
await ffmpegRef.current.load()
2024-09-26 08:57:28 +02:00
}
2024-09-27 10:57:18 +02:00
}
2024-09-26 08:57:28 +02:00
2024-09-27 10:57:18 +02:00
const stopRecording = () => {
mediaRecorderRef.current?.stop()
setIsRecording(false)
}
2024-09-25 12:33:52 +02:00
2024-09-23 11:11:45 +02:00
const handleMicClick = () => {
2024-09-25 12:33:52 +02:00
if (!isRecording) {
startRecording();
} else {
stopRecording();
}
};
2024-09-19 15:56:26 +02:00
2024-09-23 11:11:45 +02:00
const handleResendClick = () => {
2024-09-24 16:42:36 +02:00
var temporary_message = messages[messages.length - 2]['content']
const updatedMessages = messages.slice(0, -2)
setMessages(updatedMessages)
endGetWorker()
getNewToken()
setInputDisabled(false)
handleSendClick(temporary_message, true)
2024-09-23 11:11:45 +02:00
}
2024-09-19 15:56:26 +02:00
2024-09-23 11:11:45 +02:00
const handleEditClick = () => {
2024-09-24 16:42:36 +02:00
setInputMessage(messages[messages.length - 2]['content'])
const updatedMessages = messages.slice(0, -2)
setMessages(updatedMessages)
endGetWorker()
getNewToken()
setInputDisabled(false)
2024-09-23 11:11:45 +02:00
}
2024-09-19 13:02:56 +02:00
2024-09-24 16:42:36 +02:00
const handleCopyClick = async () => {
2024-09-26 13:42:22 +02:00
setCopyClicked(false)
2024-09-24 16:42:36 +02:00
try {
await navigator.clipboard.writeText(messages[messages.length - 1]['content']);
2024-09-26 13:42:22 +02:00
fadeCopyText()
2024-09-24 16:42:36 +02:00
} catch (err) {
console.error('Failed to copy: ', err);
}
2024-09-23 11:11:45 +02:00
}
2024-09-20 09:17:28 +02:00
2024-09-26 13:42:22 +02:00
const wait = (time: number) => {
return new Promise(resolve => setTimeout(resolve, time));
}
const fadeCopyText = async () => {
setCopyClicked(true)
await wait(1000)
setCopyClicked(false)
}
2024-09-24 16:42:36 +02:00
return (
2024-09-19 15:56:26 +02:00
<div>
<ConversationFrontend
messages={messages}
onResendClick={handleResendClick}
onEditClick={handleEditClick}
onCopyClick={handleCopyClick}
2024-09-26 13:42:22 +02:00
isClicked={copyClicked}
2024-09-19 15:56:26 +02:00
/>
<InputFrontend
2024-09-24 16:42:36 +02:00
message={inputMessage}
2024-09-19 15:56:26 +02:00
onSendClick={handleSendClick}
onMicClick={handleMicClick}
2024-09-24 13:50:46 +02:00
inputDisabled={inputDisabled}
2024-09-26 08:57:28 +02:00
isRecording={isRecording}
2024-09-27 13:59:27 +02:00
/>
2024-09-19 15:56:26 +02:00
</div>
2024-09-24 16:42:36 +02:00
)
2024-09-19 13:02:56 +02:00
}
2024-09-27 13:59:27 +02:00
export default InputOutputBackend