-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
205 lines (159 loc) · 6.64 KB
/
app.py
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
import pandas as pd
import numpy as np
import nltk
import string
import mysql.connector
from flask import Flask, render_template, request, redirect, url_for
from nltk.tokenize import word_tokenize
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
app = Flask(__name__)
app.config['STATIC_FOLDER']='static'
mysql_config = {
'host':'localhost',
'user':'root',
'password':'@dm1nr00t123',
'database':'dbkabuuta'
}
connection = mysql.connector.connect(**mysql_config)
dataset_query = "SELECT * FROM dataset"
# Preprocessing
def preprocess_data(text):
if isinstance(text, str):
# Mengonversi seluruh teks menjadi huruf kecil
text = text.lower()
# Tokenisasi kata
tokens = word_tokenize(text)
processed_data = ' '.join(tokens)
return processed_data
else:
return ''
import string
def preprocess_text(text):
if isinstance(text, str):
# Menghapus tanda baca
text = text.translate(str.maketrans("", "", string.punctuation))
# Mengonversi seluruh teks menjadi huruf kecil
text = text.lower()
# Tokenisasi kata
tokens = word_tokenize(text)
# Join kembali token-token untuk membentuk teks yang telah diproses
processed_text = ' '.join(tokens)
return processed_text
else:
return ''
@app.route("/")
@app.route("/index")
def index():
return render_template("index.html")
@app.route("/Qas")
def Qas():
return render_template("question.html")
@app.route("/Answer", methods=['POST'])
def Answer():
# Membaca dataset
dataset = pd.read_sql(dataset_query, connection)
user_question = request.form['question']
preprocessed_user_question = preprocess_text(user_question)
print(preprocessed_user_question)
dataset['data'] = dataset['data'].apply(preprocess_data)
#code dari https://github.com/nikitaa30/Content-based-Recommender-System/blob/master/recommender_system.py
vectorizer = TfidfVectorizer(ngram_range=(1, 2))
vectors = vectorizer.fit_transform([preprocessed_user_question] + list(dataset['data']))
print("vectors: ", vectors)
similarities = cosine_similarity(vectors)
print("similarities:", similarities)
# Menggunakan np.argsort() untuk mendapatkan indeks yang diurutkan
sorted_indices = np.argsort(similarities[0])[::-1]
batas_similarity = 0.7
most_similar_idx = next((idx for idx in sorted_indices if similarities[0, idx] >= batas_similarity), None)
# Mencari indeks terbaik yang bukan indeks pertanyaan pengguna
most_similar_idx = next(idx for idx in sorted_indices if idx != 0)
mendekati_similar_idx = sorted_indices[1:8] # Mengambil 7 indeks
print("most_similar_idx:", most_similar_idx)
print("mendekati_similar_idx:", mendekati_similar_idx)
# Memastikan best_answer tidak muncul di dalam mendekati_similar_answers
if most_similar_idx in mendekati_similar_idx:
mendekati_similar_idx = mendekati_similar_idx[1:]
if most_similar_idx is not None:
best_answer = dataset.iloc[most_similar_idx]['data']
mendekati_similar_answers = dataset.iloc[mendekati_similar_idx]['data'].tolist()
return render_template('Answer.html', user_question=user_question, preprocessed_user_question=preprocessed_user_question, best_answer=best_answer, mendekati_similar_answers=mendekati_similar_answers)
else:
return f"Maaf, tidak ada jawaban atau jawaban mendekati untuk pertanyaan: {user_question}"
@app.route("/Artikel")
def Artikel():
return render_template("Artikel.html")
@app.route("/AboutUs")
def AboutUs():
return render_template("AboutUs.html")
@app.route("/view_data")
def view_data():
try:
# Mengambil data dari MySQL
connection = mysql.connector.connect(**mysql_config)
dataset_query = "SELECT * FROM dataset"
dataset = pd.read_sql(dataset_query, connection)
connection.close()
dataset = dataset.fillna('NA')
return render_template("view_data.html", dataset=dataset)
except Exception as e:
print("Error:", str(e))
# Atau berikan pesan kesalahan umum.
return render_template("view_data.html", dataset=pd.DataFrame())
@app.route("/add_data", methods=['GET', 'POST'])
def add_data():
try:
if request.method == 'POST':
# Mengambil data dari formulir
new_id = int(request.form['new_id'])
print("Nilai new_id:", new_id)
new_data = request.form['new_data']
# Menambahkan data ke MySQL
connection = mysql.connector.connect(**mysql_config)
cursor = connection.cursor()
query = "INSERT INTO dataset (id, data) VALUES (%s, %s)"
cursor.execute(query, (new_id, new_data,))
connection.commit()
connection.close()
return redirect(url_for('view_data'))
except ValueError as ve:
print(f"Error: {ve}. Input value: {request.form['new_id']}")
# Atau berikan pesan kesalahan kepada pengguna, misalnya:
# flash("Error: ID or data is not a valid integer.")
except Exception as e:
print("Error:", str(e))
# Atau berikan pesan kesalahan umum.
return render_template("add_data.html")
@app.route("/edit_data/<int:data_id>", methods=['GET', 'POST'])
def edit_data(data_id):
# Mengambil data dari MySQL berdasarkan ID
connection = mysql.connector.connect(**mysql_config)
query = "SELECT * FROM dataset WHERE id = %s"
data = pd.read_sql_query(query, connection, params=(data_id,))
connection.close()
if request.method == 'POST':
# Mengambil data yang diedit dari formulir
edited_id = request.form['edited_id']
edited_data = request.form['edited_data']
# Memperbarui data di MySQL
connection = mysql.connector.connect(**mysql_config)
cursor = connection.cursor()
query = "UPDATE dataset SET id = %s, data = %s WHERE id = %s"
cursor.execute(query, (edited_id, edited_data, data_id))
connection.commit()
connection.close()
return redirect(url_for('view_data'))
return render_template("edit_data.html", data=data.iloc[0])
@app.route("/delete_data/<int:data_id>")
def delete_data(data_id):
# Menghapus data dari MySQL berdasarkan ID
connection = mysql.connector.connect(**mysql_config)
cursor = connection.cursor()
query = "DELETE FROM dataset WHERE id = %s"
cursor.execute(query, (data_id,))
connection.commit()
connection.close()
return redirect(url_for('view_data'))
if __name__ == '__main__':
app.run(debug=True)