From 002d64f2b14702428b69cfb8d2fa1100f8d691cf Mon Sep 17 00:00:00 2001 From: Prathameshdhande22 Date: Sat, 27 Apr 2024 22:24:40 +0530 Subject: [PATCH] fix: New download function with improved chatbot interface and implementation of videos and lifestyle recommendation implemented fixed the #5 --- bot/app.py | 5 +- bot/chatModule.py | 19 ++-- bot/utils.py | 102 ++++++++------------- frontend/src/Components/About.jsx | 4 - frontend/src/Components/Chatbot.jsx | 17 +++- frontend/src/Components/DownloadButton.jsx | 2 +- 6 files changed, 63 insertions(+), 86 deletions(-) diff --git a/bot/app.py b/bot/app.py index a55d906..a424a88 100644 --- a/bot/app.py +++ b/bot/app.py @@ -38,10 +38,7 @@ async def chatsocket(websocket: WebSocket) -> Reply: chat: ChatResponse = await chatWithUser(received, session,websocket) if isinstance(chat.get("response"), list): for resps in chat.get("response"): - if isinstance(resps, bytes): - await websocket.send_bytes(resps) - else: - await websocket.send_json({"name": "bot", "message": resps}) + await websocket.send_json({"name": "bot", "message": resps}) time.sleep(1.1) else: await websocket.send_json( diff --git a/bot/chatModule.py b/bot/chatModule.py index b460327..2b170df 100644 --- a/bot/chatModule.py +++ b/bot/chatModule.py @@ -170,10 +170,11 @@ def askQuestion(msg: Reply, session: Session) -> dict | str: recommend = True return [ msg, + {"share": "Prakriti", "dosha": prakriti.prakriti.title()}, f"The input you provided is {already_known.title()} and our model predicted as {prakriti.prakriti.title()} is different.", "It seems that there may be one or more incorrect answers to the questions you provided. Please review and verify your responses.", { - "question": "Want Diet Recommendation based on Your Prakriti?", + "question": "Want Diet & LifeStyle Recommendation based on Your Prakriti?", "options": {0: "yes", 1: "no"}, }, ] @@ -181,8 +182,9 @@ def askQuestion(msg: Reply, session: Session) -> dict | str: recommend = True return [ msg, + {"share": "Prakriti", "dosha": prakriti.prakriti.title()}, { - "question": "Want Diet Recommendation based on Your Prakriti?", + "question": "Want Diet & LifeStyle Recommendation based on Your Prakriti?", "options": {0: "yes", 1: "no"}, }, ] @@ -201,8 +203,8 @@ def handleWrongAnswer(response: str | dict | list) -> ChatResponse: } -async def sendPDFBytes(toConsume: str, toAvoid: str, websocket: WebSocket, doshas: str) -> None: - pdfbytes = createPDF(toConsume, toAvoid, doshas) +async def sendPDFBytes(toConsume: str, toAvoid: str, websocket: WebSocket, doshas: str, lifestyle: str) -> None: + pdfbytes = createPDF(toConsume, toAvoid, doshas, lifestyle) await websocket.send_json({"name": "bot", "message": "Your PDF has been Created."}) await websocket.send_bytes(pdfbytes) @@ -231,7 +233,7 @@ async def chatWithUser(msg: Reply, session: Session, websocket: WebSocket) -> Ch confirm = True return { "response": { - "question": "Do you already know your Prakriti? If yes, could you please share it with me?", + "question": "Do you already know your Prakriti? If Yes, could you please share it with me?", "options": {0: "yes", 1: "no"}, } } @@ -325,7 +327,7 @@ async def chatWithUser(msg: Reply, session: Session, websocket: WebSocket) -> Ch [ "Please give Proper Input Either Yes or No", { - "question": "Do you already know your Prakriti? If yes, could you please share it with me?", + "question": "Do you already know your Prakriti? If Yes, could you please share it with me?", "options": {0: "yes", 1: "no"}, }, ] @@ -334,12 +336,13 @@ async def chatWithUser(msg: Reply, session: Session, websocket: WebSocket) -> Ch elif recommend: if str(msg.get("message")).lower().strip() == "yes": diet = recommend_Diet(prakriti.prakriti) + lifestyle = diet.pop(2) Thread(target=runAsynioFunc, args=(sendPDFBytes( - diet[0][20:], diet[1][18:], websocket, prakriti.prakriti),)).start() + diet[0][20:], diet[1][18:], websocket, prakriti.prakriti, lifestyle),)).start() diet.append( "Thank You For predicting Prakriti with AYURBOT") diet.append( - "Your diet plan in PDF format will be available shortly. Please Wait for Some time.") + "Your personalized advice on lifestyle, diet, and related videos for your Prakriti will be ready to download in PDF format soon. Please be patient while it processes.") clearAll() return {"response": diet} else: diff --git a/bot/utils.py b/bot/utils.py index c38bf7a..1f9f022 100644 --- a/bot/utils.py +++ b/bot/utils.py @@ -1,79 +1,51 @@ -import os -import nltk -from nltk.tokenize import sent_tokenize -from weasyprint import HTML +import logging +import pandas as pd from logger import logger +from diet import recommend_Diet +from weasyprint import HTML, CSS +from nltk.tokenize import sent_tokenize +from typing import Literal +import os +df = pd.read_csv(os.path.join("dataset", "videos.csv")) # nltk.download("punkt") +logging.getLogger("weasyprint").setLevel(logging.WARNING) +logging.getLogger("fontTools").setLevel(logging.WARNING) -def createHTMLListString(text: str) -> str: - """Converts the paragraph into a Unorderedlist HTML Tag. - - Args: - text (str): Paragraph to be converted into a unorderedlist. - - Returns: - str: Paragraph converted into a unorderedlist. - """ +def createHTMLListString(text: str, listTag: Literal["", ""]) -> str: text: list[str] = sent_tokenize(text) - text.insert(0, "") + text.insert(0, listTag) + text.insert(len(text), closingTag) for i in range(1, len(text)-1): text[i] = f"
  • {text[i]}
  • " text = "".join(text) return text -def createPDF(consume: str, avoid: str, dosha: str) -> bytes: - html_content = f""" - - - Your Prakriti - AyurInsights - - -
    -
    -
    - Logo -
    -
    -
    -
    -

    Your Prakriti is : {dosha}

    -
    -
    Diet - Recommendation
    -
    -

    To Consume:

    -
    - {createHTMLListString(consume)} -
    -
    -
    -

    To Avoid:

    -
    - {createHTMLListString(avoid)} -
    -
    -
    -
    - - -""" - pdf = HTML(string=html_content).write_pdf() +def createHTMLVideoElement(videos: dict[str, str]) -> str: + htmlstr = list() + for vids in videos: + htmlstr.append("
    ") + htmlstr.append(f"{vids} ➡️ ") + htmlstr.append(f"{videos[vids]}") + htmlstr.append("
    ") + videosString = "".join(htmlstr) + return videosString + + +def recommentVideos(dosha: str) -> dict[str, str]: + vids = df.loc[df["Doshas"] == dosha].drop("Doshas", axis=1).to_dict() + return dict(zip(list(vids["Title"].values()), list(vids["Video"].values()))) + + +def createPDF(consume: str, avoid: str, dosha: str, lifeStyle: str) -> bytes: + with open(os.path.join("doc.html"), "r", encoding="utf8") as f: + html_content = str(f.read()) + videos = recommentVideos(dosha) + html_content = html_content.format( + dosha, createHTMLListString(consume, ""), createHTMLListString(avoid, ""), createHTMLListString(lifeStyle, "
      ", "
    "), createHTMLVideoElement(videos=videos)) + pdf = HTML(string=html_content).write_pdf(stylesheets=[ + CSS(string="@page {size: A4; margin: 18mm 15mm 25mm 15mm;}")]) logger.info("Created PDF File") return pdf diff --git a/frontend/src/Components/About.jsx b/frontend/src/Components/About.jsx index def9ffb..a2b83f7 100644 --- a/frontend/src/Components/About.jsx +++ b/frontend/src/Components/About.jsx @@ -17,19 +17,15 @@ function About() { "Welcome to AyurInsights, your gateway to the harmonious fusion of ancient Ayurvedic wisdom and modern technology. At AyurInsights, we're dedicated to empowering individuals with profound insights into their well-being, health, and constitution. Our journey began with a simple yet powerful question: how can we blend the timeless principles of Ayurveda with the precision of modern machine learning to enhance lives?" }

    -

    Your Solutions

    - - - { [websckt] ); + const handleMaximizeandMinimize = () => { + setFullSize(!fullsize); + if (!fullsize) { + if (typeof window != "undefined" && window.document) { + document.body.style.overflow = "hidden"; + } + } else { + document.body.style.overflow = "unset"; + } + }; + return (
    {