Skip to content

Commit 31af9f6

Browse files
committedJun 8, 2024
inhertance some parts
1 parent 2aee827 commit 31af9f6

38 files changed

+2002
-598
lines changed
 

‎.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
TYpackges/

‎app.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,6 @@
1515

1616

1717
if __name__ == "__main__" :
18-
app.run(debug=True,port=5000)
18+
app.run(debug=True,port=5000,host="0.0.0.0")
1919

2020
# chatBot\Scripts\activate

‎chatbot_model.h5

697 KB
Binary file not shown.

‎classes.pkl

59 Bytes
Binary file not shown.

‎instance/tytopya.db

-32 KB
Binary file not shown.

‎requirements.txt

4.41 KB
Binary file not shown.

‎requirments.txt

-13
This file was deleted.

‎research/tytopya research.pdf

335 KB
Binary file not shown.

‎webapp/__init__.py

+6
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,9 @@ def create_app():
2727
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True
2828

2929
from .routes import routes1
30+
from .auth import auth1
31+
from .summarization import summarization1
32+
from .chatbot import chatbot1
3033
from .admin import adminnbp, MyAdminIndexView,MyModelView,UserModelView
3134
from .models import User,Question,Texts,Response,Summaries,Feedbacks
3235

@@ -46,6 +49,9 @@ def create_app():
4649

4750
app.register_blueprint(adminnbp)
4851
app.register_blueprint(routes1)
52+
app.register_blueprint(auth1)
53+
app.register_blueprint(chatbot1)
54+
app.register_blueprint(summarization1)
4955

5056
with app.app_context():
5157
db.create_all()
386 Bytes
Binary file not shown.
-191 Bytes
Binary file not shown.
4.1 KB
Binary file not shown.
5.78 KB
Binary file not shown.
148 Bytes
Binary file not shown.
-12.8 KB
Binary file not shown.
Binary file not shown.

‎webapp/admin.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
from flask import Blueprint
22
from flask_admin.contrib.sqla import ModelView
33
from flask_admin import AdminIndexView
4-
from .models import User,Question,Feedbacks,Response,Texts,Summaries
5-
from webapp import db,bcrypt
4+
5+
from webapp import bcrypt
66
from flask_login import current_user
77

88

‎webapp/auth.py

+70
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
2+
from webapp.models import User
3+
from flask import render_template ,url_for,flash ,redirect,request
4+
from webapp.forms import RegistrationForm , LoginForm
5+
from webapp import bcrypt,db
6+
from flask_login import login_user,current_user,logout_user
7+
from flask import Blueprint
8+
9+
10+
11+
12+
13+
auth1 = Blueprint("auth1",__name__)
14+
15+
# start login logout register
16+
@auth1.post("/register")
17+
@auth1.get("/register")
18+
def register():
19+
if current_user.is_authenticated:
20+
return redirect(url_for('summarization1.summary'))
21+
form = RegistrationForm()
22+
23+
if form.validate_on_submit():
24+
hash_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8')
25+
user = User(fname=form.fname.data,lname=form.lname.data,username=form.username.data,email=form.email.data,password=hash_password)
26+
27+
28+
db.session.add(user)
29+
db.session.commit()
30+
flash(f"Account created successfully for {form.username.data}", "success")
31+
return redirect(url_for("auth1.login"))
32+
return render_template("register.html", title="Register", form=form)
33+
34+
35+
@auth1.get("/login")
36+
@auth1.post("/login")
37+
def login():
38+
if current_user.is_authenticated:
39+
return redirect(url_for('routes1.summary'))
40+
form = LoginForm()
41+
if form.validate_on_submit():
42+
user = User.query.filter_by(email=form.email.data).first()
43+
if (user and bcrypt.check_password_hash(user.password , form.password.data)):
44+
login_user(user,remember=form.remember.data)
45+
next_page = request.args.get('next')
46+
flash("You have been logged in!", "success")
47+
return redirect(next_page) if next_page else redirect(url_for("routes1.home"))
48+
else:
49+
flash("Login Unsuccessful. Please check credentials", "danger")
50+
return render_template("login.html", title="Login", form=form)
51+
52+
53+
54+
55+
@auth1.route("/logout")
56+
def logout():
57+
logout_user()
58+
return redirect(url_for("routes1.home"))
59+
60+
# end login logout register
61+
62+
63+
64+
65+
66+
67+
68+
69+
70+

