broadfield-dev commited on
Commit
b861f00
·
verified ·
1 Parent(s): 4255bc2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +69 -30
app.py CHANGED
@@ -1,10 +1,10 @@
1
- # app.py (Updated for a model with pre-normalized embeddings)
2
 
3
  import sys
4
  import subprocess
 
5
  from flask import Flask, render_template, request, flash, redirect, url_for, jsonify
6
  import torch
7
- import torch.nn.functional as F
8
  from transformers import AutoTokenizer, AutoModel
9
  import os
10
  import chromadb
@@ -13,19 +13,47 @@ from huggingface_hub import snapshot_download
13
  app = Flask(__name__)
14
  app.secret_key = os.urandom(24)
15
 
 
16
  CHROMA_PATH = "chroma_db"
17
  COLLECTION_NAME = "bible_verses"
18
- # *** CHANGE 1: USE A MODEL WITH NORMALIZED EMBEDDINGS ***
19
  MODEL_NAME = "sentence-transformers/multi-qa-mpnet-base-dot-v1"
20
- # *** CHANGE 2: USE THE NEW REPO FOR THE NEW DATABASE ***
21
  DATASET_REPO = "broadfield-dev/bible-chromadb-multi-qa-mpnet"
22
  STATUS_FILE = "build_status.log"
 
23
 
 
24
  chroma_collection = None
25
  tokenizer = None
26
  embedding_model = None
27
 
28
- # Mean Pooling Function - Crucial for sentence-transformer models
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  def mean_pooling(model_output, attention_mask):
30
  token_embeddings = model_output[0]
31
  input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
@@ -39,28 +67,19 @@ def load_resources():
39
  if not os.path.exists(CHROMA_PATH) or not os.listdir(CHROMA_PATH):
40
  print(f"Local DB not found. Downloading from '{DATASET_REPO}'...")
41
  snapshot_download(repo_id=DATASET_REPO, repo_type="dataset", local_dir=CHROMA_PATH, local_dir_use_symlinks=False)
42
- print("Database files downloaded.")
43
- else:
44
- print("Local database files found.")
45
  client = chromadb.PersistentClient(path=CHROMA_PATH)
46
- collection = client.get_collection(name=COLLECTION_NAME)
47
- if collection.count() == 0:
48
- print("Warning: Database collection is empty.")
49
- return False
50
- chroma_collection = collection
51
- print(f"Successfully connected to DB with {collection.count()} items.")
52
  tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
53
  embedding_model = AutoModel.from_pretrained(MODEL_NAME)
54
- print(f"Embedding model '{MODEL_NAME}' loaded successfully.")
55
  return True
56
  except Exception as e:
57
- print(f"Could not load resources. DB may not be built or repo is empty.")
58
- print(f"Error: {e}")
59
  return False
60
 
61
  resources_loaded = load_resources()
62
 
63
- # (home, build_rag_route, and status routes are unchanged)
64
  @app.route('/')
65
  def home():
66
  return render_template('index.html')
@@ -86,9 +105,9 @@ def status():
86
  def search():
87
  global resources_loaded
88
  if not resources_loaded:
89
- resources_loaded = load_resources()
90
  if not resources_loaded:
91
- flash("Database not ready. Please wait for the build process to finish and then refresh the page.", "error")
92
  return redirect(url_for('home'))
93
 
94
  user_query = request.form['query']
@@ -98,29 +117,49 @@ def search():
98
  encoded_input = tokenizer([user_query], padding=True, truncation=True, return_tensors='pt')
99
  with torch.no_grad():
100
  model_output = embedding_model(**encoded_input)
101
-
102
  query_embedding = mean_pooling(model_output, encoded_input['attention_mask'])
103
 
104
- # *** REMOVED: NO LONGER NEED TO NORMALIZE THE QUERY EMBEDDING ***
105
- # query_embedding = F.normalize(query_embedding, p=2, dim=1)
106
-
107
- search_results = chroma_collection.query(
108
- query_embeddings=query_embedding.cpu().tolist(),
109
- n_results=10
110
- )
111
 
112
  results_list = []
113
  documents, metadatas, distances = search_results['documents'][0], search_results['metadatas'][0], search_results['distances'][0]
114
 
115
  for i in range(len(documents)):
 
 
