Yoonc commited on
Commit
d35f2ae
·
verified ·
1 Parent(s): 83517c2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +164 -199
app.py CHANGED
@@ -1,16 +1,18 @@
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
12
 
13
- warnings.filterwarnings("ignore")
14
  load_dotenv()
15
 
16
  app = Flask(__name__)
@@ -21,190 +23,145 @@ USERS_FILE = 'users_data.json'
21
 
22
  # Together API for chatbot
23
  TOGETHER_API_KEY = os.getenv("TOGETHER_API_KEY")
24
- together.api_key = TOGETHER_API_KEY
25
- client = together if TOGETHER_API_KEY else None
26
 
27
  # Assessment Questions
28
  QUESTIONS = [
29
  {
30
  "id": 1,
31
- "question": "What is your view on the existence of God or a higher power?",
32
  "options": {
33
- "One supreme God": {"Christianity": 3, "Islam": 3, "Judaism": 3, "Sikhism": 3},
34
- "Multiple gods": {"Hinduism": 3, "Ancient Greek": 3, "Norse": 3},
35
- "Spiritual force/energy": {"Buddhism": 2, "Taoism": 3, "New Age": 3},
36
- "Uncertain/Agnostic": {"Secular Humanism": 3, "Buddhism": 1},
37
- "No God (Atheist)": {"Secular Humanism": 3}
38
  }
39
  },
40
  {
41
  "id": 2,
42
- "question": "How do you prefer to connect with the divine or spiritual realm?",
43
  "options": {
44
- "Organized worship services": {"Christianity": 3, "Islam": 3, "Judaism": 3},
45
- "Personal meditation": {"Buddhism": 3, "Hinduism": 2, "New Age": 2},
46
- "Nature and environment": {"Taoism": 3, "Wicca": 3, "Indigenous": 3},
47
- "Study and reflection": {"Judaism": 2, "Secular Humanism": 3},
48
- "No spiritual practice": {"Secular Humanism": 3}
49
  }
50
  },
51
  {
52
  "id": 3,
53
- "question": "What role should religious texts play in your life?",
54
  "options": {
55
- "Central authority": {"Islam": 3, "Christianity": 3, "Judaism": 3},
56
- "Guidance but not absolute": {"Hinduism": 2, "Buddhism": 2, "Sikhism": 2},
57
- "Philosophical insights": {"Taoism": 2, "Buddhism": 2, "Confucianism": 3},
58
- "Not important": {"Secular Humanism": 3, "New Age": 1}
 
59
  }
60
  },
61
  {
62
  "id": 4,
63
- "question": "What happens after death?",
64
  "options": {
65
- "Heaven or Hell": {"Christianity": 3, "Islam": 3},
66
- "Reincarnation": {"Hinduism": 3, "Buddhism": 3, "Sikhism": 2},
67
- "Merge with the universe": {"Taoism": 3, "New Age": 2},
68
- "Nothing/End of consciousness": {"Secular Humanism": 3},
69
- "Unknown": {"Secular Humanism": 1, "Buddhism": 1}
70
  }
71
  },
72
  {
73
  "id": 5,
74
- "question": "How important is community in your spiritual life?",
75
  "options": {
76
- "Very important": {"Christianity": 3, "Islam": 3, "Judaism": 3, "Sikhism": 3},
77
- "Somewhat important": {"Hinduism": 2, "Buddhism": 2, "Wicca": 2},
78
- "Not very important": {"Taoism": 2, "New Age": 2},
79
- "Prefer solitary practice": {"Buddhism": 1, "New Age": 2}
 
80
  }
81
  },
82
  {
83
  "id": 6,
84
- "question": "What is the purpose of life?",
85
  "options": {
86
- "Serve God": {"Christianity": 3, "Islam": 3, "Judaism": 3},
87
- "Achieve enlightenment": {"Buddhism": 3, "Hinduism": 3},
88
- "Live in harmony": {"Taoism": 3, "Confucianism": 3, "Indigenous": 3},
89
- "Help humanity": {"Secular Humanism": 3, "Sikhism": 2},
90
- "Personal fulfillment": {"New Age": 3, "Secular Humanism": 2}
91
  }
92
  },
93
  {
94
  "id": 7,
95
- "question": "How do you view suffering?",
96
  "options": {
97
- "Test from God": {"Christianity": 3, "Islam": 3, "Judaism": 2},
98
- "Result of attachment": {"Buddhism": 3},
99
- "Natural part of life": {"Taoism": 3, "Stoicism": 3, "Secular Humanism": 2},
100
- "Karma from past actions": {"Hinduism": 3, "Buddhism": 2, "Sikhism": 2}
 
101
  }
102
  },
103
  {
104
  "id": 8,
105
- "question": "What is your stance on ritual and ceremony?",
106
  "options": {
107
- "Essential": {"Hinduism": 3, "Judaism": 3, "Wicca": 3},
108
- "Important but flexible": {"Christianity": 2, "Islam": 2, "Buddhism": 2},
109
- "Optional": {"New Age": 2, "Taoism": 2},
110
- "Unnecessary": {"Secular Humanism": 3}
 
111
  }
112
  }
113
  ]
