Yoonc commited on
Commit
0bfb426
·
verified ·
1 Parent(s): 45ca50e

Update example.py

Browse files
Files changed (1) hide show
  1. example.py +21 -249
example.py CHANGED
@@ -1,18 +1,14 @@
1
  """
2
  Concept: Flask + HTML Integration - Spiritual Path Assessment Tool
3
-
4
  This app helps users discover which religious or spiritual path aligns with their
5
  beliefs, values, lifestyle, and background through an interactive questionnaire.
6
  """
7
- # cSpell:ignore jsonify
8
-
9
  from flask import Flask, render_template, request, jsonify, session, redirect, url_for
10
  import json
11
  import os
12
  import warnings
13
  from dotenv import load_dotenv
14
- import together
15
-
16
 
17
  warnings.filterwarnings("ignore")
18
  load_dotenv()
@@ -28,144 +24,35 @@ TOGETHER_API_KEY = os.getenv("TOGETHER_API_KEY")
28
  together.api_key = TOGETHER_API_KEY
29
  client = together if TOGETHER_API_KEY else None
30
 
31
-
32
  # Assessment Questions
33
  QUESTIONS = [
34
- {
35
- "id": 1,
36
- "question": "What is your view on the nature of the divine?",
37
- "options": {
38
- "One supreme God who created everything": {"christianity": 3, "islam": 3, "judaism": 3},
39
- "Multiple gods and goddesses": {"hinduism": 3, "paganism": 3},
40
- "A universal energy or force": {"buddhism": 2, "taoism": 3, "new_age": 3},
41
- "No divine being, focus on human potential": {"humanism": 3, "atheism": 3},
42
- "Uncertain or unknowable": {"agnosticism": 3}
43
- }
44
- },
45
- {
46
- "id": 2,
47
- "question": "How do you prefer to connect with spirituality?",
48
- "options": {
49
- "Through organized worship and community": {"christianity": 2, "islam": 2, "judaism": 2},
50
- "Through personal meditation and reflection": {"buddhism": 3, "hinduism": 2, "taoism": 2},
51
- "Through nature and natural cycles": {"paganism": 3, "indigenous": 3},
52
- "Through reason and philosophy": {"humanism": 2, "stoicism": 3},
53
- "I don't feel the need for spiritual connection": {"atheism": 3}
54
- }
55
- },
56
- {
57
- "id": 3,
58
- "question": "What is your belief about the afterlife?",
59
- "options": {
60
- "Heaven or Hell based on faith/deeds": {"christianity": 3, "islam": 3},
61
- "Reincarnation until enlightenment": {"hinduism": 3, "buddhism": 3},
62
- "Ancestral realm or spiritual world": {"indigenous": 2, "paganism": 2},
63
- "No afterlife, this life is all there is": {"atheism": 3, "humanism": 2},
64
- "Unsure or open to possibilities": {"agnosticism": 2, "new_age": 2}
65
- }
66
- },
67
- {
68
- "id": 4,
69
- "question": "What guides your moral and ethical decisions?",
70
- "options": {
71
- "Sacred texts and religious teachings": {"christianity": 3, "islam": 3, "judaism": 3},
72
- "Universal principles of compassion and mindfulness": {"buddhism": 3, "jainism": 3},
73
- "Harmony with nature and balance": {"taoism": 3, "indigenous": 2},
74
- "Reason, empathy, and human rights": {"humanism": 3, "secularism": 3},
75
- "Personal intuition and inner wisdom": {"new_age": 2, "spiritualism": 3}
76
- }
77
- },
78
- {
79
- "id": 5,
80
- "question": "What role does ritual or practice play in your life?",
81
- "options": {
82
- "Regular prayer and worship are essential": {"islam": 3, "christianity": 2, "judaism": 2},
83
- "Daily meditation or mindfulness practice": {"buddhism": 3, "hinduism": 2, "zen": 3},
84
- "Seasonal celebrations and ceremonies": {"paganism": 3, "wicca": 3},
85
- "Minimal to no ritual, prefer intellectual engagement": {"humanism": 2, "deism": 2},
86
- "Flexible, whatever feels meaningful to me": {"new_age": 2, "spiritual_not_religious": 3}
87
- }
88
- },
89
- {
90
- "id": 6,
91
- "question": "How do you view the relationship between humans and nature?",
92
- "options": {
93
- "Humans are stewards of God's creation": {"christianity": 2, "islam": 2, "judaism": 2},
94
- "All life is interconnected and sacred": {"buddhism": 2, "hinduism": 2, "jainism": 3},
95
- "Nature itself is divine": {"paganism": 3, "pantheism": 3, "indigenous": 3},
96
- "Nature follows natural laws we can understand": {"atheism": 2, "humanism": 2},
97
- "We should live in harmony with natural flow": {"taoism": 3, "shintoism": 2}
98
- }
99
- },
100
- {
101
- "id": 7,
102
- "question": "What is your view on suffering and its purpose?",
103
- "options": {
104
- "A test of faith or part of God's plan": {"christianity": 2, "islam": 2},
105
- "Result of attachment and desire": {"buddhism": 3, "stoicism": 2},
106
- "Karma from past actions": {"hinduism": 3, "sikhism": 2},
107
- "Random or result of natural causes": {"atheism": 3, "secular": 2},
108
- "An opportunity for growth and learning": {"new_age": 2, "spiritualism": 2}
109
- }
110
- },
111
- {
112
- "id": 8,
113
- "question": "How important is community in your spiritual life?",
114
- "options": {
115
- "Very important, prefer group worship": {"christianity": 2, "islam": 2, "sikhism": 3},
116
- "Somewhat important, but personal practice matters more": {"buddhism": 2, "hinduism": 2},
117
- "Community of like-minded seekers": {"paganism": 2, "unitarian": 3},
118
- "Not important, spirituality is personal": {"spiritual_not_religious": 3, "deism": 2},
119
- "Prefer secular community over religious": {"humanism": 2, "atheism": 2}
120
- }
121
- }
122
  ]
