0% found this document useful (0 votes)
35 views4 pages

Emotion Chatbot

The document outlines the structure and implementation of an emotion chatbot project, consisting of a backend using FastAPI and BERT for emotion detection, and a frontend with a WhatsApp-style UI. The backend handles user authentication, message processing, and sentiment analysis, providing suggestions based on detected emotions. The frontend allows users to interact with the chatbot through a simple interface, displaying messages and responses dynamically.

Uploaded by

Manisha Samal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views4 pages

Emotion Chatbot

The document outlines the structure and implementation of an emotion chatbot project, consisting of a backend using FastAPI and BERT for emotion detection, and a frontend with a WhatsApp-style UI. The backend handles user authentication, message processing, and sentiment analysis, providing suggestions based on detected emotions. The frontend allows users to interact with the chatbot through a simple interface, displaying messages and responses dynamically.

Uploaded by

Manisha Samal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

# Project Structure (Separated Folders)

#
# emotion_chatbot/
# ├── backend/ # FastAPI, BERT, user auth, suggestions, voice
# └── frontend/ # HTML, CSS, JavaScript UI with WhatsApp-style design

# -------- BACKEND: FastAPI APP WITH BERT EMOTION DETECTION --------


# File: backend/[Link]

from fastapi import FastAPI, UploadFile, Form, Request


from [Link] import HTMLResponse, FileResponse
from [Link] import StaticFiles
from pydantic import BaseModel
from transformers import pipeline
import json, os
from gtts import gTTS
import uvicorn

app = FastAPI()
[Link]("/static", StaticFiles(directory="../frontend/static"), name="static")

# BERT Sentiment Analyzer


sentiment_pipeline = pipeline("sentiment-analysis")

# In-memory user data (or use DB for real deployment)


USER_DB = "[Link]"
if not [Link](USER_DB):
with open(USER_DB, "w") as f:
[Link]({}, f)

class Message(BaseModel):
username: str
message: str

class UserLogin(BaseModel):
username: str
password: str

ACTIVITY_MAP = {
"POSITIVE": ["Try singing a happy song!", "Go for a walk", "Do some painting or
dancing!"],
"NEGATIVE": ["Take deep breaths", "Write in a journal", "Try a short
meditation"],
"NEUTRAL": ["Read a book", "Organize your space", "Listen to music"]
}

# Utilities

def get_sentiment_label(label):
if "NEGATIVE" in [Link]():
return "NEGATIVE"
elif "POSITIVE" in [Link]():
return "POSITIVE"
else:
return "NEUTRAL"

def speak(text):
tts = gTTS(text=text, lang='en')
[Link]("response.mp3")
[Link]("start response.mp3")

@[Link]("/login")
def login(user: UserLogin):
with open(USER_DB) as f:
users = [Link](f)
if [Link] in users and users[[Link]]["password"] ==
[Link]:
return {"success": True}
return {"success": False, "error": "Invalid credentials"}

@[Link]("/register")
def register(user: UserLogin):
with open(USER_DB) as f:
users = [Link](f)
if [Link] in users:
return {"success": False, "error": "User exists"}
users[[Link]] = {"password": [Link], "history": []}
with open(USER_DB, 'w') as f:
[Link](users, f)
return {"success": True}

@[Link]("/chat")
def chat(msg: Message):
analysis = sentiment_pipeline([Link])[0]
sentiment = get_sentiment_label(analysis['label'])
with open(USER_DB) as f:
users = [Link](f)
users[[Link]]["history"].append({"text": [Link], "sentiment":
sentiment})
with open(USER_DB, 'w') as f:
[Link](users, f)

suggestions = ACTIVITY_MAP[sentiment]
response = f"I sense you're feeling {[Link]()}. You might enjoy:
{suggestions[0]}"
speak(response)
return {"sentiment": sentiment, "response": response}

@[Link]("/", response_class=HTMLResponse)
async def serve_home():
with open("../frontend/[Link]") as f:
return [Link]()

if __name__ == "__main__":
[Link]("main:app", host="[Link]", port=5000, reload=True)

# -------- FRONTEND: Beautiful WhatsApp-style UI --------


# File: frontend/[Link]

<!-- Basic WhatsApp-like layout -->


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Emotion Chatbot</title>
<link rel="stylesheet" href="static/[Link]">
</head>
<body>
<div class="container">
<div class="chat-window" id="chat-window"></div>
<div class="input-bar">
<input type="text" id="user-input" placeholder="Type your message...">
<button onclick="sendMessage()">Send</button>
</div>
</div>
<script src="static/[Link]"></script>
</body>
</html>

# File: frontend/static/[Link]

body {
background-color: #202c33;
font-family: Arial;
margin: 0;
padding: 0;
}
.container {
width: 100%;
max-width: 600px;
margin: auto;
background-color: #111b21;
height: 100vh;
display: flex;
flex-direction: column;
}
.chat-window {
flex: 1;
overflow-y: auto;
padding: 10px;
color: white;
}
.input-bar {
display: flex;
background-color: #2a3942;
padding: 10px;
}
#user-input {
flex: 1;
padding: 10px;
border: none;
border-radius: 5px;
font-size: 16px;
}
button {
margin-left: 10px;
background-color: #00a884;
color: white;
border: none;
padding: 10px 15px;
border-radius: 5px;
font-size: 16px;
}
.bubble {
margin: 10px;
padding: 10px;
border-radius: 15px;
max-width: 80%;
animation: fadeIn 0.3s;
}
.user {
background-color: #005c4b;
color: white;
align-self: flex-end;
}
.bot {
background-color: #202c33;
color: white;
align-self: flex-start;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}

# File: frontend/static/[Link]

async function sendMessage() {


const input = [Link]("user-input");
const chat = [Link]("chat-window");
const msg = [Link];
if (!msg) return;
const userBubble = [Link]("div");
[Link] = "bubble user";
[Link] = msg;
[Link](userBubble);
[Link] = "";

const res = await fetch("/chat", {


method: "POST",
headers: { "Content-Type": "application/json" },
body: [Link]({ username: "demo", message: msg })
});
const data = await [Link]();

const botBubble = [Link]("div");


[Link] = "bubble bot";
[Link] = [Link];
[Link](botBubble);
[Link] = [Link];
}

// Optional: Add voice recognition, session storage, login UI, etc.

You might also like