114
 
115
  # Religion Descriptions
116
  RELIGIONS = {
117
- "Christianity": {
118
- "name": "Christianity",
119
- "description": "Based on the life and teachings of Jesus Christ, emphasizing love, forgiveness, and salvation through faith.",
120
- "core_beliefs": "Trinity (Father, Son, Holy Spirit), Salvation through Jesus, Bible as sacred text",
121
- "practices": "Church attendance, prayer, sacraments, Bible study",
122
- "resources": ["Bible", "Local churches", "Christian counseling", "Bible.com"]
123
- },
124
- "Islam": {
125
- "name": "Islam",
126
- "description": "Monotheistic faith revealed to Prophet Muhammad, emphasizing submission to Allah's will.",
127
- "core_beliefs": "Five Pillars, Quran as final revelation, Prophet Muhammad, One God (Allah)",
128
- "practices": "Five daily prayers, fasting during Ramadan, charity, pilgrimage to Mecca",
129
- "resources": ["Quran", "Local mosques", "Islamic centers", "Quran.com"]
130
- },
131
- "Buddhism": {
132
- "name": "Buddhism",
133
- "description": "Path to enlightenment through understanding the nature of suffering and following the Eightfold Path.",
134
- "core_beliefs": "Four Noble Truths, Eightfold Path, Karma, Reincarnation, No eternal soul",
135
- "practices": "Meditation, mindfulness, following precepts, studying dharma",
136
- "resources": ["Buddhist temples", "Meditation centers", "AccessToInsight.org"]
137
- },
138
- "Hinduism": {
139
- "name": "Hinduism",
140
- "description": "Ancient tradition with diverse beliefs, emphasizing dharma, karma, and moksha (liberation).",
141
- "core_beliefs": "Brahman (ultimate reality), Karma, Reincarnation, Multiple paths to divine",
142
- "practices": "Puja (worship), yoga, meditation, festivals, pilgrimages",
143
- "resources": ["Bhagavad Gita", "Hindu temples", "Yoga centers"]
144
- },
145
- "Judaism": {
146
- "name": "Judaism",
147
- "description": "Covenant relationship between God and the Jewish people, emphasizing Torah study and ethical living.",
148
- "core_beliefs": "One God, Chosen people, Torah, Messiah to come, Ethical monotheism",
149
- "practices": "Sabbath observance, kashrut (dietary laws), prayer, Torah study",
150
- "resources": ["Torah", "Synagogues", "Jewish community centers"]
151
- },
152
- "Sikhism": {
153
- "name": "Sikhism",
154
- "description": "Monotheistic faith founded by Guru Nanak, emphasizing equality, service, and devotion to one God.",
155
- "core_beliefs": "One God, Equality of all people, Karma and reincarnation, Guru Granth Sahib",
156
- "practices": "Prayer, meditation on God's name, service (seva), honest living",
157
- "resources": ["Guru Granth Sahib", "Gurdwaras", "Sikh community organizations"]
158
- },
159
- "Taoism": {
160
- "name": "Taoism",
161
- "description": "Chinese philosophy emphasizing living in harmony with the Tao (the Way), natural flow of the universe.",
162
- "core_beliefs": "The Tao, Wu wei (effortless action), Yin and yang, Natural harmony",
163
- "practices": "Meditation, Tai Chi, Qigong, simplicity, nature connection",
164
- "resources": ["Tao Te Ching", "Taoist temples", "Tai Chi classes"]
165
- },
166
- "Secular Humanism": {
167
- "name": "Secular Humanism",
168
- "description": "Non-religious philosophy emphasizing reason, ethics, human welfare without supernatural beliefs.",
169
- "core_beliefs": "Human reason, Scientific method, Ethical living without religion, Human dignity",
170
- "practices": "Critical thinking, ethical action, community service, rational inquiry",
171
- "resources": ["Humanist organizations", "Secular communities", "Philosophy books"]
172
- },
173
- "New Age": {
174
- "name": "New Age Spirituality",
175
- "description": "Modern spiritual movement combining various traditions, emphasizing personal growth and consciousness.",
176
- "core_beliefs": "Universal energy, Personal transformation, Interconnectedness, Alternative healing",
177
- "practices": "Meditation, crystal healing, astrology, energy work, holistic wellness",
178
- "resources": ["Spiritual centers", "Wellness workshops", "Metaphysical bookstores"]
179
- },
180
- "Wicca": {
181
- "name": "Wicca",
182
- "description": "Modern pagan religion honoring nature, practicing ritual magic, and worshipping the Goddess and God.",
183
- "core_beliefs": "Nature reverence, Magic, Goddess and God, Harm none, Wheel of the Year",
184
- "practices": "Seasonal rituals, spell work, moon celebrations, nature worship",
185
- "resources": ["Wiccan covens", "Pagan gatherings", "Nature-based spirituality books"]
186
- }
187
  }