123
 
124
  # Religion Descriptions
125
  RELIGIONS = {
126
- "christianity": {"name": "Christianity", "description": "Faith in Jesus Christ emphasizing love, forgiveness, and salvation through grace.", "practices": "Prayer, Bible study, church, communion", "core_beliefs": "Trinity, salvation through Christ, eternal life"},
127
- "islam": {"name": "Islam", "description": "Submission to Allah through Prophet Muhammad's teachings and the Quran.", "practices": "Five daily prayers, Ramadan fasting, charity, Mecca pilgrimage", "core_beliefs": "One God (Allah), Muhammad as prophet, Day of Judgment"},
128
- "buddhism": {"name": "Buddhism", "description": "Path to enlightenment through mindfulness and compassion.", "practices": "Meditation, mindfulness, Eightfold Path", "core_beliefs": "Four Noble Truths, impermanence, ending suffering"},
129
- "hinduism": {"name": "Hinduism", "description": "Ancient tradition embracing diverse paths to spiritual realization.", "practices": "Yoga, meditation, puja, festivals", "core_beliefs": "Dharma, karma, reincarnation, moksha, multiple paths"},
130
- "judaism": {"name": "Judaism", "description": "Covenant with God through Torah and Jewish community.", "practices": "Shabbat, Torah study, prayer, kosher", "core_beliefs": "One God, Torah as divine law, ethical monotheism"},
131
- "taoism": {"name": "Taoism", "description": "Living in harmony with the Tao - the natural order.", "practices": "Meditation, tai chi, wu wei, simplicity", "core_beliefs": "Yin-yang balance, harmony with nature"},
132
- "paganism": {"name": "Modern Paganism", "description": "Nature-based spirituality honoring seasonal cycles.", "practices": "Seasonal celebrations, rituals, nature work", "core_beliefs": "Nature as sacred, multiple deities"},
133
- "humanism": {"name": "Secular Humanism", "description": "Ethics emphasizing human values and reason without supernatural beliefs.", "practices": "Critical thinking, ethical living, community service", "core_beliefs": "Human dignity, reason, science, secular ethics"},
134
- "atheism": {"name": "Atheism", "description": "Lack of belief in deities with naturalistic worldview.", "practices": "Evidence-based thinking, secular community", "core_beliefs": "No gods, natural explanations, this-life focus"},
135
- "agnosticism": {"name": "Agnosticism", "description": "Divine existence is unknown or unknowable.", "practices": "Philosophical inquiry, ethical living", "core_beliefs": "Uncertainty about divine, questions over answers"},
136
- "new_age": {"name": "New Age Spirituality", "description": "Eclectic approach emphasizing personal growth.", "practices": "Meditation, energy work, crystals, yoga", "core_beliefs": "Personal transformation, universal consciousness"},
137
- "spiritual_not_religious": {"name": "Spiritual But Not Religious", "description": "Personal spirituality without organized religion.", "practices": "Personal practices, meditation, self-reflection", "core_beliefs": "Individual journey, authenticity, diverse wisdom"},
138
- "sikhism": {"name": "Sikhism", "description": "One God emphasizing service, equality, and meditation.", "practices": "Prayer, meditation, community service, 5 Ks", "core_beliefs": "One God, equality, honest living, sharing"},
139
- "indigenous": {"name": "Indigenous Spirituality", "description": "Traditional practices honoring ancestors and land.", "practices": "Ceremonies, storytelling, seasonal rituals", "core_beliefs": "Land connection, ancestor veneration, reciprocity"}
140
  }