‎webapp/chatbot.py

+120
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
# chat bot code
2+
import random
3+
import json
4+
import pickle
5+
import numpy as np
6+
import nltk
7+
8+
from nltk.stem import WordNetLemmatizer
9+
from keras.models import load_model
10+
11+
lemmatizer = WordNetLemmatizer()
12+
intents = json.loads(open("webapp/intents2.json").read())
13+
14+
15+
16+
# paterns
17+
words = pickle.load(open('words.pkl', 'rb'))
18+
19+
# tags
20+
classes = pickle.load(open('classes.pkl', 'rb'))
21+
22+
model1 = load_model('chatbot_model.h5')
23+
24+
25+
26+
def clean_up_sentence(sentence):
27+
28+
# Tokenize the sentence into individual words
29+
sentence_words = nltk.word_tokenize(sentence)
30+
31+
# Lemmatize each word to its base form
32+
sentence_words = [lemmatizer.lemmatize(word) for word in sentence_words]
33+
return sentence_words
34+
35+
36+
def bag_of_words(sentence):
37+
# Clean up the sentence
38+
sentence_words = clean_up_sentence(sentence)
39+
40+
# Create a bag of words representation
41+
bag = [0] * len(words)
42+
for w in sentence_words:
43+
for i, word in enumerate(words):
44+
if word == w:
45+
bag[i] = 1
46+
47+
return np.array(bag)
48+
49+
50+
def predict_class(sentence):
51+
# Convert the sentence into a bag of words
52+
bow = bag_of_words(sentence)
53+
54+
# Predict the intent using the loaded model
55+
res = model1.predict(np.array([bow]))[0]
56+
57+
ERROR_THRESHOLD = 0.25
58+
# Filter out predictions below the error threshold
59+
results = [[i, r] for i, r in enumerate(res) if r > ERROR_THRESHOLD]
60+
61+
# Sort the results by probability in descending order
62+
results.sort(key=lambda x: x[1], reverse=True)
63+
64+
return_list = []
65+
for r in results:
66+
# Get the corresponding intent and its probability
67+
return_list.append({'intent': classes[r[0]], 'probability': str(r[1])})
68+
69+
return return_list
70+
71+
72+
def get_response(ints, intents_json):
73+
if not ints or not isinstance(ints[0], dict) or 'intent' not in ints[0]:
74+
return "Sorry, I didn't understand that. Could you please rephrase?"
75+
76+
tag = ints[0]['intent']
77+
list_of_intents = intents_json['intents']
78+
for i in list_of_intents:
79+
if i['tag'] == tag:
80+
return random.choice(i['responses'])
81+
return "Sorry, I couldn't find an appropriate response."
82+
83+
84+
85+
86+
from webapp.models import Question,Response
87+
from flask import request,jsonify
88+
89+
from webapp import db
90+
from flask_login import current_user
91+
from flask import Blueprint
92+
93+
94+
95+
96+
chatbot1= Blueprint("chatbot1",__name__)
97+
98+
@chatbot1.post('/predictChat', endpoint='predictChat')
99+
@chatbot1.get('/predictChat', endpoint='predictChat')
100+
def predictChat():
101+
text2=request.get_json().get("message")
102+
print("======================================")
103+
print(text2)
104+
print(type(text2))
105+
print("======================================")
106+
ints = predict_class(text2)
107+
response = get_response(ints, intents)
108+
if current_user.is_authenticated:
109+
question = Question(data=text2, user_id=current_user.id)
110+
res = Response( data=response, user_id=current_user.id)
111+
try:
112+
113+
db.session.add(question)
114+
db.session.add(res)
115+
db.session.commit()
116+
except Exception as e:
117+
# Handle the exception, e.g., log the error
118+
print(f"Error occurred: {e}")
119+
message={"answer":response}
120+
return jsonify(message)

0 commit comments

Comments
 (0)
Please sign in to comment.