**MentorWise AI Chatbot Code**
=====================================
**Overview**
------------
This code builds a basic AI chatbot using Python and its libraries, focusing on educational and career assistance. The chatbot will provide guidance and resources for students and freshers, helping them with exam preparation, interview preparation, internships, and project development.
**Libraries and Dependencies**
-----------------------------
* **Python 3.8+**
* **Natural Language Processing (NLP)**: `nltk`, `spaCy`
* **Machine Learning**: `scikit-learn`, `TensorFlow`
* **Web Development**: `Flask`
* **Database**: `MongoDB`
**Code Structure**
-----------------
### **Section 1: Import Libraries and Initialize**
```python
import nltk
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
import json
import pickle
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Activation, Dropout
from keras.optimizers import SGD
import random
import tf
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
# Initialize NLTK data
nltk.download('punkt')
nltk.download('wordnet')
```
### **Section 2: Load Data and Preprocess**
```python
# Load data from JSON file
with open('intents.json') as file:
data = json.load(file)
# Preprocess data
words = []
labels = []
docs_x = []
docs_y = []
for intent in data['intents']:
for pattern in intent['patterns']:
wrds = nltk.word_tokenize(pattern)
words.extend(wrds)
docs_x.append(wrds)
docs_y.append(intent['tag'])
if intent['tag'] not in labels:
labels.append(intent['tag'])
words = [lemmatizer.lemmatize(w.lower()) for w in words if w != "?"]
words = sorted(list(set(words)))
labels = sorted(labels)
# Create pickle files for words and labels
pickle.dump(words, open('words.pkl', 'wb'))
pickle.dump(labels, open('labels.pkl', 'wb'))
```
### **Section 3: Create Training Data**
```python
# Create training data
training = []
output_empty = [0] * len(labels)
for x, doc in enumerate(docs_x):
bag = []
wrds = [lemmatizer.lemmatize(w.lower()) for w in doc]
for w in words:
if w in wrds:
bag.append(1)
else:
bag.append(0)
output_row = list(output_empty)
output_row[labels.index(docs_y[x])] = 1
training.append([bag, output_row])
random.shuffle(training)
training = np.array(training)
train_x = list(training[:, 0])
train_y = list(training[:, 1])
# Create tokenizer and sequence padding
tokenizer = Tokenizer()
tokenizer.fit_on_texts(train_x)
sequences = tokenizer.texts_to_sequences(train_x)
padded_sequences = pad_sequences(sequences, maxlen=50)
# One-hot encoding for labels
labels_onehot = []
for label in train_y:
onehot = [0] * len(labels)
onehot[labels.index(labels[np.argmax(label)])] = 1
labels_onehot.append(onehot)
# Convert to numpy arrays
train_x = np.array(padded_sequences)
train_y = np.array(labels_onehot)
```
### **Section 4: Build and Compile the Model**
```python
# Build the model
model = Sequential()
model.add(Dense(128, input_shape=(50,), activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(len(labels), activation='softmax'))
# Compile the model
sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
# Train the model
hist = model.fit(np.array(train_x), np.array(train_y), epochs=200, batch_size=5, verbose=1)
```
### **Section 5: Create Chatbot Interface**
```python
from flask import Flask, render_template, request
app = Flask(__name__)
# Load the model and words
model = tf.keras.models.load_model('MentorWiseAI.h5')
words = pickle.load(open('words.pkl', 'rb'))
# Define a function to clean and tokenize input
def clean_input(input_text):
input_text = input_text.lower()
wrds = nltk.word_tokenize(input_text)
input_text = [lemmatizer.lemmatize(w) for w in wrds]
input_text = [w for w in input_text if w in words]
sequence = tokenizer.texts_to_sequences([input_text])
padded_sequence = pad_sequences(sequence, maxlen=50)
return padded_sequence
# Define a function to get response
def get_response(input_text):
input_sequence = clean_input(input_text)
prediction = model.predict(input_sequence)
tag = labels[np.argmax(prediction)]
for intent in data['intents']:
if intent['tag'] == tag:
return random.choice(intent['responses'])
# Define a route for chatbot interface
@app.route('/')
def index():
return render_template('index.html')
# Define a route for chatbot response
@app.route('/chat', methods=['POST'])
def chat():
input_text = request.form['input_text']
response = get_response(input_text)
return response
if __name__ == '__main__':
app.run(debug=True)
```
**Integrating Free Courses, Internships, Projects, and Resources**
-----------------------------------------------------------
To integrate free courses, internships, projects, and resources, you can use APIs from platforms like:
* Coursera
* edX
* Internshala
* GitHub
You can create a database to store information about these resources and use it to provide relevant suggestions to users.
**Generating High-Quality Photos and Videos**
---------------------------------------------
To generate high-quality photos and videos, you can use libraries like:
* **Deep Dream Generator**: A Python library for generating surreal and dreamlike images.
* **StyleGAN**: A Python library for generating high-quality images using Generative Adversarial Networks (GANs).
You can integrate these libraries into your chatbot to generate images and videos based on user input.
### **Example Use Cases**
* A student asks the chatbot, "I'm preparing for a machine learning interview. Can you provide some resources?"
* The chatbot responds, "Here are some free courses on machine learning: [list of courses]. You can also check out this project on GitHub: [link to project]."
* A fresher asks the chatbot, "I'm interested in data science. Can you suggest some internships?"
* The chatbot responds, "Here are some internships in data science: [list of internships]. You can also check out this course on data science: [link to course]."
### **Future Development**
* Integrate more libraries and APIs to provide a wider range of resources and services.
* Improve the chatbot's conversational flow and response accuracy.
* Develop a mobile app for the chatbot to reach a wider audience.
By following this code and integrating the suggested libraries and APIs, you can build a comprehensive AI chatbot like MentorWise AI that provides valuable resources and guidance to students and freshers.