188
 
189
  def load_users():
 
190
  if os.path.exists(USERS_FILE):
191
  with open(USERS_FILE, 'r') as f:
192
  return json.load(f)
193
  return {}
194
 
195
  def save_users(users):
 
196
  with open(USERS_FILE, 'w') as f:
197
  json.dump(users, f, indent=2)
198
 
199
  def calculate_results(answers):
 
200
  scores = {}
 
201
  for answer in answers:
202
  question = next((q for q in QUESTIONS if q["id"] == answer["question_id"]), None)
203
  if question and answer["answer"] in question["options"]:
204
  points = question["options"][answer["answer"]]
205
  for religion, score in points.items():
206
  scores[religion] = scores.get(religion, 0) + score
 
 
207
  sorted_scores = sorted(scores.items(), key=lambda x: x[1], reverse=True)
 
 
208
  recommendations = []
209
  for religion_key, score in sorted_scores[:3]:
210
  if religion_key in RELIGIONS:
@@ -212,31 +169,27 @@ def calculate_results(answers):
212
  religion_info["score"] = score
213
  religion_info["percentage"] = round((score / (len(answers) * 3)) * 100)
214
  recommendations.append(religion_info)
 
215
  return recommendations
216
 
217
- # Routes
218
  @app.route("/")
219
- def index():
220
- # Check if user is logged in
221
- if 'username' in session:
222
- users = load_users()
223
- user_data = users.get(session['username'], {})
224
- has_results = len(user_data.get('recommendations', [])) > 0
225
-
226
- return render_template("index.html",
227
- logged_in=True,
228
- username=session['username'],
229
- title="🌟 Your Spiritual Journey" if has_results else "🌟 Spiritual Path Assessment",
230
- message="Explore your personalized results" if has_results else "Discover your path",
231
- has_results=has_results,
232
- questions=QUESTIONS,
233
- results=user_data.get('recommendations', [])
234
- )
235
 
236
- # Not logged in - show login page
237
- return render_template("index.html",
238
- logged_in=False,
239
- is_signup=False
 
 
 
 
 
 
 
 
 
240
  )
241
 
