-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
103 lines (84 loc) · 3.66 KB
/
app.py
File metadata and controls
103 lines (84 loc) · 3.66 KB
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
from flask import Flask, render_template, request, jsonify
import json
import string
app = Flask(__name__)
# --- OPTIMIZATION 1: Add a set of "stop words" ---
STOP_WORDS = set([
"a", "an", "and", "are", "as", "at", "be", "by", "for", "from", "has", "he",
"in", "is", "it", "its", "of", "on", "that", "the", "to", "was", "were",
"will", "with", "what", "when", "where", "how", "who", "which", "i", "you",
"me", "my", "me", "please", "can", "tell"
])
# --- OPTIMLayers of the Earth's atmosphere. OPTIMIZATION 2: Load data safely ---
def load_faqs():
"""
Loads FAQs from the JSON file safely.
Now expects an object: {"Category": [questions...]}
"""
try:
with open('data/faq.json') as f:
return json.load(f)
except FileNotFoundError:
print("ERROR: data/faq.json file not found.")
return {} # Return empty dict on error
except json.JSONDecodeError:
print("ERROR: Could not read data/faq.json. Check for typos.")
return {} # Return empty dict on error
# Load the FAQs once when the app starts
faqs = load_faqs()
# --- *** NEW FUNCTION *** ---
# This new route sends all the structured FAQ data to the frontend
@app.route("/get-initial-data")
def get_initial_data():
"""
Sends the entire FAQ structure to the frontend
so it can build the category and question buttons.
"""
return jsonify(faqs)
# --- *** MODIFIED FUNCTION *** ---
# get_answer() is now updated to work with the new data structure
def get_answer(question):
"""
Finds the best answer by keyword matching from the new
object-based FAQ structure.
"""
if not faqs:
return "I'm sorry, my knowledge base is empty. Please contact the administration."
# --- Tokenize the user's question ---
question_lower = question.lower()
question_no_punct = question_lower.translate(str.maketrans('', '', string.punctuation))
user_tokens = set(word for word in question_no_punct.split() if word not in STOP_WORDS)
if not user_tokens:
return "I'm sorry, I don't understand the question. Could you be more specific?"
# --- Find the best match ---
best_match_score = 0
best_answer = "I'm sorry, I don't have the answer to that. Please contact the administration."
# --- MODIFIED LOOP ---
# Now we loop through each category, then each question in that category
for category, questions_list in faqs.items():
for faq in questions_list:
# Tokenize the FAQ question (same process)
faq_question_lower = faq['question'].lower()
faq_question_no_punct = faq_question_lower.translate(str.maketrans('', '', string.punctuation))
faq_tokens = set(word for word in faq_question_no_punct.split() if word not in STOP_WORDS)
# Calculate match score (number of common words)
match_score = len(user_tokens.intersection(faq_tokens))
if match_score > best_match_score:
best_match_score = match_score
best_answer = faq['answer']
return best_answer
# Route to render the main chat page
@app.route("/")
def index():
return render_template("index.html")
# API endpoint to handle user questions asynchronously
@app.route("/ask", methods=["POST"])
def ask():
user_message = request.form.get('message', '')
if not user_message:
return jsonify({'answer': 'Please send a message.'})
bot_answer = get_answer(user_message)
return jsonify({'answer': bot_answer})
# Run the app in debug mode when executed directly
if __name__ == "__main__":
app.run(debug=True)