Spaces:
Running
Running
File size: 7,526 Bytes
ef8a26d 8889e4d ef8a26d 8889e4d ef8a26d 8889e4d ef8a26d 8889e4d ef8a26d 8889e4d ef8a26d 8889e4d ef8a26d 8889e4d ef8a26d 8889e4d ef8a26d 8889e4d ef8a26d 8889e4d ef8a26d 8889e4d |
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 |
---
title: AI Chatbot
emoji: π€
colorFrom: blue
colorTo: purple
sdk: gradio
sdk_version: 5.49.1
app_file: app.py
pinned: false
license: mit
short_description: A simple AI chatbot built with Gradio
---
# AI Chatbot with Database Integration
A smart AI chatbot built with Gradio that can handle general conversation and answer specific questions from a database/FAQ system.
## Features
- π€ **General Conversation**: Handles greetings, help requests, thanks, and goodbyes
- π **Smart Database Integration**: Intelligent fuzzy matching finds answers even with different wording
- π§ **AI-Powered Matching**: Uses keyword extraction, text similarity, and semantic matching
- π **Smart Learning**: Automatically saves unanswered questions to `/unanswered_questions` table for review
- π¬ **Interactive Chat Interface**: Clean, modern UI built with Gradio
- π **Error Handling**: Robust error handling for network issues and API failures
- π± **Responsive Design**: Works on desktop and mobile devices
## How It Works
The chatbot operates in three modes:
1. **Conversation Mode**: Recognizes common conversation patterns like greetings, help requests, and thanks
2. **Smart Database Query Mode**: For specific questions, it uses intelligent matching to find relevant answers
3. **Learning Mode**: When no answer is found, it automatically saves the question to your database for review
### Smart Matching Algorithm
The chatbot uses a sophisticated matching system that combines:
- **Text Normalization**: Removes punctuation, converts to lowercase, handles whitespace
- **Enhanced Keyword Extraction**: Identifies important words with stemming (removes 's', 'ing', 'ed')
- **Sequence Matching**: Uses difflib for character-level similarity
- **Keyword Overlap**: Calculates Jaccard similarity between keyword sets
- **Substring Matching**: Detects when one text contains another with length weighting
- **Word Order Similarity**: Matches common word sequences
- **Semantic Similarity**: Groups related words (money, time, contact, requirements, etc.)
- **Phrase Matching**: Recognizes common phrase patterns
- **Adaptive Thresholds**: Adjusts matching criteria based on query length
- **Weighted Scoring**: Combines all methods with optimized weights
**Example**: If your database has "What are the admission requirements?" and a user asks "admission requirements", the chatbot will find a match with 68% similarity!
**Success Rate**: The improved algorithm achieves **92% success rate** (23/25 test cases matched) compared to the previous 66.7%!
## Local Development
### Prerequisites
- Python 3.7 or higher
- pip package manager
### Installation
1. Clone or download this repository
2. Install the required dependencies:
```bash
pip install -r requirements.txt
```
### Running Locally
```bash
python app.py
```
The chatbot will be available at `http://localhost:7860`
## Deployment to Hugging Face Spaces
### Step 1: Create a Hugging Face Account
1. Go to [Hugging Face](https://huggingface.co) and create an account
2. Verify your email address
### Step 2: Create a New Space
1. Navigate to [Create a New Space](https://huggingface.co/new-space)
2. Fill in the details:
- **Space Name**: Choose a unique name (e.g., `my-ai-chatbot`)
- **License**: Select an appropriate license (e.g., MIT)
- **Space Hardware**: Choose CPU (free tier)
- **Visibility**: Set to Public or Private as desired
- **SDK**: Select "Gradio"
### Step 3: Upload Files
Upload these files to your Hugging Face Space:
1. `app.py` - Main application file
2. `requirements.txt` - Dependencies
3. `README.md` - This documentation (optional)
### Step 4: Configure Settings
1. In your Space settings, make sure the **SDK** is set to "Gradio"
2. The **App file** should be set to `app.py`
3. If your database requires authentication, add credentials as secrets in the Space settings
### Step 5: Deploy
Once all files are uploaded, your Space will automatically build and deploy. The process usually takes 2-5 minutes.
## Database Integration
The chatbot connects to your database at `https://database-dhe2.onrender.com` and tries multiple endpoints:
### Answer Retrieval Endpoints:
- `/faq`
- `/search`
- `/query`
- `/api/faq`
### Smart Matching Endpoints (for getting all questions):
- `/questions`
- `/faq/all`
- `/api/questions`
- `/all_questions`
### Unanswered Questions Endpoints:
- `/unanswered_questions`
- `/api/unanswered_questions`
- `/save_question`
- `/api/save_question`
### Request Formats:
**GET Request for Answers:**
```
https://database-dhe2.onrender.com/faq?question=your_question_here
```
**POST Request for Answers:**
```json
{
"question": "your_question_here"
}
```
**POST Request for Saving Unanswered Questions:**
```json
{
"question": "unanswered_question_here",
"created_at": "2024-01-01T12:00:00.000000"
}
```
### Response Formats:
- `{"answer": "response_text"}`
- `{"response": "response_text"}`
- `["response_text"]`
- `"response_text"`
### Database Table Structure:
**unanswered_questions table:**
```sql
CREATE TABLE unanswered_questions (
id INT PRIMARY KEY AUTO_INCREMENT,
question TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```
### Smart Learning Feature:
When the chatbot cannot find an answer to a question, it automatically:
1. Saves the question to the `/unanswered_questions` table with the structure:
- `id` (auto-generated by database)
- `question` (the user's question)
- `created_at` (timestamp when question was asked)
2. Provides a helpful response to the user
3. Allows you to review and add answers later
## Customization
### Modifying Conversation Patterns
Edit the regex patterns in the `AIChatbot` class to customize conversation recognition:
```python
self.greeting_patterns = [
r'\b(hi|hello|hey|good morning|good afternoon|good evening)\b',
# Add your own patterns here
]
```
### Changing Database URL
Update the database URL in the `AIChatbot` initialization:
```python
chatbot = AIChatbot(database_url="your_database_url_here")
```
### Customizing Responses
Modify the response functions to change how the chatbot responds to different conversation types:
- `get_greeting_response()`
- `get_help_response()`
- `get_thanks_response()`
- `get_goodbye_response()`
## Troubleshooting
### Common Issues
1. **Database Connection Errors**: Check if your database URL is accessible and the endpoints are working
2. **Import Errors**: Make sure all dependencies are installed: `pip install -r requirements.txt`
3. **Port Issues**: If port 7860 is busy, Gradio will automatically use the next available port
### Testing Database Connection
You can test your database connection by running:
```python
import requests
response = requests.get("https://database-dhe2.onrender.com/faq?question=test")
print(response.status_code, response.json())
```
## File Structure
```
βββ app.py # Main application file
βββ requirements.txt # Python dependencies
βββ README.md # This documentation
```
## License
This project is open source and available under the MIT License.
## Support
If you encounter any issues:
1. Check the Hugging Face Space logs for error messages
2. Test your database endpoints manually
3. Verify all dependencies are correctly installed
4. Check that your database is accessible from the internet
## Contributing
Feel free to submit issues, feature requests, or pull requests to improve this chatbot!
|