242
  @app.route("/login", methods=["GET", "POST"])
@@ -244,52 +197,62 @@ def login():
244
  if request.method == "POST":
245
  data = request.json
246
  username = data.get('username', '').strip()
247
- password = data.get('password', '').strip()
248
-
249
- if not username or not password:
250
- return jsonify({"success": False, "message": "Username and password required"})
251
 
252
  users = load_users()
253
- if username in users and users[username].get('password') == password:
254
- session['username'] = username
255
- return jsonify({"success": True, "message": "Login successful"})
256
 
257
- return jsonify({"success": False, "message": "Invalid credentials"})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
258
 
259
- # GET request - show login page
260
- return render_template("index.html",
261
- logged_in=False,
262
- is_signup=False
263
- )
264
 
265
  @app.route("/signup", methods=["GET", "POST"])
266
  def signup():
267
  if request.method == "POST":
268
  data = request.json
269
  username = data.get('username', '').strip()
270
- password = data.get('password', '').strip()
271
-
272
- if not username or not password:
273
- return jsonify({"success": False, "message": "All fields required"})
274
 
275
  users = load_users()
 
276
  if username in users:
277
- return jsonify({"success": False, "message": "Username already exists"})
 
 
 
278
 
 
279
  users[username] = {
280
- "password": password,
281
- "answers": [],
282
- "recommendations": []
283
  }
284
  save_users(users)
285
  session['username'] = username
286
- return jsonify({"success": True, "message": "Account created successfully"})
287
 
288
- # GET request - show signup page
289
- return render_template("index.html",
290
- logged_in=False,
291
- is_signup=True
292
- )
 
293
 
294
  @app.route("/submit_assessment", methods=["POST"])
295
  def submit_assessment():
@@ -299,18 +262,20 @@ def submit_assessment():
299
  data = request.json
300
  answers = data.get('answers', [])
301
 
302
- if not answers:
303
- return jsonify({"success": False, "message": "No answers provided"})
304
 
305
- users = load_users()
306
- username = session['username']
307
 
308
- if username in users:
309
- users[username]['answers'] = answers
310
- recommendations = calculate_results(answers)
311
- users[username]['recommendations'] = recommendations
 
312
  save_users(users)
313
- return jsonify({"success": True, "recommendations": recommendations})
 
314
 
315
  return jsonify({"success": False, "message": "User not found"})
316
 
@@ -320,71 +285,71 @@ def reset_assessment():
320
  return jsonify({"success": False, "message": "Not logged in"})
321
 
322
  users = load_users()
323
- username = session['username']
324
-
325
- if username in users:
326
- users[username]['answers'] = []
327
- users[username]['recommendations'] = []
328
  save_users(users)
329
  return jsonify({"success": True})
330
 
331
  return jsonify({"success": False, "message": "User not found"})
332
 
333
- @app.route("/logout")
334
- def logout():
335
- session.pop('username', None)
336
- return redirect(url_for('index'))
337
-
338
  @app.route("/chat", methods=["POST"])
339
  def chat():
340
  if 'username' not in session:
341
  return jsonify({"success": False, "message": "Not logged in"})
342
-
343
  if not client:
344
  return jsonify({"success": False, "message": "Chat service not configured. Please set TOGETHER_API_KEY."})
345
-
346
  data = request.json
347
  user_message = data.get('message', '').strip()
348
  religion_name = data.get('religion', '')
349
  chat_history = data.get('history', [])
350
-
351
  if not user_message or not religion_name:
352
  return jsonify({"success": False, "message": "Message and religion required"})
353
-
354
  # Find religion details
355
  religion_data = None
356
  for key, value in RELIGIONS.items():
357
  if value['name'] == religion_name:
358
  religion_data = value
359
  break
360
-
361
  if not religion_data:
362
  return jsonify({"success": False, "message": "Religion not found"})
363
-
364
  # Create context-aware system prompt
