Skip to content

Commit

Permalink
fix: refactoring & code quality
Browse files Browse the repository at this point in the history
  • Loading branch information
ahmtslmngcl committed Dec 12, 2024
1 parent ede42a4 commit f36b352
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 48 deletions.
4 changes: 2 additions & 2 deletions src/components/Chatbot/Chatbot.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ export default function HungerMapChatbot() {
return (
<div
className={clsx('absolute', {
'inset-0 z-chatbotFullScreen ': isFullScreen,
'inset-0 z-chatbotFullScreen': isFullScreen,
'top-4 right-4': !isFullScreen,
'z-chatbotExpanded': isOpen,
'z-chatbotCollapsed': !isOpen,
Expand Down Expand Up @@ -274,7 +274,7 @@ export default function HungerMapChatbot() {
<ScrollShadow hideScrollBar className="w-full h-full">
{chats[currentChatIndex].messages.length === 0 ? (
<div className="flex flex-col items-center pt-4 space-y-4">
<p className="-center text-xl max-w-[80%] mb-2">{WELCOME_MESSAGE}</p>
<p className="text-center text-xl max-w-[80%] mb-2">{WELCOME_MESSAGE}</p>
<p className="text-center text-md max-w-[80%] mb-2text">{SUB_WELCOME_MESSAGE}</p>
<div className="flex flex-col items-center space-y-2 w-full max-w-md">
{DEFAULT_PROMPT.map((prompt) => (
Expand Down
31 changes: 24 additions & 7 deletions src/domain/contexts/ChatbotContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ export function ChatbotProvider({ children }: { children: ReactNode }) {
const [isSidebarOpen, setIsSidebarOpen] = useState(false);
const [chats, setChats] = useState<IChat[]>(ChatbotOperations.loadChatsFromStorage());

// Save chats to localStorage whenever they change
/**
* Saves chats to localStorage whenever they change
*/
useEffect(() => {
ChatbotOperations.saveChatsToStorage(chats);
}, [chats]);
Expand All @@ -39,6 +41,11 @@ export function ChatbotProvider({ children }: { children: ReactNode }) {
setIsOpen(true);
};

/**
* Starts a new chat, either with a provided chat object or a default one.
* @param newChat - Optional chat object to start with.
* @param openNewChat - Optional flag to determine if the new chat should be opened immediately.
*/
const startNewChat = (newChat?: IChat, openNewChat?: boolean) => {
let chatToAdd: IChat;

Expand Down Expand Up @@ -70,23 +77,33 @@ export function ChatbotProvider({ children }: { children: ReactNode }) {
}
};

const chatWithReport = async (countryName: string, report: string) => {
/**
* Initiates a chat with a report based on the provided country name and report content.
* If a chat for that specific already exists, it opens that chat; otherwise, it creates a new one.
* @param countryName - The name of the country related to the report.
* @param reportURL - The URL of the report to be processed.
*/
const chatWithReport = async (countryName: string, reportURL: string) => {
const reportChatIndex = chats.findIndex((chat) => chat.title === `Report ${countryName}`);
const reportChatExists = reportChatIndex !== -1;

if (reportChatExists) {
openChat(reportChatIndex);
return;
}

// Use dynamic import for client-side PDF text extraction
const { extractClientSidePdfText } = await import('@/operations/pdf/DownloadPortalOperations');
const reportText = await extractClientSidePdfText(report);
// const reportText = await DownloadPortalOperations.extractTextFromPdf(await report);
const { extractPdfText } = await import('@/operations/chatbot/ExtractPdfText');
let reportText;
try {
reportText = await extractPdfText(reportURL);
} catch {
reportText = '';
}

const assistantMessage = {
id: crypto.randomUUID(),
content: reportText
? `Hey, how can I help you with this report about ${reportText}?`
? `Hey, how can I help you with this report about ${countryName}?`
: `Hey, unfortunately I'm currently unable to answer questions about this report. You can try it later or chat with me about other things!`,
role: SenderRole.ASSISTANT,
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,15 @@ import { pdfjs } from 'react-pdf';

pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.min.mjs`;

export const extractClientSidePdfText = async (url: string): Promise<string> => {
/**
* Extracts text from a PDF document located at the specified URL.
* This function retrieves the text content from each page of the PDF
* and concatenates it into a single string, which is then returned.
*
* @param url - The URL of the PDF document to extract text from.
* @returns A promise that resolves to the extracted text or undefined if an error occurs.
*/
export const extractPdfText = async (url: string): Promise<string> => {
try {
const pdf = await pdfjs.getDocument(url).promise;
let fullText = '';
Expand All @@ -31,7 +39,6 @@ export const extractClientSidePdfText = async (url: string): Promise<string> =>

return fullText.trim();
} catch (error) {
console.error('Error extracting text from PDF:', error);
return 'error during extraction';
throw new Error(`Error extracting text from PDF: ${error}`);
}
};
36 changes: 0 additions & 36 deletions src/operations/download-portal/DownloadPortalOperations.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@ import { CountryCodesData } from '@/domain/entities/country/CountryCodesData';
import { ICountryData } from '@/domain/entities/download/Country';
import { CustomTableColumns } from '@/domain/props/CustomTableProps';

// pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.min.mjs`;

export class DownloadPortalOperations {
static getColumns(): CustomTableColumns {
return [
Expand Down Expand Up @@ -128,38 +126,4 @@ export class DownloadPortalOperations {
DownloadPortalOperations.handlePreview(country.url.summary, setPdfFile, setError);
toggleModal();
}

/*
static async extractTextFromPdf(url: string): Promise<string> {
try {
const pdf = await pdfjs.getDocument(url).promise;
let fullText = '';
const pagePromises: Promise<string>[] = [];
for (let i = 1; i <= pdf.numPages; i += 1) {
pagePromises.push(
pdf.getPage(i).then(async (page) => {
const textContent = await page.getTextContent();
return textContent.items
.map((item) => {
if ('str' in item) {
return item.str;
}
return '';
})
.join(' ');
})
);
}
const pageTexts = await Promise.all(pagePromises);
fullText = pageTexts.join('\n');
return fullText.trim();
} catch (error) {
console.error('Error extracting text from PDF:', error);
return 'error during extraction';
}
}
*/
}

0 comments on commit f36b352

Please sign in to comment.