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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import weaviate
|
| 3 |
+
from weaviate.auth import Auth
|
| 4 |
+
from sentence_transformers import SentenceTransformer
|
| 5 |
+
from weaviate.classes.query import MetadataQuery
|
| 6 |
+
from weaviate.collections.classes.filters import Filter
|
| 7 |
+
from typing import List, Dict, Any
|
| 8 |
+
import os
|
| 9 |
+
from dotenv import load_dotenv
|
| 10 |
+
import pandas as pd
|
| 11 |
+
import re
|
| 12 |
+
from functools import lru_cache
|
| 13 |
+
|
| 14 |
+
# Load environment variables
|
| 15 |
+
load_dotenv()
|
| 16 |
+
|
| 17 |
+
# Validate environment variables
|
| 18 |
+
WEAVIATE_URL = os.getenv("WEAVIATE_URL")
|
| 19 |
+
WEAVIATE_API_KEY = os.getenv("WEAVIATE_API_KEY")
|
| 20 |
+
COLLECTION_NAME = os.getenv("COLLECTION_NAME")
|
| 21 |
+
|
| 22 |
+
if not all([WEAVIATE_URL, WEAVIATE_API_KEY, COLLECTION_NAME]):
|
| 23 |
+
raise ValueError(
|
| 24 |
+
"Missing required environment variables. Please ensure the following are set:\n"
|
| 25 |
+
"WEAVIATE_URL\n"
|
| 26 |
+
"WEAVIATE_API_KEY\n"
|
| 27 |
+
"COLLECTION_NAME"
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
# Initialize the model
|
| 31 |
+
model = SentenceTransformer('sentence-transformers/LaBSE')
|
| 32 |
+
|
| 33 |
+
# Book mappings
|
| 34 |
+
VULGATE_BOOKS = {
|
| 35 |
+
"Genesis": "Gn", "Exodus": "Ex", "Leviticus": "Lv", "Numbers": "Nm",
|
| 36 |
+
"Deuteronomy": "Dt", "Joshua": "Jos", "Judges": "Jdc", "Ruth": "Rt",
|
| 37 |
+
"1 Samuel": "1Rg", "2 Samuel": "2Rg", "1 Kings": "3Rg", "2 Kings": "4Rg",
|
| 38 |
+
"1 Chronicles": "1Par", "2 Chronicles": "2Par", "Ezra": "Esr",
|
| 39 |
+
"Nehemiah": "Neh", "Tobit": "Tob", "Judith": "Jdt", "Esther": "Est",
|
| 40 |
+
"1 Maccabees": "1Mcc", "2 Maccabees": "2Mcc", "Job": "Job", "Psalms": "Ps",
|
| 41 |
+
"Proverbs": "Pr", "Ecclesiastes": "Ecl", "Song of Solomon": "Ct",
|
| 42 |
+
"Wisdom": "Sap", "Sirach": "Sir", "Isaiah": "Is", "Jeremiah": "Jr",
|
| 43 |
+
"Lamentations": "Lam", "Baruch": "Bar", "Ezekiel": "Ez", "Daniel": "Dn",
|
| 44 |
+
"Hosea": "Os", "Joel": "Joel", "Amos": "Am", "Obadiah": "Abd",
|
| 45 |
+
"Jonah": "Jon", "Micah": "Mch", "Nahum": "Nah", "Habakkuk": "Hab",
|
| 46 |
+
"Zephaniah": "Soph", "Haggai": "Agg", "Zechariah": "Zach",
|
| 47 |
+
"Malachi": "Mal", "Matthew": "Mt", "Mark": "Mc", "Luke": "Lc",
|
| 48 |
+
"John": "Jo", "Acts": "Act", "Romans": "Rom", "1 Corinthians": "1Cor",
|
| 49 |
+
"2 Corinthians": "2Cor", "Galatians": "Gal", "Ephesians": "Eph",
|
| 50 |
+
"Philippians": "Phlp", "Colossians": "Col", "1 Thessalonians": "1Thes",
|
| 51 |
+
"2 Thessalonians": "2Thes", "1 Timothy": "1Tim", "2 Timothy": "2Tim",
|
| 52 |
+
"Titus": "Tit", "Philemon": "Phlm", "Hebrews": "Hbr", "James": "Jac",
|
| 53 |
+
"1 Peter": "1Ptr", "2 Peter": "2Ptr", "1 John": "1Jo", "2 John": "2Jo",
|
| 54 |
+
"3 John": "3Jo", "Jude": "Jud", "Revelation": "Apc"
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
@lru_cache(maxsize=1)
|
| 58 |
+
def load_vulgate_csv():
|
| 59 |
+
df = pd.read_csv("data/clem_vulgate.csv")
|
| 60 |
+
# Expect columns: book, chapter, verse, text
|
| 61 |
+
return df
|
| 62 |
+
|
| 63 |
+
def highlight_matching_words(text: str, query: str) -> str:
|
| 64 |
+
if not query.strip():
|
| 65 |
+
return text
|
| 66 |
+
query_words = set(re.findall(r'\b\w+\b', query.lower()))
|
| 67 |
+
if not query_words:
|
| 68 |
+
return text
|
| 69 |
+
partial_pattern = re.compile(r'(' + '|'.join(re.escape(w) for w in query_words) + r')', re.IGNORECASE)
|
| 70 |
+
tokens = re.findall(r'\w+|\W+', text)
|
| 71 |
+
highlighted = []
|
| 72 |
+
for token in tokens:
|
| 73 |
+
token_lc = token.lower()
|
| 74 |
+
if token_lc in query_words:
|
| 75 |
+
highlighted.append(f'<span style="background:yellow">{token}</span>')
|
| 76 |
+
elif token.strip() and token.isalpha() and any(w in token_lc and w != token_lc for w in query_words):
|
| 77 |
+
def green_sub(m):
|
| 78 |
+
return f'<span style="background:lightgreen">{m.group(0)}</span>'
|
| 79 |
+
highlighted.append(partial_pattern.sub(green_sub, token))
|
| 80 |
+
else:
|
| 81 |
+
highlighted.append(token)
|
| 82 |
+
return ''.join(highlighted)
|
| 83 |
+
|
| 84 |
+
def find_similar(query: str, books: List[str], limit: int = 50) -> List[Dict[str, Any]]:
|
| 85 |
+
try:
|
| 86 |
+
query_vector = model.encode([query])[0]
|
| 87 |
+
client = weaviate.connect_to_weaviate_cloud(
|
| 88 |
+
cluster_url=WEAVIATE_URL,
|
| 89 |
+
auth_credentials=Auth.api_key(WEAVIATE_API_KEY),
|
| 90 |
+
)
|
| 91 |
+
try:
|
| 92 |
+
vulgate = client.collections.get(COLLECTION_NAME)
|
| 93 |
+
filter_condition = None
|
| 94 |
+
if books:
|
| 95 |
+
selected_books = [VULGATE_BOOKS[book] for book in books]
|
| 96 |
+
filter_condition = Filter.by_property("book").contains_any(selected_books)
|
| 97 |
+
response = vulgate.query.near_vector(
|
| 98 |
+
near_vector=query_vector,
|
| 99 |
+
limit=limit,
|
| 100 |
+
return_metadata=MetadataQuery(distance=True),
|
| 101 |
+
filters=filter_condition
|
| 102 |
+
)
|
| 103 |
+
results = []
|
| 104 |
+
for obj in response.objects:
|
| 105 |
+
highlighted_text = highlight_matching_words(obj.properties["text"], query)
|
| 106 |
+
results.append({
|
| 107 |
+
"Reference": f"{obj.properties['book']} {obj.properties['chapter']}:{obj.properties['verse']}",
|
| 108 |
+
"Book": obj.properties["book"],
|
| 109 |
+
"Chapter": obj.properties["chapter"],
|
| 110 |
+
"Verse": obj.properties["verse"],
|
| 111 |
+
"Text": highlighted_text,
|
| 112 |
+
"RawText": obj.properties["text"],
|
| 113 |
+
"Similarity": round(1 - obj.metadata.distance, 3)
|
| 114 |
+
})
|
| 115 |
+
return results
|
| 116 |
+
finally:
|
| 117 |
+
client.close()
|
| 118 |
+
except Exception as e:
|
| 119 |
+
return [{"Error": str(e)}]
|
| 120 |
+
|
| 121 |
+
def format_results_html(results: List[Dict[str, Any]]) -> str:
|
| 122 |
+
if not results:
|
| 123 |
+
return "<div>No results found.</div>"
|
| 124 |
+
if "Error" in results[0]:
|
| 125 |
+
return f'<div style="color:red">Error: {results[0]["Error"]}</div>'
|
| 126 |
+
html = [
|
| 127 |
+
'<style>td,th{padding:8px;}th{background:#f4f1e9;}tr:nth-child(even){background:#f9f9f9;}tr:hover{background:#e6e2d3;}table{border-radius:8px;overflow:hidden;box-shadow:0 2px 8px #e6e2d3;}td{vertical-align:top;}</style>',
|
| 128 |
+
'<table style="border-collapse:collapse;width:100%;font-size:1em;">',
|
| 129 |
+
'<thead><tr>'
|
| 130 |
+
'<th>Reference</th><th>Text</th><th>Similarity</th><th>Book</th><th>Chapter</th><th>Verse</th>'
|
| 131 |
+
'</tr></thead><tbody>'
|
| 132 |
+
]
|
| 133 |
+
for r in results:
|
| 134 |
+
html.append(f'<tr>'
|
| 135 |
+
f'<td>{r["Reference"]}</td>'
|
| 136 |
+
f'<td>{r["Text"]}</td>'
|
| 137 |
+
f'<td>{r["Similarity"]}</td>'
|
| 138 |
+
f'<td>{r["Book"]}</td>'
|
| 139 |
+
f'<td>{r["Chapter"]}</td>'
|
| 140 |
+
f'<td>{r["Verse"]}</td>'
|
| 141 |
+
f'</tr>')
|
| 142 |
+
html.append('</tbody></table>')
|
| 143 |
+
return ''.join(html)
|
| 144 |
+
|
| 145 |
+
def search(query: str, books: List[str], limit: int) -> str:
|
| 146 |
+
if not query.strip():
|
| 147 |
+
return "<div>Please enter a search query.</div>"
|
| 148 |
+
results = find_similar(query, books, limit)
|
| 149 |
+
return format_results_html(results)
|
| 150 |
+
|
| 151 |
+
with gr.Blocks(title="Latin Vulgate Verse Similarity Search", theme=gr.themes.Soft()) as demo:
|
| 152 |
+
gr.Markdown("""
|
| 153 |
+
# Latin Vulgate Verse Similarity Search
|
| 154 |
+
|
| 155 |
+
Search for similar verses in the Latin Vulgate Bible using semantic similarity.
|
| 156 |
+
<br>Words matching your query will be <span style='background:yellow'>highlighted yellow</span> (exact) or <span style='background:lightgreen'>green</span> (partial).
|
| 157 |
+
""")
|
| 158 |
+
with gr.Row():
|
| 159 |
+
query = gr.Textbox(
|
| 160 |
+
label="Search Query",
|
| 161 |
+
placeholder="Enter your search query...",
|
| 162 |
+
lines=2,
|
| 163 |
+
scale=3
|
| 164 |
+
)
|
| 165 |
+
with gr.Row():
|
| 166 |
+
with gr.Column(scale=2):
|
| 167 |
+
book_select = gr.Dropdown(
|
| 168 |
+
choices=list(VULGATE_BOOKS.keys()),
|
| 169 |
+
label="Select Books (Optional)",
|
| 170 |
+
multiselect=True
|
| 171 |
+
)
|
| 172 |
+
with gr.Row():
|
| 173 |
+
limit = gr.Slider(
|
| 174 |
+
minimum=1,
|
| 175 |
+
maximum=50,
|
| 176 |
+
value=20,
|
| 177 |
+
step=1,
|
| 178 |
+
label="Number of results"
|
| 179 |
+
)
|
| 180 |
+
with gr.Row():
|
| 181 |
+
search_btn = gr.Button("Search", variant="primary")
|
| 182 |
+
output = gr.HTML(label="Results")
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
search_btn.click(
|
| 186 |
+
fn=search,
|
| 187 |
+
inputs=[query, book_select, limit],
|
| 188 |
+
outputs=output
|
| 189 |
+
)
|
| 190 |
+
query.submit(
|
| 191 |
+
fn=search,
|
| 192 |
+
inputs=[query, book_select, limit],
|
| 193 |
+
outputs=output
|
| 194 |
+
)
|
| 195 |
+
if __name__ == "__main__":
|
| 196 |
+
demo.launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
sentence_transformers
|
| 2 |
+
weaviate-client
|