141
 
142
  def load_users():
143
- """Load users from JSON file"""
144
  if os.path.exists(USERS_FILE):
145
  with open(USERS_FILE, 'r') as f:
146
  return json.load(f)
147
  return {}
148
 
149
  def save_users(users):
150
- """Save users to JSON file"""
151
  with open(USERS_FILE, 'w') as f:
152
  json.dump(users, f, indent=2)
153
 
154
  def calculate_results(answers):
155
- """Calculate which spiritual paths align with user's answers"""
156
  scores = {}
157
-
158
  for answer in answers:
159
  question = next((q for q in QUESTIONS if q["id"] == answer["question_id"]), None)
160
  if question and answer["answer"] in question["options"]:
161
  points = question["options"][answer["answer"]]
162
  for religion, score in points.items():
163
  scores[religion] = scores.get(religion, 0) + score
164
-
165
- # Sort by score
166
  sorted_scores = sorted(scores.items(), key=lambda x: x[1], reverse=True)
167
-
168
- # Get top 3 recommendations
169
  recommendations = []
170
  for religion_key, score in sorted_scores[:3]:
171
  if religion_key in RELIGIONS:
@@ -173,176 +60,61 @@ def calculate_results(answers):
173
  religion_info["score"] = score
174
  religion_info["percentage"] = round((score / (len(answers) * 3)) * 100)
175
  recommendations.append(religion_info)
176
-
177
  return recommendations
178
 
