File size: 7,668 Bytes
aefc87e
 
 
 
 
 
 
 
 
 
d4e8d9b
 
fee8462
 
 
 
 
 
 
d4e8d9b
fee8462
d4e8d9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fee8462
 
 
 
 
 
 
d4e8d9b
 
fee8462
 
 
d4e8d9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
---
title: Chatbot
emoji: πŸ€–
colorFrom: indigo
colorTo: blue
sdk: docker
sdk_version: "1.0"
app_file: app.py
pinned: false
---
# CampVerse Chatbot Microservice

## Features

- **Gemini AI Integration**: Enhanced NLP understanding using Google's Gemini API
- **Intent Classification**: Smart detection of user intents (event search, greetings, help, etc.)
- **Semantic Event Search**: Find events using natural language queries
- **FAQ Support**: Answer common questions about the platform
- **Real-time Chat**: WebSocket support for live conversations

## Quick Start for New Users

If you're new and want to run this chatbot microservice, you can choose either Docker or Python. Both methods are described below:

---

### πŸš€ Run via Python (Local Development)

1. **Clone the Repository**
  ```bash
  git clone https://github.com/CcpC-cuj/CampVerse.git
  cd CampVerse/ML/chatbot
  ```

2. **Install Python & Dependencies**
  Make sure you have Python 3.10+ installed. Then install dependencies:
  ```bash
  pip install -r requirements.txt
  ```

3. **Set Environment Variables**
   ```bash
   export BACKEND_URL=http://localhost:5001  # Backend API URL
   export GEMINI_API_KEY=your_gemini_api_key  # For enhanced NLP (optional)
   ```

4. **Start the Backend Service**
   ```bash
   uvicorn app:app_socket --host 0.0.0.0 --port 8000
   ```

5. **Test with CLI Chat Client**
  Open a new terminal and run:
  ```bash
  python cli_chat.py
  ```
  Type your questions and interact with the bot.

---

### 🐳 Run via Docker (Containerized)

1. **Build the Docker Image**
  ```bash
  docker build -t chatbot-service .
  ```

2. **Run the Docker Container**
   ```bash
   docker run -p 8000:8000 -e BACKEND_URL=http://localhost:5001 chatbot-service
   ```3. **Test the Service**
  - REST API: 
    ```bash
    curl -X POST http://localhost:8000/chatbot -H "Content-Type: application/json" -d '{"question":"How do I register?"}'
    ```
  - Socket.IO: 
    ```bash
    python cli_chat.py
    ```

---

### 🌐 Integrate with Your Web App
Use REST API or Socket.IO as shown below to connect your frontend.

---

A production-ready chatbot microservice using FastAPI, Socket.IO, and sentence transformers for FAQ-based question answering.

## Features

- πŸš€ **FastAPI REST API**: HTTP endpoint for Q&A
- πŸ”Œ **Socket.IO Real-time**: WebSocket support for live chat
- πŸ€– **AI-Powered**: Uses sentence transformers and FAISS for semantic search
- 🎯 **Intent Classification**: Detects greetings, event queries, help requests, and more
- πŸ” **Dynamic Event Discovery**: Fetches and searches live events from backend API
- 🐳 **Docker Ready**: Containerized for easy deployment
- πŸ“ **Logging**: Comprehensive logging for debugging
- βœ… **Input Validation**: Validates question length and content
- 🌐 **CORS Enabled**: Ready for frontend integration

## Architecture

```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   Frontend      β”‚
β”‚  (React/Web)    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         β”‚
         β”‚ HTTP POST /chatbot
         β”‚ OR Socket.IO
         β”‚
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   app.py        β”‚
β”‚  FastAPI +      β”‚
β”‚  Socket.IO      β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         β”‚
         β”‚ Semantic Search
         β”‚
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   faq.json      β”‚
β”‚  (FAQ Database) β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

## API Endpoints

### REST API

**POST /chatbot**
```json
Request:
{
  "question": "How do I register?"
}