365
  system_prompt = f"""You're a spiritual guide for {religion_data['name']}.
366
  Info: {religion_data['description']} | Practices: {religion_data['practices']} | Beliefs: {religion_data['core_beliefs']}
367
  Rules: Keep 30-50 words, be respectful, use * for bullet points (format: "Text: * item * item"), answer directly."""
368
 
 
369
  messages = [{"role": "system", "content": system_prompt}]
 
 
370
  for msg in chat_history[-5:]:
371
  messages.append({"role": msg["role"], "content": msg["content"]})
 
 
372
  messages.append({"role": "user", "content": user_message})
373
-
374
  try:
375
- response = together.chat.completions.create(
 
376
  model="meta-llama/Meta-Llama-3-8B-Instruct-Lite",
377
  messages=messages,
378
- max_tokens=80,
379
  temperature=0.7,
380
  )
381
-
382
- bot_response = response.output[0].content[0].text
 
383
  return jsonify({
384
  "success": True,
385
  "response": bot_response
386
  })
387
-
388
  except Exception as e:
389
  return jsonify({
390
  "success": False,
@@ -392,4 +357,4 @@ Rules: Keep 30-50 words, be respectful, use * for bullet points (format: "Text:
392
  })
393
 
394
  if __name__ == "__main__":
395
- app.run(debug=True, host="0.0.0.0", port=7860)
 
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 werkzeug dotenv puja moksha sikhism jainism shintoism paganism wicca
8
+
9
  from flask import Flask, render_template, request, jsonify, session, redirect, url_for
10
+ from werkzeug.security import generate_password_hash, check_password_hash
11
  import json
12
  import os
 
13
  from dotenv import load_dotenv
14
+ from together import Together
15
 
 
16
  load_dotenv()
17
 
18
  app = Flask(__name__)
 
23
 
24
  # Together API for chatbot
25
  TOGETHER_API_KEY = os.getenv("TOGETHER_API_KEY")
26
+ client = Together(api_key=TOGETHER_API_KEY) if TOGETHER_API_KEY else None
 
27
 
28
  # Assessment Questions
29
  QUESTIONS = [
30
  {
31
  "id": 1,
32
+ "question": "What is your view on the nature of the divine?",
33
  "options": {
34
+ "One supreme God who created everything": {"christianity": 3, "islam": 3, "judaism": 3},
35
+ "Multiple gods and goddesses": {"hinduism": 3, "paganism": 3},
36
+ "A universal energy or force": {"buddhism": 2, "taoism": 3, "new_age": 3},
37
+ "No divine being, focus on human potential": {"humanism": 3, "atheism": 3},
38
+ "Uncertain or unknowable": {"agnosticism": 3}
39
  }
40
  },
41
  {
42
  "id": 2,
43
+ "question": "How do you prefer to connect with spirituality?",
44
  "options": {
45
+ "Through organized worship and community": {"christianity": 2, "islam": 2, "judaism": 2},
46
+ "Through personal meditation and reflection": {"buddhism": 3, "hinduism": 2, "taoism": 2},
47
+ "Through nature and natural cycles": {"paganism": 3, "indigenous": 3},
48
+ "Through reason and philosophy": {"humanism": 2, "stoicism": 3},
49
+ "I don't feel the need for spiritual connection": {"atheism": 3}
50
  }
51
  },
52
  {
53
  "id": 3,
54
+ "question": "What is your belief about the afterlife?",
55
  "options": {
56
+ "Heaven or Hell based on faith/deeds": {"christianity": 3, "islam": 3},
57
+ "Reincarnation until enlightenment": {"hinduism": 3, "buddhism": 3},
58
+ "Ancestral realm or spiritual world": {"indigenous": 2, "paganism": 2},
59
+ "No afterlife, this life is all there is": {"atheism": 3, "humanism": 2},
60
+ "Unsure or open to possibilities": {"agnosticism": 2, "new_age": 2}
61
  }
62
  },
63
  {
64
  "id": 4,
65
+ "question": "What guides your moral and ethical decisions?",
66
  "options": {
67
+ "Sacred texts and religious teachings": {"christianity": 3, "islam": 3, "judaism": 3},
68
+ "Universal principles of compassion and mindfulness": {"buddhism": 3, "jainism": 3},
69
+ "Harmony with nature and balance": {"taoism": 3, "indigenous": 2},
70
+ "Reason, empathy, and human rights": {"humanism": 3, "secularism": 3},
71
+ "Personal intuition and inner wisdom": {"new_age": 2, "spiritualism": 3}
72
  }
73
  },
74
  {
75
  "id": 5,
76
+ "question": "What role does ritual or practice play in your life?",
77
  "options": {
78
+ "Regular prayer and worship are essential": {"islam": 3, "christianity": 2, "judaism": 2},
79
+ "Daily meditation or mindfulness practice": {"buddhism": 3, "hinduism": 2, "zen": 3},
80
+ "Seasonal celebrations and ceremonies": {"paganism": 3, "wicca": 3},
81
+ "Minimal to no ritual, prefer intellectual engagement": {"humanism": 2, "deism": 2},
82
+ "Flexible, whatever feels meaningful to me": {"new_age": 2, "spiritual_not_religious": 3}
83
  }
84
  },
85
  {
86
  "id": 6,
87
+ "question": "How do you view the relationship between humans and nature?",
88
  "options": {
89
+ "Humans are stewards of God's creation": {"christianity": 2, "islam": 2, "judaism": 2},
90
+ "All life is interconnected and sacred": {"buddhism": 2, "hinduism": 2, "jainism": 3},
91
+ "Nature itself is divine": {"paganism": 3, "pantheism": 3, "indigenous": 3},
92
+ "Nature follows natural laws we can understand": {"atheism": 2, "humanism": 2},
93
+ "We should live in harmony with natural flow": {"taoism": 3, "shintoism": 2}
94
  }
95
  },
96
  {
97
  "id": 7,
98
+ "question": "What is your view on suffering and its purpose?",
99
  "options": {
100
+ "A test of faith or part of God's plan": {"christianity": 2, "islam": 2},
101
+ "Result of attachment and desire": {"buddhism": 3, "stoicism": 2},
102
+ "Karma from past actions": {"hinduism": 3, "sikhism": 2},
103
+ "Random or result of natural causes": {"atheism": 3, "secular": 2},
104
+ "An opportunity for growth and learning": {"new_age": 2, "spiritualism": 2}
105
  }
106
  },
107
  {
108
  "id": 8,
109
+ "question": "How important is community in your spiritual life?",
110
  "options": {
111
+ "Very important, prefer group worship": {"christianity": 2, "islam": 2, "sikhism": 3},
112
+ "Somewhat important, but personal practice matters more": {"buddhism": 2, "hinduism": 2},
113
+ "Community of like-minded seekers": {"paganism": 2, "unitarian": 3},
114
+ "Not important, spirituality is personal": {"spiritual_not_religious": 3, "deism": 2},
115
+ "Prefer secular community over religious": {"humanism": 2, "atheism": 2}
116
  }
117
  }
118
  ]
119
 
120
  # Religion Descriptions
121
  RELIGIONS = {
122
+ "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"},
123
+ "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"},
124
+ "buddhism": {"name": "Buddhism", "description": "Path to enlightenment through mindfulness and compassion.", "practices": "Meditation, mindfulness, Eightfold Path", "core_beliefs": "Four Noble Truths, impermanence, ending suffering"},
125
+ "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"},
126
+ "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"},
127
+ "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"},
128
+ "paganism": {"name": "Modern Paganism", "description": "Nature-based spirituality honoring seasonal cycles.", "practices": "Seasonal celebrations, rituals, nature work", "core_beliefs": "Nature as sacred, multiple deities"},
129
+ "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"},
130
+ "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"},
131
+ "agnosticism": {"name": "Agnosticism", "description": "Divine existence is unknown or unknowable.", "practices": "Philosophical inquiry, ethical living", "core_beliefs": "Uncertainty about divine, questions over answers"},
132
+ "new_age": {"name": "New Age Spirituality", "description": "Eclectic approach emphasizing personal growth.", "practices": "Meditation, energy work, crystals, yoga", "core_beliefs": "Personal transformation, universal consciousness"},
133
+ "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"},
134
+ "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"},
135
+ "indigenous": {"name": "Indigenous Spirituality", "description": "Traditional practices honoring ancestors and land.", "practices": "Ceremonies, storytelling, seasonal rituals", "core_beliefs": "Land connection, ancestor veneration, reciprocity"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136
  }
