From 2366c2cd94a0ff2d0cf450c6825cf63c08b0f937 Mon Sep 17 00:00:00 2001 From: JeevaRamanathan M Date: Sat, 19 Oct 2024 04:24:14 +0000 Subject: [PATCH 01/16] enhancement: added loading state for conversation --- frontend/src/Navigation.tsx | 23 ++++++++++++++++----- frontend/src/preferences/preferenceApi.ts | 11 +++++----- frontend/src/preferences/preferenceSlice.ts | 10 +++++++-- 3 files changed, 32 insertions(+), 12 deletions(-) diff --git a/frontend/src/Navigation.tsx b/frontend/src/Navigation.tsx index ac7063be..c8252e37 100644 --- a/frontend/src/Navigation.tsx +++ b/frontend/src/Navigation.tsx @@ -37,11 +37,12 @@ import { setSelectedDocs, setSourceDocs, } from './preferences/preferenceSlice'; +import Spinner from './assets/spinner.svg'; +import SpinnerDark from './assets/spinner-dark.svg'; import Upload from './upload/Upload'; import ShareButton from './components/ShareButton'; import Help from './components/Help'; - interface NavigationProps { navOpen: boolean; setNavOpen: React.Dispatch>; @@ -89,18 +90,20 @@ export default function Navigation({ navOpen, setNavOpen }: NavigationProps) { const navigate = useNavigate(); useEffect(() => { - if (!conversations) { + if (!conversations?.data) { fetchConversations(); } - }, [conversations, dispatch]); + }, [conversations?.data, dispatch]); async function fetchConversations() { + dispatch(setConversations({ data: null, loading: true })); return await getConversations() .then((fetchedConversations) => { dispatch(setConversations(fetchedConversations)); }) .catch((error) => { console.error('Failed to fetch conversations: ', error); + dispatch(setConversations({ data: null, loading: false })); }); } @@ -196,6 +199,7 @@ export default function Navigation({ navOpen, setNavOpen }: NavigationProps) { setNavOpen(!isMobile); }, [isMobile]); useDefaultDocument(); + return ( <> {!navOpen && ( @@ -278,13 +282,22 @@ export default function Navigation({ navOpen, setNavOpen }: NavigationProps) { id="conversationsMainDiv" className="mb-auto h-[78vh] overflow-y-auto overflow-x-hidden dark:text-white" > - {conversations && conversations.length > 0 ? ( + {conversations?.loading && ( +
+ +
+ )} + + {conversations?.data && conversations.data.length > 0 ? (

{t('chats')}

- {conversations?.map((conversation) => ( + {conversations.data?.map((conversation) => ( { } } -export async function getConversations(): Promise< - { name: string; id: string }[] | null -> { +export async function getConversations(): Promise<{ + data: { name: string; id: string }[] | null; + loading: boolean; +}> { try { const response = await conversationService.getConversations(); const data = await response.json(); @@ -34,10 +35,10 @@ export async function getConversations(): Promise< conversations.push(conversation as { name: string; id: string }); }); - return conversations; + return { data: conversations, loading: false }; } catch (error) { console.log(error); - return null; + return { data: null, loading: false }; } } diff --git a/frontend/src/preferences/preferenceSlice.ts b/frontend/src/preferences/preferenceSlice.ts index 6fb2480b..c566ba70 100644 --- a/frontend/src/preferences/preferenceSlice.ts +++ b/frontend/src/preferences/preferenceSlice.ts @@ -15,7 +15,10 @@ export interface Preference { token_limit: number; selectedDocs: Doc | null; sourceDocs: Doc[] | null; - conversations: { name: string; id: string }[] | null; + conversations: { + data: { name: string; id: string }[] | null; + loading: boolean; + }; modalState: ActiveState; } @@ -34,7 +37,10 @@ const initialState: Preference = { retriever: 'classic', } as Doc, sourceDocs: null, - conversations: null, + conversations: { + data: null, + loading: false, + }, modalState: 'INACTIVE', }; From a185b2a12a526e843b0a0723c02d255c02dc953c Mon Sep 17 00:00:00 2001 From: JeevaRamanathan M Date: Sat, 19 Oct 2024 04:45:00 +0000 Subject: [PATCH 02/16] retaining original state --- frontend/src/Navigation.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/frontend/src/Navigation.tsx b/frontend/src/Navigation.tsx index c8252e37..d858bc02 100644 --- a/frontend/src/Navigation.tsx +++ b/frontend/src/Navigation.tsx @@ -96,14 +96,14 @@ export default function Navigation({ navOpen, setNavOpen }: NavigationProps) { }, [conversations?.data, dispatch]); async function fetchConversations() { - dispatch(setConversations({ data: null, loading: true })); + dispatch(setConversations({ ...conversations, loading: true })); return await getConversations() .then((fetchedConversations) => { dispatch(setConversations(fetchedConversations)); }) .catch((error) => { console.error('Failed to fetch conversations: ', error); - dispatch(setConversations({ data: null, loading: false })); + dispatch(setConversations({ ...conversations, loading: false })); }); } From 6a024b0ced42d89a32d4ba868dbcecaded4c5b37 Mon Sep 17 00:00:00 2001 From: JeevaRamanathan M Date: Sat, 19 Oct 2024 04:46:46 +0000 Subject: [PATCH 03/16] update catch block --- frontend/src/Navigation.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/src/Navigation.tsx b/frontend/src/Navigation.tsx index d858bc02..5aa694f8 100644 --- a/frontend/src/Navigation.tsx +++ b/frontend/src/Navigation.tsx @@ -103,7 +103,7 @@ export default function Navigation({ navOpen, setNavOpen }: NavigationProps) { }) .catch((error) => { console.error('Failed to fetch conversations: ', error); - dispatch(setConversations({ ...conversations, loading: false })); + dispatch(setConversations({ data: null, loading: false })); }); } From fcb5f946dd676d3583587350a4db5e5c8403760a Mon Sep 17 00:00:00 2001 From: JeevaRamanathan M Date: Tue, 22 Oct 2024 22:37:56 +0000 Subject: [PATCH 04/16] fixed according to suggestion Signed-off-by: JeevaRamanathan M --- frontend/src/Navigation.tsx | 10 ++++------ frontend/src/store.ts | 5 ++++- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/frontend/src/Navigation.tsx b/frontend/src/Navigation.tsx index aa0b1a58..6050108e 100644 --- a/frontend/src/Navigation.tsx +++ b/frontend/src/Navigation.tsx @@ -11,7 +11,6 @@ import DocsGPT3 from './assets/cute_docsgpt3.svg'; import Discord from './assets/discord.svg'; import Expand from './assets/expand.svg'; import Github from './assets/github.svg'; -import Info from './assets/info.svg'; import SettingGear from './assets/settingGear.svg'; import Twitter from './assets/TwitterX.svg'; import UploadIcon from './assets/upload.svg'; @@ -44,7 +43,6 @@ import Spinner from './assets/spinner.svg'; import SpinnerDark from './assets/spinner-dark.svg'; import { selectQueries } from './conversation/conversationSlice'; import Upload from './upload/Upload'; -import ShareButton from './components/ShareButton'; import Help from './components/Help'; interface NavigationProps { @@ -314,14 +312,14 @@ export default function Navigation({ navOpen, setNavOpen }: NavigationProps) { className="mb-auto h-[78vh] overflow-y-auto overflow-x-hidden dark:text-white" > {conversations?.loading && ( -
+
+ className="animate-spin cursor-pointer bg-transparent" + alt="Loading..." + />
)} - {conversations?.data && conversations.data.length > 0 ? (
diff --git a/frontend/src/store.ts b/frontend/src/store.ts index 565ea8cc..5843d493 100644 --- a/frontend/src/store.ts +++ b/frontend/src/store.ts @@ -23,7 +23,10 @@ const preloadedState: { preference: Preference } = { chunks: JSON.parse(chunks ?? '2').toString(), token_limit: token_limit ? parseInt(token_limit) : 2000, selectedDocs: doc !== null ? JSON.parse(doc) : null, - conversations: null, + conversations: { + data: null, + loading: false, + }, sourceDocs: [ { name: 'default', From 1e88c8637824ecdfee7210c2e5dd6333fdd796bf Mon Sep 17 00:00:00 2001 From: JeevaRamanathan M Date: Tue, 22 Oct 2024 23:34:32 +0000 Subject: [PATCH 05/16] updated loader state Signed-off-by: JeevaRamanathan M --- frontend/src/Navigation.tsx | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/frontend/src/Navigation.tsx b/frontend/src/Navigation.tsx index 6050108e..cf9da2d1 100644 --- a/frontend/src/Navigation.tsx +++ b/frontend/src/Navigation.tsx @@ -72,6 +72,7 @@ export default function Navigation({ navOpen, setNavOpen }: NavigationProps) { const conversations = useSelector(selectConversations); const modalStateDeleteConv = useSelector(selectModalStateDeleteConv); const conversationId = useSelector(selectConversationId); + const [isDeletingConversation, setIsDeletingConversation] = useState(false); const { isMobile } = useMediaQuery(); const [isDarkTheme] = useDarkTheme(); @@ -114,6 +115,7 @@ export default function Navigation({ navOpen, setNavOpen }: NavigationProps) { } const handleDeleteAllConversations = () => { + setIsDeletingConversation(true); conversationService .deleteAll() .then(() => { @@ -123,6 +125,7 @@ export default function Navigation({ navOpen, setNavOpen }: NavigationProps) { }; const handleDeleteConversation = (id: string) => { + setIsDeletingConversation(true); conversationService .delete(id, {}) .then(() => { @@ -311,7 +314,7 @@ export default function Navigation({ navOpen, setNavOpen }: NavigationProps) { id="conversationsMainDiv" className="mb-auto h-[78vh] overflow-y-auto overflow-x-hidden dark:text-white" > - {conversations?.loading && ( + {conversations?.loading && !isDeletingConversation && (
Date: Sat, 26 Oct 2024 03:29:54 +0530 Subject: [PATCH 06/16] Feature: Added Text-To-Speech Functionality --- frontend/src/assets/speaker.svg | 4 ++ frontend/src/assets/stopspeech.svg | 5 ++ .../src/components/TextToSpeechButton.tsx | 64 +++++++++++++++++++ .../src/conversation/ConversationBubble.tsx | 10 ++- 4 files changed, 82 insertions(+), 1 deletion(-) create mode 100644 frontend/src/assets/speaker.svg create mode 100644 frontend/src/assets/stopspeech.svg create mode 100644 frontend/src/components/TextToSpeechButton.tsx diff --git a/frontend/src/assets/speaker.svg b/frontend/src/assets/speaker.svg new file mode 100644 index 00000000..ea947330 --- /dev/null +++ b/frontend/src/assets/speaker.svg @@ -0,0 +1,4 @@ + + + + diff --git a/frontend/src/assets/stopspeech.svg b/frontend/src/assets/stopspeech.svg new file mode 100644 index 00000000..f77a235b --- /dev/null +++ b/frontend/src/assets/stopspeech.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/frontend/src/components/TextToSpeechButton.tsx b/frontend/src/components/TextToSpeechButton.tsx new file mode 100644 index 00000000..2ab7d1c2 --- /dev/null +++ b/frontend/src/components/TextToSpeechButton.tsx @@ -0,0 +1,64 @@ +import { useState } from 'react'; +import Speaker from '../assets/speaker.svg?react'; +import Stopspeech from '../assets/stopspeech.svg?react'; + +export default function SpeakButton({ + text, + colorLight, + colorDark, +}: { + text: string; + colorLight?: string; + colorDark?: string; +}) { + const [isSpeaking, setIsSpeaking] = useState(false); + const [isSpeakHovered, setIsSpeakHovered] = useState(false); + + const handleSpeakClick = (text: string) => { + if (isSpeaking) { + window.speechSynthesis.cancel(); + setIsSpeaking(false); + return; + } // Stop ongoing speech if already speaking + + const utterance = new SpeechSynthesisUtterance(text); + setIsSpeaking(true); + + utterance.onend = () => { + setIsSpeaking(false); // Reset when speech ends + }; + + utterance.onerror = () => { + console.error('Speech synthesis failed.'); + setIsSpeaking(false); + }; + + window.speechSynthesis.speak(utterance); + }; + + return ( +
+ {isSpeaking ? ( + handleSpeakClick(text)} + onMouseEnter={() => setIsSpeakHovered(true)} + onMouseLeave={() => setIsSpeakHovered(false)} + /> + ) : ( + handleSpeakClick(text)} + onMouseEnter={() => setIsSpeakHovered(true)} + onMouseLeave={() => setIsSpeakHovered(false)} + /> + )} +
+ ); +} diff --git a/frontend/src/conversation/ConversationBubble.tsx b/frontend/src/conversation/ConversationBubble.tsx index 2ccf1ca3..a9a05168 100644 --- a/frontend/src/conversation/ConversationBubble.tsx +++ b/frontend/src/conversation/ConversationBubble.tsx @@ -7,7 +7,6 @@ import remarkGfm from 'remark-gfm'; import remarkMath from 'remark-math'; import rehypeKatex from 'rehype-katex'; import 'katex/dist/katex.min.css'; - import DocsGPT3 from '../assets/cute_docsgpt3.svg'; import Dislike from '../assets/dislike.svg?react'; import Document from '../assets/document.svg'; @@ -23,6 +22,7 @@ import { } from '../preferences/preferenceSlice'; import classes from './ConversationBubble.module.css'; import { FEEDBACK, MESSAGE_TYPE } from './conversationModels'; +import SpeakButton from '../components/TextToSpeechButton'; const DisableSourceFE = import.meta.env.VITE_DISABLE_SOURCE_FE || false; @@ -336,6 +336,14 @@ const ConversationBubble = forwardRef<
+
+
+ {/* Add SpeakButton here */} +
+
{type === 'ERROR' && (
{retryBtn}
From 91690ff99affef6260628ee7f7b1d97ddea18abf Mon Sep 17 00:00:00 2001 From: Srayash <146334722+Srayash@users.noreply.github.com> Date: Sun, 27 Oct 2024 23:02:52 +0530 Subject: [PATCH 07/16] Resize speaker icon. --- frontend/src/assets/speaker.svg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/src/assets/speaker.svg b/frontend/src/assets/speaker.svg index ea947330..6c379177 100644 --- a/frontend/src/assets/speaker.svg +++ b/frontend/src/assets/speaker.svg @@ -1,4 +1,4 @@ - + From fcb6bec4746314244d9abca42e97cf7949ec2a3e Mon Sep 17 00:00:00 2001 From: Srayash <146334722+Srayash@users.noreply.github.com> Date: Mon, 28 Oct 2024 02:52:13 +0530 Subject: [PATCH 08/16] Update TextToSpeechButton.tsx --- .../src/components/TextToSpeechButton.tsx | 33 ++++++++++--------- 1 file changed, 18 insertions(+), 15 deletions(-) diff --git a/frontend/src/components/TextToSpeechButton.tsx b/frontend/src/components/TextToSpeechButton.tsx index 2ab7d1c2..cc062c87 100644 --- a/frontend/src/components/TextToSpeechButton.tsx +++ b/frontend/src/components/TextToSpeechButton.tsx @@ -1,6 +1,7 @@ import { useState } from 'react'; import Speaker from '../assets/speaker.svg?react'; import Stopspeech from '../assets/stopspeech.svg?react'; +import EasySpeech from 'easy-speech'; export default function SpeakButton({ text, @@ -14,26 +15,28 @@ export default function SpeakButton({ const [isSpeaking, setIsSpeaking] = useState(false); const [isSpeakHovered, setIsSpeakHovered] = useState(false); - const handleSpeakClick = (text: string) => { + const handleSpeakClick = async (text: string) => { if (isSpeaking) { - window.speechSynthesis.cancel(); + EasySpeech.cancel(); setIsSpeaking(false); return; } // Stop ongoing speech if already speaking - const utterance = new SpeechSynthesisUtterance(text); - setIsSpeaking(true); - - utterance.onend = () => { - setIsSpeaking(false); // Reset when speech ends - }; - - utterance.onerror = () => { - console.error('Speech synthesis failed.'); - setIsSpeaking(false); - }; - - window.speechSynthesis.speak(utterance); + try { + await EasySpeech.init(); // Initialize EasySpeech + setIsSpeaking(true); + + EasySpeech.speak({ + text, + onend: () => setIsSpeaking(false), // Reset when speech ends + onerror: () => { + console.error('Speech synthesis failed.'); + setIsSpeaking(false); + }, + }); + } catch (error) { + console.error('Failed to initialize speech synthesis', error); + } }; return ( From 6978e7439f9039b8c8cfe1f201b6d40e131db089 Mon Sep 17 00:00:00 2001 From: Srayash <146334722+Srayash@users.noreply.github.com> Date: Mon, 28 Oct 2024 02:53:07 +0530 Subject: [PATCH 09/16] Update package-lock.json --- frontend/package-lock.json | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 4087e4f5..37bf0c07 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -10,6 +10,7 @@ "dependencies": { "@reduxjs/toolkit": "^2.2.7", "chart.js": "^4.4.4", + "easy-speech": "^2.4.0", "i18next": "^23.15.1", "i18next-browser-languagedetector": "^8.0.0", "prop-types": "^15.8.1", @@ -3075,6 +3076,24 @@ "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==", "dev": true }, + "node_modules/easy-speech": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/easy-speech/-/easy-speech-2.4.0.tgz", + "integrity": "sha512-wpMv29DEoeP/eyXr4aXpDqd9DvlXl7aQs7BgfKbjGVxqkmQPgNmpbF5YULaTH5bc/5qrteg5MDfCD2Zd0qr4rQ==", + "funding": [ + { + "type": "GitHub", + "url": "https://github.com/sponsors/jankapunkt" + }, + { + "type": "PayPal", + "url": "https://paypal.me/kuesterjan" + } + ], + "engines": { + "node": ">= 14.x" + } + }, "node_modules/electron-to-chromium": { "version": "1.5.11", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.11.tgz", From 0b1a3029959384df00fff0b5e0bce78c0fc52b94 Mon Sep 17 00:00:00 2001 From: Srayash <146334722+Srayash@users.noreply.github.com> Date: Mon, 28 Oct 2024 02:53:51 +0530 Subject: [PATCH 10/16] Update package.json --- frontend/package.json | 1 + 1 file changed, 1 insertion(+) diff --git a/frontend/package.json b/frontend/package.json index 83d531d6..9148831f 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -21,6 +21,7 @@ "dependencies": { "@reduxjs/toolkit": "^2.2.7", "chart.js": "^4.4.4", + "easy-speech": "^2.4.0", "i18next": "^23.15.1", "i18next-browser-languagedetector": "^8.0.0", "prop-types": "^15.8.1", From b223cf05d93be450b15c0a6dfc6c233d47717a13 Mon Sep 17 00:00:00 2001 From: Srayash Date: Tue, 29 Oct 2024 23:36:09 +0530 Subject: [PATCH 11/16] use /api/tts endpoint for TTS feature --- .../src/components/TextToSpeechButton.tsx | 52 +++++++++++++------ 1 file changed, 35 insertions(+), 17 deletions(-) diff --git a/frontend/src/components/TextToSpeechButton.tsx b/frontend/src/components/TextToSpeechButton.tsx index cc062c87..b5402469 100644 --- a/frontend/src/components/TextToSpeechButton.tsx +++ b/frontend/src/components/TextToSpeechButton.tsx @@ -1,7 +1,7 @@ -import { useState } from 'react'; +import { useState, useRef } from 'react'; import Speaker from '../assets/speaker.svg?react'; import Stopspeech from '../assets/stopspeech.svg?react'; -import EasySpeech from 'easy-speech'; +const apiHost = import.meta.env.VITE_API_HOST || 'https://docsapi.arc53.com'; export default function SpeakButton({ text, @@ -14,28 +14,46 @@ export default function SpeakButton({ }) { const [isSpeaking, setIsSpeaking] = useState(false); const [isSpeakHovered, setIsSpeakHovered] = useState(false); + const audioRef = useRef(null); // Reference to the audio object - const handleSpeakClick = async (text: string) => { + const handleSpeakClick = async () => { if (isSpeaking) { - EasySpeech.cancel(); + // Stop audio if currently playing and reset the state + audioRef.current?.pause(); + audioRef.current = null; setIsSpeaking(false); return; - } // Stop ongoing speech if already speaking + } try { - await EasySpeech.init(); // Initialize EasySpeech setIsSpeaking(true); - - EasySpeech.speak({ - text, - onend: () => setIsSpeaking(false), // Reset when speech ends - onerror: () => { - console.error('Speech synthesis failed.'); - setIsSpeaking(false); - }, + + // Make a POST request to the /api/tts endpoint + const response = await fetch(apiHost + '/api/tts', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ text }), }); + + const data = await response.json(); + + if (data.success && data.audio_base64) { + const audio = new Audio(`data:audio/mp3;base64,${data.audio_base64}`); + audioRef.current = audio; // Store the audio object in ref for later control + audio.play(); + + // Reset state when audio ends + audio.onended = () => { + setIsSpeaking(false); + audioRef.current = null; + }; + } else { + console.error('Failed to retrieve audio.'); + setIsSpeaking(false); + } } catch (error) { - console.error('Failed to initialize speech synthesis', error); + console.error('Error fetching audio from TTS endpoint', error); + setIsSpeaking(false); } }; @@ -50,14 +68,14 @@ export default function SpeakButton({ {isSpeaking ? ( handleSpeakClick(text)} + onClick={handleSpeakClick} onMouseEnter={() => setIsSpeakHovered(true)} onMouseLeave={() => setIsSpeakHovered(false)} /> ) : ( handleSpeakClick(text)} + onClick={handleSpeakClick} onMouseEnter={() => setIsSpeakHovered(true)} onMouseLeave={() => setIsSpeakHovered(false)} /> From 605f168c7ef834f733bdeb461e9ad56c28404d4f Mon Sep 17 00:00:00 2001 From: Srayash Date: Tue, 29 Oct 2024 23:51:25 +0530 Subject: [PATCH 12/16] remove unused modules (easy-speech) --- frontend/package-lock.json | 1 - frontend/package.json | 1 - 2 files changed, 2 deletions(-) diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 37bf0c07..9973bb9e 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -10,7 +10,6 @@ "dependencies": { "@reduxjs/toolkit": "^2.2.7", "chart.js": "^4.4.4", - "easy-speech": "^2.4.0", "i18next": "^23.15.1", "i18next-browser-languagedetector": "^8.0.0", "prop-types": "^15.8.1", diff --git a/frontend/package.json b/frontend/package.json index 9148831f..83d531d6 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -21,7 +21,6 @@ "dependencies": { "@reduxjs/toolkit": "^2.2.7", "chart.js": "^4.4.4", - "easy-speech": "^2.4.0", "i18next": "^23.15.1", "i18next-browser-languagedetector": "^8.0.0", "prop-types": "^15.8.1", From 5c99615edf373bef3b50c1c188064ca7979864fc Mon Sep 17 00:00:00 2001 From: Srayash Date: Wed, 30 Oct 2024 00:03:08 +0530 Subject: [PATCH 13/16] UI changes: add loading animation while audio response is being fetched --- frontend/src/assets/Loading.svg | 3 ++ .../src/components/TextToSpeechButton.tsx | 37 ++++++++++++------- 2 files changed, 26 insertions(+), 14 deletions(-) create mode 100644 frontend/src/assets/Loading.svg diff --git a/frontend/src/assets/Loading.svg b/frontend/src/assets/Loading.svg new file mode 100644 index 00000000..84a604f9 --- /dev/null +++ b/frontend/src/assets/Loading.svg @@ -0,0 +1,3 @@ + + + diff --git a/frontend/src/components/TextToSpeechButton.tsx b/frontend/src/components/TextToSpeechButton.tsx index b5402469..2cb9e8f8 100644 --- a/frontend/src/components/TextToSpeechButton.tsx +++ b/frontend/src/components/TextToSpeechButton.tsx @@ -1,6 +1,7 @@ import { useState, useRef } from 'react'; import Speaker from '../assets/speaker.svg?react'; import Stopspeech from '../assets/stopspeech.svg?react'; +import LoadingIcon from '../assets/Loading.svg?react'; // Add a loading icon SVG here const apiHost = import.meta.env.VITE_API_HOST || 'https://docsapi.arc53.com'; export default function SpeakButton({ @@ -13,12 +14,13 @@ export default function SpeakButton({ colorDark?: string; }) { const [isSpeaking, setIsSpeaking] = useState(false); + const [isLoading, setIsLoading] = useState(false); const [isSpeakHovered, setIsSpeakHovered] = useState(false); - const audioRef = useRef(null); // Reference to the audio object + const audioRef = useRef(null); const handleSpeakClick = async () => { if (isSpeaking) { - // Stop audio if currently playing and reset the state + // Stop audio if it's currently playing audioRef.current?.pause(); audioRef.current = null; setIsSpeaking(false); @@ -26,9 +28,9 @@ export default function SpeakButton({ } try { - setIsSpeaking(true); + // Set loading state and initiate TTS request + setIsLoading(true); - // Make a POST request to the /api/tts endpoint const response = await fetch(apiHost + '/api/tts', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -38,22 +40,27 @@ export default function SpeakButton({ const data = await response.json(); if (data.success && data.audio_base64) { + // Create and play the audio const audio = new Audio(`data:audio/mp3;base64,${data.audio_base64}`); - audioRef.current = audio; // Store the audio object in ref for later control - audio.play(); + audioRef.current = audio; - // Reset state when audio ends - audio.onended = () => { - setIsSpeaking(false); - audioRef.current = null; - }; + audio.play().then(() => { + setIsSpeaking(true); + setIsLoading(false); + + // Reset when audio ends + audio.onended = () => { + setIsSpeaking(false); + audioRef.current = null; + }; + }); } else { console.error('Failed to retrieve audio.'); - setIsSpeaking(false); + setIsLoading(false); } } catch (error) { console.error('Error fetching audio from TTS endpoint', error); - setIsSpeaking(false); + setIsLoading(false); } }; @@ -65,7 +72,9 @@ export default function SpeakButton({ : `bg-[${colorLight ? colorLight : '#FFFFFF'}] dark:bg-[${colorDark ? colorDark : 'transparent'}]` }`} > - {isSpeaking ? ( + {isLoading ? ( + + ) : isSpeaking ? ( Date: Wed, 30 Oct 2024 12:59:28 +0000 Subject: [PATCH 14/16] fix: discord bot --- extensions/discord/bot.py | 128 +++++++++++++++++++++++++++++--------- 1 file changed, 99 insertions(+), 29 deletions(-) diff --git a/extensions/discord/bot.py b/extensions/discord/bot.py index 3cb1d1e2..9e2eee67 100644 --- a/extensions/discord/bot.py +++ b/extensions/discord/bot.py @@ -1,25 +1,39 @@ import os import re - +import logging +import aiohttp import discord -import requests from discord.ext import commands import dotenv dotenv.load_dotenv() -# Replace 'YOUR_BOT_TOKEN' with your bot's token +# Enable logging +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + +# Bot configuration TOKEN = os.getenv("DISCORD_TOKEN") -PREFIX = '@DocsGPT' -BASE_API_URL = 'http://localhost:7091' +PREFIX = '!' # Command prefix +BASE_API_URL = os.getenv("API_BASE", "https://gptcloud.arc53.com") +API_URL = BASE_API_URL + "/api/answer" +API_KEY = os.getenv("API_KEY") intents = discord.Intents.default() intents.message_content = True bot = commands.Bot(command_prefix=PREFIX, intents=intents) +# Store conversation history per user +conversation_histories = {} + +def escape_markdown(text): + """Escapes Discord markdown characters.""" + escape_chars = r'\*_$$$$()~>#+-=|{}.!' + return re.sub(f'([{re.escape(escape_chars)}])', r'\\\1', text) def split_string(input_str): + """Splits the input string to detect bot mentions.""" pattern = r'^<@!?{0}>\s*'.format(bot.user.id) match = re.match(pattern, input_str) if match: @@ -27,42 +41,98 @@ def split_string(input_str): return str(bot.user.id), content return None, input_str - @bot.event async def on_ready(): print(f'{bot.user.name} has connected to Discord!') - -async def fetch_answer(question): - data = { - 'sender': 'discord', - 'question': question, - 'history': '' +async def generate_answer(question, messages, conversation_id): + """Generates an answer using the external API.""" + payload = { + "question": question, + "api_key": API_KEY, + "history": messages, + "conversation_id": conversation_id } - headers = {"Content-Type": "application/json", - "Accept": "application/json"} - response = requests.post(BASE_API_URL + '/api/answer', json=data, headers=headers) - if response.status_code == 200: - return response.json()['answer'] - return 'Sorry, I could not fetch the answer.' + headers = { + "Content-Type": "application/json; charset=utf-8" + } + timeout = aiohttp.ClientTimeout(total=60) + async with aiohttp.ClientSession(timeout=timeout) as session: + async with session.post(API_URL, json=payload, headers=headers) as resp: + if resp.status == 200: + data = await resp.json() + conversation_id = data.get("conversation_id") + answer = data.get("answer", "Sorry, I couldn't find an answer.") + return {"answer": answer, "conversation_id": conversation_id} + else: + return {"answer": "Sorry, I couldn't find an answer.", "conversation_id": None} +@bot.command(name="start") +async def start(ctx): + """Handles the /start command.""" + await ctx.send(f"Hi {ctx.author.mention}! How can I assist you today?") + +@bot.command(name="custom_help") +async def custom_help_command(ctx): + """Handles the /custom_help command.""" + help_text = ( + "Here are the available commands:\n" + "`!start` - Begin a new conversation with the bot\n" + "`!help` - Display this help message\n\n" + "You can also mention me or send a direct message to ask a question!" + ) + await ctx.send(help_text) @bot.event async def on_message(message): if message.author == bot.user: return - content = message.content.strip() - prefix, content = split_string(content) - if prefix is None: - return - - part_prefix = str(bot.user.id) - if part_prefix == prefix: - answer = await fetch_answer(content) - await message.channel.send(answer) - + # Process commands first await bot.process_commands(message) + # Check if the message is in a DM channel + if isinstance(message.channel, discord.DMChannel): + content = message.content.strip() + else: + # In guild channels, check if the message mentions the bot at the start + content = message.content.strip() + prefix, content = split_string(content) + if prefix is None: + return + part_prefix = str(bot.user.id) + if part_prefix != prefix: + return # Bot not mentioned at the start, so do not process -bot.run(TOKEN) + # Now process the message + user_id = message.author.id + if user_id not in conversation_histories: + conversation_histories[user_id] = { + "history": [], + "conversation_id": None + } + + conversation = conversation_histories[user_id] + conversation["history"].append({"prompt": content}) + + # Generate the answer + response_doc = await generate_answer( + content, + conversation["history"], + conversation["conversation_id"] + ) + answer = response_doc["answer"] + conversation_id = response_doc["conversation_id"] + + # Escape markdown characters + answer = escape_markdown(answer) + + await message.channel.send(answer) + + conversation["history"][-1]["response"] = answer + conversation["conversation_id"] = conversation_id + + # Keep conversation history to last 10 exchanges + conversation["history"] = conversation["history"][-10:] + +bot.run(TOKEN) \ No newline at end of file From 06e4a05e419bab9d5e8cb1169f6006ba035af0ed Mon Sep 17 00:00:00 2001 From: Alex Date: Wed, 30 Oct 2024 15:17:37 +0000 Subject: [PATCH 15/16] fix: slightly better discord bot formatting --- extensions/discord/bot.py | 1 - 1 file changed, 1 deletion(-) diff --git a/extensions/discord/bot.py b/extensions/discord/bot.py index 9e2eee67..7ebef2ea 100644 --- a/extensions/discord/bot.py +++ b/extensions/discord/bot.py @@ -125,7 +125,6 @@ async def on_message(message): conversation_id = response_doc["conversation_id"] # Escape markdown characters - answer = escape_markdown(answer) await message.channel.send(answer) From 2cc3372b86820e9c30ef51813ddac1d22083de86 Mon Sep 17 00:00:00 2001 From: Alex Date: Wed, 30 Oct 2024 15:27:14 +0000 Subject: [PATCH 16/16] fix: bot chunking --- extensions/discord/bot.py | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/extensions/discord/bot.py b/extensions/discord/bot.py index 7ebef2ea..94daf7e2 100644 --- a/extensions/discord/bot.py +++ b/extensions/discord/bot.py @@ -27,6 +27,27 @@ bot = commands.Bot(command_prefix=PREFIX, intents=intents) # Store conversation history per user conversation_histories = {} +def chunk_string(text, max_length=2000): + """Splits a string into chunks of a specified maximum length.""" + # Create list to store the split strings + chunks = [] + # Loop through the text, create substrings with max_length + while len(text) > max_length: + # Find last space within the limit + idx = text.rfind(' ', 0, max_length) + # Ensure we don't have an empty part + if idx == -1: + # If no spaces, just take chunk + chunks.append(text[:max_length]) + text = text[max_length:] + else: + # Push whatever we've got up to the last space + chunks.append(text[:idx]) + text = text[idx+1:] + # Catches the remaining part + chunks.append(text) + return chunks + def escape_markdown(text): """Escapes Discord markdown characters.""" escape_chars = r'\*_$$$$()~>#+-=|{}.!' @@ -124,9 +145,9 @@ async def on_message(message): answer = response_doc["answer"] conversation_id = response_doc["conversation_id"] - # Escape markdown characters - - await message.channel.send(answer) + answer_chunks = chunk_string(answer) + for chunk in answer_chunks: + await message.channel.send(chunk) conversation["history"][-1]["response"] = answer conversation["conversation_id"] = conversation_id