116
  results_list.append({
117
  'score': distances[i],
118
  'text': documents[i],
119
- 'reference': metadatas[i].get('reference', 'N/A'),
120
- 'version': metadatas[i].get('version', 'N/A')
 
 
121
  })
122
 
123
  return render_template('index.html', results=results_list, query=user_query)
124
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
  if __name__ == '__main__':
126
  app.run(host='0.0.0.0', port=7860)
 
1
+ # app.py
2
 
3
  import sys
4
  import subprocess
5
+ import json
6
  from flask import Flask, render_template, request, flash, redirect, url_for, jsonify
7
  import torch
 
8
  from transformers import AutoTokenizer, AutoModel
9
  import os
10
  import chromadb
 
13
  app = Flask(__name__)
14
  app.secret_key = os.urandom(24)
15
 
16
+ # --- App Configuration ---
17
  CHROMA_PATH = "chroma_db"
18
  COLLECTION_NAME = "bible_verses"
 
19
  MODEL_NAME = "sentence-transformers/multi-qa-mpnet-base-dot-v1"
 
20
  DATASET_REPO = "broadfield-dev/bible-chromadb-multi-qa-mpnet"
21
  STATUS_FILE = "build_status.log"
22
+ JSON_DIRECTORY = 'bible_json'
23
 
24
+ # --- Globals and Helpers ---
25
  chroma_collection = None
26
  tokenizer = None
27
  embedding_model = None
28
 
29
+ # *** ADD 1: BIBLE BOOK MAPPINGS FOR DATA RETRIEVAL ***
30
+ BOOK_ID_TO_NAME = {
31
+ 1: "Genesis", 2: "Exodus", 3: "Leviticus", 4: "Numbers", 5: "Deuteronomy", 6: "Joshua", 7: "Judges", 8: "Ruth", 9: "1 Samuel", 10: "2 Samuel", 11: "1 Kings", 12: "2 Kings", 13: "1 Chronicles", 14: "2 Chronicles", 15: "Ezra", 16: "Nehemiah", 17: "Esther", 18: "Job", 19: "Psalms", 20: "Proverbs", 21: "Ecclesiastes", 22: "Song of Solomon", 23: "Isaiah", 24: "Jeremiah", 25: "Lamentations", 26: "Ezekiel", 27: "Daniel", 28: "Hosea", 29: "Joel", 30: "Amos", 31: "Obadiah", 32: "Jonah", 33: "Micah", 34: "Nahum", 35: "Habakkuk", 36: "Zephaniah", 37: "Haggai", 38: "Zechariah", 39: "Malachi", 40: "Matthew", 41: "Mark", 42: "Luke", 43: "John", 44: "Acts", 45: "Romans", 46: "1 Corinthians", 47: "2 Corinthians", 48: "Galatians", 49: "Ephesians", 50: "Philippians", 51: "Colossians", 52: "1 Thessalonians", 53: "2 Thessalonians", 54: "1 Timothy", 55: "2 Timothy", 56: "Titus", 57: "Philemon", 58: "Hebrews", 59: "James", 60: "1 Peter", 61: "2 Peter", 62: "1 John", 63: "2 John", 64: "3 John", 65: "Jude", 66: "Revelation"
32
+ }
33
+ BOOK_NAME_TO_ID = {v: k for k, v in BOOK_ID_TO_NAME.items()}
34
+
35
+ # *** ADD 2: HELPER FUNCTION TO READ VERSES FROM JSON ***
36
+ def get_verses_from_json(version, book_name, chapter=None):
37
+ book_id = BOOK_NAME_TO_ID.get(book_name)
38
+ if not book_id: return None
39
+
40
+ file_path = os.path.join(JSON_DIRECTORY, f"t_{version.lower()}.json")
41
+ if not os.path.exists(file_path): return None
42
+
43
+ with open(file_path, 'r') as f: data = json.load(f)
44
+
45
+ rows = data.get("resultset", {}).get("row", [])
46
+ verses = []
47
+ for row in rows:
48
+ field = row.get("field", [])
49
+ if len(field) == 5:
50
+ row_book_id, row_chapter, row_verse, text = field[1], field[2], field[3], field[4]
51
+ if row_book_id == book_id and (chapter is None or row_chapter == chapter):
52
+ verses.append({'chapter': row_chapter, 'verse': row_verse, 'text': text.strip()})
53
+
54
+ verses.sort(key=lambda v: (v['chapter'], v['verse']))
55
+ return verses
56
+
57
  def mean_pooling(model_output, attention_mask):
