from flask import render_template, request, Blueprint
from flaskblog.models import Post

main = Blueprint('main', __name__)

import pandas as pd 
import pickle
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
import joblib
import pickle

@main.route("/")
@main.route("/home")
def home():
    page = request.args.get('page', 1, type=int)
    posts = Post.query.order_by(Post.date_posted.desc()).paginate(page=page, per_page=5)
    return render_template('home.html', posts=posts)

filename = 'nlp_model.pkl'
clf = pickle.load(open(filename, 'rb'))
cv=pickle.load(open('tranform.pkl','rb')) 

@main.route("/about")
def about():
    return render_template('about.html', title='About')
@main.route('/predict',methods=['POST'])
def predict():
 #    df= pd.read_csv("spam.csv", encoding="latin-1")
 #    df.drop(['Unnamed: 2', 'Unnamed: 3', 'Unnamed: 4'], axis=1, inplace=True)
	# # Features and Labels
 #    df['label'] = df['class'].map({'ham': 0, 'spam': 1})
 #    X = df['message']
 #    y = df['label']
	
	# # Extract Feature With CountVectorizer
 #    cv = CountVectorizer()
 #    X = cv.fit_transform(X) # Fit the Data
   
 #    pickle.dump(cv, open('tranform.pkl', 'wb'))
   
   
	# from sklearn.model_selection import train_test_split
	# X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)
	# #Naive Bayes Classifier
	# from sklearn.naive_bayes import MultinomialNB

	# clf = MultinomialNB()
	# clf.fit(X_train,y_train)
	# clf.score(X_test,y_test)
 #    filename = 'nlp_model.pkl'
 #    pickle.dump(clf, open(filename, 'wb'))
    
	# Alternative Usage of Saved Model
	# joblib.dump(clf, 'NB_spam_model.pkl')
	# NB_spam_model = open('NB_spam_model.pkl','rb')
	# clf = joblib.load(NB_spam_model)

	if request.method == 'POST':
		message = request.form['message']
		data = [message]
		vect = cv.transform(data).toarray()
		my_prediction = clf.predict(vect)
	if my_prediction==1:
		return render_template('1.html')
	else:
		return render_template('0.html')