Response:
{
  "question": "How do I register?",
  "answer": "Click on the Register button..."
}
```

### Socket.IO Events

**Client β†’ Server**
- `user_question`: Send a question
  ```javascript
  socket.emit('user_question', { question: 'How do I login?' });
  ```

**Server β†’ Client**
- `bot_answer`: Receive answer
  ```javascript
  socket.on('bot_answer', (data) => {
    console.log(data.answer);
  });
  ```

## Setup & Installation

### Local Development

1. **Install dependencies:**
   ```bash
   pip install -r requirements.txt
   ```

2. **Run the server:**
   ```bash
   uvicorn app:app_socket --host 0.0.0.0 --port 8000
   ```

3. **Test with CLI client:**
   ```bash
   python cli_chat.py
   ```

### Docker Deployment

1. **Build the image:**
   ```bash
   docker build -t chatbot-service .
   ```

2. **Run the container:**
   ```bash
   docker run -p 8000:8000 chatbot-service
   ```

3. **Test the service:**
   - REST API: `curl -X POST http://localhost:8000/chatbot -H "Content-Type: application/json" -d '{"question":"How do I register?"}'`
   - Socket.IO: `python cli_chat.py`

## Project Structure

```
chatbot/
β”œβ”€β”€ app.py              # Main backend (FastAPI + Socket.IO)
β”œβ”€β”€ cli_chat.py         # CLI client for testing
β”œβ”€β”€ Dockerfile          # Docker configuration
β”œβ”€β”€ faq.json            # FAQ database
β”œβ”€β”€ requirements.txt    # Python dependencies
└── README.md           # This file
```

## Integration with Frontend

### React Example (Socket.IO)

```javascript
import io from 'socket.io-client';

const socket = io('http://localhost:8000');

socket.on('connect', () => {
  console.log('Connected to chatbot');
});

socket.on('bot_answer', (data) => {
  console.log('Answer:', data.answer);
});

// Send question
socket.emit('user_question', { question: 'How do I login?' });
```

### React Example (REST API)

```javascript
const response = await fetch('http://localhost:8000/chatbot', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ question: 'How do I login?' })
});

const data = await response.json();
console.log(data.answer);
```

## Configuration

### Environment Variables

You can configure the service using environment variables:

- `PORT`: Server port (default: 8000)
- `LOG_LEVEL`: Logging level (default: INFO)

### FAQ Management

Edit `faq.json` to add/update questions and answers:

```json
[
  {
    "question": "How do I register?",
    "answer": "Click on the Register button on the homepage..."
  }
]
```

After updating, rebuild the Docker image or restart the server.

## Monitoring & Logs

The service logs all:
- Client connections/disconnections
- Incoming questions
- Matched FAQ pairs
- Errors and warnings

View logs in Docker:
```bash
docker logs -f <container-id>
```

## Security

- CORS is enabled for all origins (configure for production)
- Input validation (max 512 characters)
- Error handling to prevent crashes
- No rate limiting (add if needed for production)

## Testing

### Manual Testing

1. Start the service
2. Run CLI client: `python cli_chat.py`
3. Type questions and verify responses

### Testing REST API

```bash
curl -X POST http://localhost:8000/chatbot \
  -H "Content-Type: application/json" \
  -d '{"question":"How do I register?"}'
```

## Troubleshooting

**Service won't start:**
- Check if port 8000 is available
- Verify all dependencies are installed
- Check logs for errors

**CLI client can't connect:**
- Ensure service is running on port 8000
- Check firewall settings
- Verify `python-socketio` is installed

**No answer returned:**
- Check if `faq.json` exists and is valid
- Verify the question exists in FAQ database
- Check server logs for errors

## Future Enhancements

- [ ] Add rate limiting for production
- [ ] Add authentication for Socket.IO
- [ ] Support multiple languages
- [ ] Add conversation history
- [ ] Implement fallback responses
- [ ] Add metrics and analytics

## License

Part of the CampVerse project.