58
  token_embeddings = model_output[0]
59
  input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
 
67
  if not os.path.exists(CHROMA_PATH) or not os.listdir(CHROMA_PATH):
68
  print(f"Local DB not found. Downloading from '{DATASET_REPO}'...")
69
  snapshot_download(repo_id=DATASET_REPO, repo_type="dataset", local_dir=CHROMA_PATH, local_dir_use_symlinks=False)
 
 
 
70
  client = chromadb.PersistentClient(path=CHROMA_PATH)
71
+ chroma_collection = client.get_collection(name=COLLECTION_NAME)
 
 
 
 
 
72
  tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
73
  embedding_model = AutoModel.from_pretrained(MODEL_NAME)
74
+ print(f"Resources loaded: DB has {chroma_collection.count()} items. Model is '{MODEL_NAME}'.")
75
  return True
76
  except Exception as e:
77
+ print(f"Could not load resources. DB may not be built. Error: {e}")
 
78
  return False
79
 
80
  resources_loaded = load_resources()
81
 
82
+ # --- Routes ---
83
  @app.route('/')
84
  def home():
85
  return render_template('index.html')
 
105
  def search():
106
  global resources_loaded
107
  if not resources_loaded:
108
+ resources_loaded = load_resources() # Retry loading
109
  if not resources_loaded:
110
+ flash("Database not ready. Please build the database from the Admin Panel.", "error")
111
  return redirect(url_for('home'))
112
 
113
  user_query = request.form['query']
 
117
  encoded_input = tokenizer([user_query], padding=True, truncation=True, return_tensors='pt')
118
  with torch.no_grad():
119
  model_output = embedding_model(**encoded_input)
 
120
  query_embedding = mean_pooling(model_output, encoded_input['attention_mask'])
121
 
122
+ search_results = chroma_collection.query(query_embeddings=query_embedding.cpu().tolist(), n_results=10)
 
 
 
 
 
 
123
 
124
  results_list = []
125
  documents, metadatas, distances = search_results['documents'][0], search_results['metadatas'][0], search_results['distances'][0]
126
 
127
  for i in range(len(documents)):
128
+ meta = metadatas[i]
129
+ # *** CHANGE 3: PASS NEW METADATA TO TEMPLATE FOR LINKING ***
130
  results_list.append({
131
  'score': distances[i],
132
  'text': documents[i],
133
+ 'reference': meta.get('reference', 'N/A'),
134
+ 'version': meta.get('version', 'N/A'),
135
+ 'book_name': meta.get('book_name', ''),
136
+ 'chapter': meta.get('chapter', '')
137
  })
138
 
139
  return render_template('index.html', results=results_list, query=user_query)
140
 
141
+ # *** ADD 3: NEW ROUTE FOR VIEWING A FULL CHAPTER ***
142
+ @app.route('/chapter/<version>/<book_name>/<int:chapter_num>')
143
+ def view_chapter(version, book_name, chapter_num):
144
+ verses = get_verses_from_json(version, book_name, chapter=chapter_num)
145
+ if not verses:
146
+ return "Chapter not found.", 404
147
+ return render_template('chapter.html', book_name=book_name, chapter_num=chapter_num, verses=verses, version=version)
148
+
149
+ # *** ADD 4: NEW ROUTE FOR VIEWING A FULL BOOK ***
150
+ @app.route('/book/<version>/<book_name>')
151
+ def view_book(version, book_name):
152
+ all_verses = get_verses_from_json(version, book_name)
153
+ if not all_verses:
154
+ return "Book not found.", 404
155
+
156
+ chapters = {}
157
+ for verse in all_verses:
158
+ chap_num = verse['chapter']
159
+ if chap_num not in chapters: chapters[chap_num] = []
160
+ chapters[chap_num].append(verse)
161
+
162
+ return render_template('book.html', book_name=book_name, chapters=chapters)
163
+
164
  if __name__ == '__main__':
165
  app.run(host='0.0.0.0', port=7860)