137
 
138
  def load_users():
139
+ """Load users from JSON file"""
140
  if os.path.exists(USERS_FILE):
141
  with open(USERS_FILE, 'r') as f:
142
  return json.load(f)
143
  return {}
144
 
145
  def save_users(users):
146
+ """Save users to JSON file"""
147
  with open(USERS_FILE, 'w') as f:
148
  json.dump(users, f, indent=2)
149
 
150
  def calculate_results(answers):
151
+ """Calculate which spiritual paths align with user's answers"""
152
  scores = {}
153
+
154
  for answer in answers:
155
  question = next((q for q in QUESTIONS if q["id"] == answer["question_id"]), None)
156
  if question and answer["answer"] in question["options"]:
157
  points = question["options"][answer["answer"]]
158
  for religion, score in points.items():
159
  scores[religion] = scores.get(religion, 0) + score
160
+
161
+ # Sort by score
162
  sorted_scores = sorted(scores.items(), key=lambda x: x[1], reverse=True)
163
+
164
+ # Get top 3 recommendations
165
  recommendations = []
166
  for religion_key, score in sorted_scores[:3]:
167
  if religion_key in RELIGIONS:
 
169
  religion_info["score"] = score
170
  religion_info["percentage"] = round((score / (len(answers) * 3)) * 100)