179
- @app.route("/")
180
- def home():
181
- if 'username' not in session:
182
- return redirect(url_for('login'))
183
-
184
- users = load_users()
185
- user_data = users.get(session['username'], {})
186
- has_results = 'results' in user_data and user_data['results']
187
-
188
- return render_template(
189
- "index.html",
190
- title="Spiritual Path Finder",
191
- message=f"Welcome, {session['username']}! 🌟",
192
- username=session['username'],
193
- logged_in=True,
194
- questions=QUESTIONS,
195
- has_results=has_results,
196
- results=user_data.get('results', []) if has_results else []
197
- )
198
-
199
- @app.route("/login", methods=["GET", "POST"])
200
- def login():
201
- if request.method == "POST":
202
- data = request.json
203
- username = data.get('username', '').strip()
204
- password = data.get('password', '')
205
-
206
- users = load_users()
207
-
208
- if username in users and users[username]['password'] == password:
209
- session['username'] = username
210
- return jsonify({"success": True})
211
- else:
212
- return jsonify({"success": False, "message": "Invalid credentials!"})
213
-
214
- return render_template("index.html", logged_in=False, is_signup=False)
215
-
216
- @app.route("/signup", methods=["GET", "POST"])
217
- def signup():
218
- if request.method == "POST":
219
- data = request.json
220
- username = data.get('username', '').strip()
221
- password = data.get('password', '')
222
-
223
- users = load_users()
224
-
225
- if username in users:
226
- return jsonify({"success": False, "message": "Username already exists!"})
227
-
228
- if not username or not password:
229
- return jsonify({"success": False, "message": "Username and password required!"})
230
-
231
- # Create new user
232
- users[username] = {
233
- 'password': password,
234
- 'answers': [],
235
- 'results': []
236
- }
237
- save_users(users)
238
- session['username'] = username
239
- return jsonify({"success": True})
240
-
241
- return render_template("index.html", logged_in=False, is_signup=True)
242
-
243
- @app.route("/logout")
244
- def logout():
245
- session.pop('username', None)
246
- return redirect(url_for('login'))
247
-
248
- @app.route("/submit_assessment", methods=["POST"])
249
- def submit_assessment():
250
- if 'username' not in session:
251
- return jsonify({"success": False, "message": "Not logged in"})
252
-
253
- data = request.json
254
- answers = data.get('answers', [])
255
-
256
- if len(answers) != len(QUESTIONS):
257
- return jsonify({"success": False, "message": "Please answer all questions!"})
258
-
259
- # Calculate results
260
- results = calculate_results(answers)
261
-
262
- # Save to user data
263
- users = load_users()
264
- if session['username'] in users:
265
- users[session['username']]['answers'] = answers
266
- users[session['username']]['results'] = results
267
- save_users(users)
268
-
269
- return jsonify({"success": True, "results": results})
270
-
271
- return jsonify({"success": False, "message": "User not found"})
272
-
273
- @app.route("/reset_assessment", methods=["POST"])
274
- def reset_assessment():
275
- if 'username' not in session:
276
- return jsonify({"success": False, "message": "Not logged in"})
277
-
278
- users = load_users()
279
- if session['username'] in users:
280
- users[session['username']]['answers'] = []
281
- users[session['username']]['results'] = []
282
- save_users(users)
283
- return jsonify({"success": True})
284
-
285
- return jsonify({"success": False, "message": "User not found"})
286
 
287
  @app.route("/chat", methods=["POST"])
288
  def chat():
289
  if 'username' not in session:
290
  return jsonify({"success": False, "message": "Not logged in"})
291
-
292
  if not client:
293
  return jsonify({"success": False, "message": "Chat service not configured. Please set TOGETHER_API_KEY."})
294
-
295
  data = request.json
296
  user_message = data.get('message', '').strip()
297
  religion_name = data.get('religion', '')
298
  chat_history = data.get('history', [])
299
-
300
  if not user_message or not religion_name:
301
  return jsonify({"success": False, "message": "Message and religion required"})
302
-
303
  # Find religion details
304
  religion_data = None
305
  for key, value in RELIGIONS.items():
306
  if value['name'] == religion_name:
307
  religion_data = value
308
  break
309
-
310
  if not religion_data:
311
  return jsonify({"success": False, "message": "Religion not found"})
312
-
313
  # Create context-aware system prompt
314
  system_prompt = f"""You're a spiritual guide for {religion_data['name']}.
315
  Info: {religion_data['description']} | Practices: {religion_data['practices']} | Beliefs: {religion_data['core_beliefs']}
316
  Rules: Keep 30-50 words, be respectful, use * for bullet points (format: "Text: * item * item"), answer directly."""
317
 
318
- # Build conversation history
319
  messages = [{"role": "system", "content": system_prompt}]
320
-
321
- # Add chat history (last 5 messages for context)
322
  for msg in chat_history[-5:]:
323
  messages.append({"role": msg["role"], "content": msg["content"]})
324
-
325
- # Add current user message
326
  messages.append({"role": "user", "content": user_message})
327
-
328
- try:
329
- # Call Together API with limited tokens for concise responses
330
- response = together.chat.completions.create(
331
- model="meta-llama/Meta-Llama-3-8B-Instruct-Lite",
332
- messages=messages,
333
- max_tokens=80,
334
- temperature=0.7,
335
- )
336
 
337
-
338
- bot_response = response.output[0].content[0].text
339
-
340
-
 
 
 
 
 
341
  return jsonify({
342
  "success": True,
343
  "response": bot_response
344
  })
345
-
346
  except Exception as e:
