Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 0 additions & 21 deletions LICENSE

This file was deleted.

7 changes: 0 additions & 7 deletions README.md

This file was deleted.

119 changes: 119 additions & 0 deletions chatbot/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@

# 💬 Grp7 Digital Banking Bot

A web-based chatbot assistant that supports FAQ handling, intent detection, and secure banking actions (like deposit/withdraw) after authentication.

---

## 🧩 Tech Stack

- **Frontend**: HTML, CSS, JavaScript
- **Backend**: Python (Flask)
- **LLM Integration**: Gemini API (planned)
- **Authentication**: Username/Password (dummy login)
- **Intent Detection**: Currently keyword-based, to be replaced with LLM or classifier

---

## 📁 Project Structure

```
chatbot_project/
├── app.py # Flask backend server
├── /templates
│ └── chat.html # Chat UI with floating button and login modal
├── /static
│ ├── style.css # Styling for chatbot and landing page
│ └── script.js # JS for chat interaction and login popup
└── README.md # Project info and team guidance
```

---

## ✅ Features

- Chatbot UI accessible via floating 🤖 button
- Chat popup with message history and smart scroll
- Login modal triggered **only when required** (e.g., for banking actions)
- Dummy authentication: `username=admin`, `password=123`
- Intent-aware chatbot backend (to be powered by Gemini)

---

## 🧠 API Endpoints Used by Frontend

| Endpoint | Method | Description |
|------------|--------|--------------------------------------|
| `/chat` | POST | Handles user input, returns bot reply and intent |
| `/auth` | POST | Authenticates user (dummy logic for now) |

### Chat Request Format:
```json
{ "message": "I want to deposit money" }
```

### Chat Response Expected:
```json
{
"reply": "Please login to continue.",
"intent": "deposit"
}
```

### Auth Request Format:
```json
{ "username": "admin", "password": "123" }
```

---

## 👨‍💻 Backend Team – Integration Guide

### 🔹 Replace Dummy Intent Detection

In `app.py`:

```python
@app.route("/chat", methods=["POST"])
def chat():
user_input = request.json.get("message")

# 🔽 Replace this with Gemini intent classifier
if "deposit" in user_input:
return jsonify({"reply": "Please login to continue.", "intent": "deposit"})
```

> 🔁 Return both `reply` and `intent`

### 🔹 Plug in Gemini API

Use the Gemini API to:
- Detect user intent
- Generate a context-aware reply

Then return both values to the frontend.

---

## 🧪 Running the App Locally

### 1. Install Flask (once)
```bash
pip install flask
```

### 2. Start the server
```bash
python app.py
```

### 3. Visit the app
Open browser: [http://127.0.0.1:5000](http://127.0.0.1:5000)

---

## 🙋 Front-End Contact: Bikash
Handles HTML, CSS, JS, and integration layout.
71 changes: 71 additions & 0 deletions chatbot/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import os
from flask import Flask, render_template, request, jsonify, abort
import jwt
from datetime import datetime, timedelta
from database import auth_user, init_db

# Initialize Flask app pointing to local templates/ and static/
app = Flask(__name__, template_folder="templates", static_folder="static")

# JWT configuration
SECRET_KEY = os.getenv("SECRET_KEY", "your_secret_key")
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 15


# Helpers for JWT
def create_access_token(username: str) -> str:
expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
payload = {"sub": username, "exp": expire}
return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)


def verify_access_token(token: str) -> str:
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
user = payload.get("sub")
if not user:
abort(401, "Invalid token payload")
return user
except jwt.ExpiredSignatureError:
abort(401, "Token has expired")
except jwt.InvalidTokenError:
abort(401, "Invalid token")

# Routes
@app.route("/", methods=["GET"])
def index():
return render_template("chat.html")

@app.route("/auth/login", methods=["POST"])
def auth_login():
data = request.get_json() or {}
username = data.get("username")
password = data.get("password")
if not username or not password:
abort(400, 'Missing "username" or "password"')

# Validate against real database
if not auth_user(username, password):
return jsonify({"status": "fail"}), 401

token = create_access_token(username)
return jsonify({"status": "success", "access_token": token, "token_type": "bearer"}), 200

@app.route("/chat", methods=["POST"])
def chat():
auth_header = request.headers.get("Authorization", "")
if not auth_header.startswith("Bearer "):
return jsonify({"reply": "🔒 Please login to continue."}), 401
token = auth_header.split(" ", 1)[1]
user = verify_access_token(token)

msg = request.json.get("message", "")
if "transfer" in msg.lower():
return jsonify({"reply": f"🔄 Transfer flow would run here for {user}."})
if "faq" in msg.lower():
return jsonify({"reply": "Here’s an FAQ answer stub."})
return jsonify({"reply": "You are being transferred to a human agent."})

if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000, debug=True)
47 changes: 47 additions & 0 deletions chatbot/static/script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
let accessToken = null;

async function submitLogin() {
const username = document.getElementById("username").value;
const password = document.getElementById("password").value;

const res = await fetch("/auth/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, password })
});

const data = await res.json();
if (res.ok && data.status === "success") {
accessToken = data.access_token;
document.getElementById("login-modal").style.display = "none";
appendMessage("System", "✅ Login successful! You can now proceed.");
} else {
appendMessage("System", "❌ Login failed. Try again.");
}
}

async function sendMessage() {
const input = document.getElementById("message");
const message = input.value.trim();
if (!message) return;
input.value = "";
appendMessage("You", message);

if (!accessToken) {
appendMessage("System", "🔒 Please login to continue.");
document.getElementById("login-modal").style.display = "flex";
return;
}

const res = await fetch("/chat", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${accessToken}`
},
body: JSON.stringify({ message })
});

const data = await res.json();
appendMessage("Bot", data.reply);
}
Loading