171
  recommendations.append(religion_info)
172
+
173
  return recommendations
174
 
 
175
  @app.route("/")
176
+ def home():
177
+ if 'username' not in session:
178
+ return redirect(url_for('login'))
 
 
 
 
 
 
 
 
 
 
 
 
 
179
 
180
+ users = load_users()
181
+ user_data = users.get(session['username'], {})
182
+ has_results = 'results' in user_data and user_data['results']
183
+
184
+ return render_template(
185
+ "index.html",
186
+ title="Spiritual Path Finder",
187
+ message=f"Welcome, {session['username']}! 🌟",
188
+ username=session['username'],
189
+ logged_in=True,
190
+ questions=QUESTIONS,
191
+ has_results=has_results,
192
+ results=user_data.get('results', []) if has_results else []
193
  )
194
 
195
  @app.route("/login", methods=["GET", "POST"])
 
197
  if request.method == "POST":
198
  data = request.json
199
  username = data.get('username', '').strip()
200
+ password = data.get('password', '')
 
 
 
201
 
202
  users = load_users()
 
 
 
203
 
204
+ if username in users:
205
+ # Check if password is hashed or plaintext (for backward compatibility)
206
+ stored_password = users[username]['password']
207
+ if stored_password.startswith('pbkdf2:sha256:'):
208
+ # Hashed password
209
+ if check_password_hash(stored_password, password):
210
+ session['username'] = username
211
+ return jsonify({"success": True})
212
+ else:
213
+ # Plaintext password (legacy users) - hash it on login
214
+ if stored_password == password:
215
+ # Update to hashed password
216
+ users[username]['password'] = generate_password_hash(password)
217
+ save_users(users)
218
+ session['username'] = username
219
+ return jsonify({"success": True})
220
+
221
+ return jsonify({"success": False, "message": "Invalid credentials!"})
222
 
223
+ return render_template("index.html", logged_in=False, is_signup=False)
 
 
 
 
224
 
225
  @app.route("/signup", methods=["GET", "POST"])
226
  def signup():
227
  if request.method == "POST":
228
  data = request.json
229
  username = data.get('username', '').strip()
230
+ password = data.get('password', '')
 
 
 
231
 
232
  users = load_users()
233
+
234
  if username in users:
235
+ return jsonify({"success": False, "message": "Username already exists!"})
236
+
237
+ if not username or not password:
238
+ return jsonify({"success": False, "message": "Username and password required!"})
239
 