347
  return jsonify({
348
  "success": False,
 
1
  """
2
  Concept: Flask + HTML Integration - Spiritual Path Assessment Tool
 
3
  This app helps users discover which religious or spiritual path aligns with their
4
  beliefs, values, lifestyle, and background through an interactive questionnaire.
5
  """
 
 
6
  from flask import Flask, render_template, request, jsonify, session, redirect, url_for
7
  import json
8
  import os
9
  import warnings
10
  from dotenv import load_dotenv
11
+ import together # Updated import
 
12
 
13
  warnings.filterwarnings("ignore")
14
  load_dotenv()
 
24
  together.api_key = TOGETHER_API_KEY
25
  client = together if TOGETHER_API_KEY else None
26
 
 
27
  # Assessment Questions
28
  QUESTIONS = [
29
+ # ... keep all your questions exactly as before ...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  ]
31
 
32
  # Religion Descriptions
33
  RELIGIONS = {
34
+ # ... keep all your religions exactly as before ...
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  }
36
 
37
  def load_users():
 
38
  if os.path.exists(USERS_FILE):
39
  with open(USERS_FILE, 'r') as f:
40
  return json.load(f)
41
  return {}
42
 
43
  def save_users(users):
 
44
  with open(USERS_FILE, 'w') as f:
45
  json.dump(users, f, indent=2)
46
 
47
  def calculate_results(answers):
 
48
  scores = {}
 
49
  for answer in answers:
50
  question = next((q for q in QUESTIONS if q["id"] == answer["question_id"]), None)
51
  if question and answer["answer"] in question["options"]:
52
  points = question["options"][answer["answer"]]
53
  for religion, score in points.items():
54
  scores[religion] = scores.get(religion, 0) + score
 
 
55
  sorted_scores = sorted(scores.items(), key=lambda x: x[1], reverse=True)
 
 
56
  recommendations = []
57
  for religion_key, score in sorted_scores[:3]:
58
  if religion_key in RELIGIONS:
 
60
  religion_info["score"] = score
61
  religion_info["percentage"] = round((score / (len(answers) * 3)) * 100)
62
  recommendations.append(religion_info)
 
63
  return recommendations
64
 
65
+ # --- Flask routes (login, signup, home, logout, assessment routes) ---
66
+ # Keep all your existing routes unchanged
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
 
68
  @app.route("/chat", methods=["POST"])
69
  def chat():
70
  if 'username' not in session:
71
  return jsonify({"success": False, "message": "Not logged in"})
72
+
73
  if not client:
74
  return jsonify({"success": False, "message": "Chat service not configured. Please set TOGETHER_API_KEY."})
75
+
76
  data = request.json
77
  user_message = data.get('message', '').strip()
78
  religion_name = data.get('religion', '')
79
  chat_history = data.get('history', [])
80
+
81
  if not user_message or not religion_name:
82
  return jsonify({"success": False, "message": "Message and religion required"})
83
+
84
  # Find religion details
85
  religion_data = None
86
  for key, value in RELIGIONS.items():
87
  if value['name'] == religion_name:
88
  religion_data = value
89
  break
90
+
91
  if not religion_data:
92
  return jsonify({"success": False, "message": "Religion not found"})
93
+
94
  # Create context-aware system prompt
95
  system_prompt = f"""You're a spiritual guide for {religion_data['name']}.
96
  Info: {religion_data['description']} | Practices: {religion_data['practices']} | Beliefs: {religion_data['core_beliefs']}
97
  Rules: Keep 30-50 words, be respectful, use * for bullet points (format: "Text: * item * item"), answer directly."""
98
 
 
99
  messages = [{"role": "system", "content": system_prompt}]
 
 
100
  for msg in chat_history[-5:]:
101
  messages.append({"role": msg["role"], "content": msg["content"]})
 
 
102
  messages.append({"role": "user", "content": user_message})
 
 
 
 
 
 
 
 
 
103
 
104
+ try:
105
+ response = together.chat.completions.create(
106
+ model="meta-llama/Meta-Llama-3-8B-Instruct-Lite",
107
+ messages=messages,
108
+ max_tokens=80,
109
+ temperature=0.7,
110
+ )
111
+
112
+ bot_response = response.output[0].content[0].text # ✅ Correctly indented
113
  return jsonify({
114
  "success": True,
115
  "response": bot_response
116
  })
117
+
118
  except Exception as e:
119
  return jsonify({
120
  "success": False,