240
+ # Create new user with hashed password
241
  users[username] = {
242
+ 'password': generate_password_hash(password),
243
+ 'answers': [],
244
+ 'results': []
245
  }
246
  save_users(users)
247
  session['username'] = username
248
+ return jsonify({"success": True})
249
 
250
+ return render_template("index.html", logged_in=False, is_signup=True)
251
+
252
+ @app.route("/logout")
253
+ def logout():
254
+ session.pop('username', None)
255
+ return redirect(url_for('login'))
256
 
257
  @app.route("/submit_assessment", methods=["POST"])
258
  def submit_assessment():
 
262
  data = request.json
263
  answers = data.get('answers', [])
264
 
265
+ if len(answers) != len(QUESTIONS):
266
+ return jsonify({"success": False, "message": "Please answer all questions!"})
267
 
268
+ # Calculate results
269
+ results = calculate_results(answers)
270
 
271
+ # Save to user data
272
+ users = load_users()
273
+ if session['username'] in users:
274
+ users[session['username']]['answers'] = answers
275
+ users[session['username']]['results'] = results
276
  save_users(users)
277
+
278
+ return jsonify({"success": True, "results": results})
279
 
280
  return jsonify({"success": False, "message": "User not found"})
281
 
 
285
  return jsonify({"success": False, "message": "Not logged in"})
286
 
287
  users = load_users()
288
+ if session['username'] in users:
289
+ users[session['username']]['answers'] = []
290
+ users[session['username']]['results'] = []
 
 
291
  save_users(users)
292
  return jsonify({"success": True})
293
 
294
  return jsonify({"success": False, "message": "User not found"})
295
 
 
 
 
 
 
296
  @app.route("/chat", methods=["POST"])
297
  def chat():
298
  if 'username' not in session:
299
  return jsonify({"success": False, "message": "Not logged in"})
300
+
301
  if not client:
302
  return jsonify({"success": False, "message": "Chat service not configured. Please set TOGETHER_API_KEY."})
303
+
304
  data = request.json
305
  user_message = data.get('message', '').strip()
306
  religion_name = data.get('religion', '')
307
  chat_history = data.get('history', [])
308
+
309
  if not user_message or not religion_name:
310
  return jsonify({"success": False, "message": "Message and religion required"})
311
+
312
  # Find religion details
313
  religion_data = None
314
  for key, value in RELIGIONS.items():
315
  if value['name'] == religion_name:
316
  religion_data = value
317
  break
318
+
319
  if not religion_data:
320
  return jsonify({"success": False, "message": "Religion not found"})
321
+
322
  # Create context-aware system prompt
323
  system_prompt = f"""You're a spiritual guide for {religion_data['name']}.
324
  Info: {religion_data['description']} | Practices: {religion_data['practices']} | Beliefs: {religion_data['core_beliefs']}
325
  Rules: Keep 30-50 words, be respectful, use * for bullet points (format: "Text: * item * item"), answer directly."""
326
 
327
+ # Build conversation history
328
  messages = [{"role": "system", "content": system_prompt}]
329
+
330
+ # Add chat history (last 5 messages for context)
331
  for msg in chat_history[-5:]:
332
  messages.append({"role": msg["role"], "content": msg["content"]})
333
+
334
+ # Add current user message
335
  messages.append({"role": "user", "content": user_message})
336
+
337
  try:
338
+ # Call Together API with limited tokens for concise responses
339
+ response = client.chat.completions.create(
340
  model="meta-llama/Meta-Llama-3-8B-Instruct-Lite",
341
  messages=messages,
342
+ max_tokens=80, # Roughly 50-60 words maximum
343
  temperature=0.7,
344
  )
345
+
346
+ bot_response = response.choices[0].message.content
347
+
348
  return jsonify({
349
  "success": True,
350
  "response": bot_response
351
  })
352
+
353
  except Exception as e:
354
  return jsonify({
355
  "success": False,
 
357
  })
358
 
359
  if __name__ == "__main__":
360
+ app.run(debug=True, port=5001)