Spaces:
Sleeping
Sleeping
Repository Documentation | |
This document provides a comprehensive overview of the repository's structure and contents. | |
The first section, titled 'Directory/File Tree', displays the repository's hierarchy in a tree format. | |
In this section, directories and files are listed using tree branches to indicate their structure and relationships. | |
Following the tree representation, the 'File Content' section details the contents of each file in the repository. | |
Each file's content is introduced with a '[File Begins]' marker followed by the file's relative path, | |
and the content is displayed verbatim. The end of each file's content is marked with a '[File Ends]' marker. | |
This format ensures a clear and orderly presentation of both the structure and the detailed contents of the repository. | |
Directory/File Tree Begins --> | |
/ | |
├── README.md | |
├── __pycache__ | |
├── app.py | |
├── bible.py | |
├── database-structure.txt | |
├── els_cache.db.initial | |
├── gematria.py | |
├── hindu.py | |
├── populate_translations.py | |
├── quran.py | |
├── requirements-all.txt | |
├── requirements.txt | |
├── texts | |
│ ├── bible | |
│ ├── mahabharata | |
│ ├── quran | |
│ ├── rigveda | |
│ ├── torah | |
│ └── tripitaka | |
├── torah.py | |
├── translation_database.db.initial | |
├── translation_utils.py | |
├── tripitaka.py | |
├── util.py | |
└── utils.py | |
<-- Directory/File Tree Ends | |
File Content Begin --> | |
[File Begins] README.md | |
--- | |
title: Book of Souls - Search your name+day (journal) oracle with ELS over Torah, Bible, Quran, Rigveda, Tripitaka | |
emoji: 📊 | |
colorFrom: green | |
colorTo: pink | |
sdk: gradio | |
sdk_version: 4.39.0 | |
app_file: app.py | |
pinned: false | |
--- | |
This application searches for equidistant letter sequences (ELS) in the Torah, Bible, Quran, and Rigveda. It also integrates a network search functionality to find related phrases based on gematria. | |
**Inputs:** | |
* **Target Language for Translation:** The language to translate the results into. | |
* **Date to investigate (optional):** A date to include in the gematria calculation. | |
* **Language of the person/topic (optional) (Date Word Language):** The language to use for converting the date to words. | |
* **Name and/or Topic (required):** The text to calculate the gematria for. | |
* **Jump Width (Steps) (optional) for ELS:** The step size for the ELS search. | |
* **Round (1) / Round (2) (optional):** The number of rounds for the ELS search (positive or negative). | |
* **Include Torah / Include Bible / Include Quran / Include Rigveda:** Checkboxes to select which texts to search. | |
* **Strip Spaces from Books / Strip Text in Braces from Books / Strip Diacritics from Books:** Options for text preprocessing. | |
**Outputs:** | |
* **ELS Results:** A dataframe containing the ELS search results. | |
* **Most Frequent Phrase in Network Search:** The most frequent phrase found in the network search. | |
* **JSON Output:** A JSON representation of the search results. | |
**How to Use:** | |
1. Enter the name or topic you want to investigate. | |
2. Optionally, select a date and the language for its representation. | |
3. Set the jump width (steps) and rounds for the ELS search. | |
4. Choose which texts to include in the search. | |
5. Configure text preprocessing options as needed. | |
6. Click "Search with ELS". | |
7. The results will be displayed in the output sections. You can copy the JSON output using the provided button. | |
**Network Search:** | |
The network search functionality uses the calculated gematria of the ELS results to search a database for phrases with the same gematria. It displays the most frequent matching phrase. If no exact match is found, it attempts to find the closest match based on similarity and word count difference. | |
[File Ends] README.md | |
[File Begins] app.py | |
#TODO: Quran results have numbers | |
import logging | |
logger = logging.getLogger(__name__) | |
logging.basicConfig(level=logging.DEBUG) | |
import gradio as gr | |
import torah | |
import bible | |
import quran | |
import hindu | |
import tripitaka | |
from utils import number_to_ordinal_word, custom_normalize, date_to_words, translate_date_to_words | |
from gematria import calculate_gematria, strip_diacritics | |
import pandas as pd | |
from deep_translator import GoogleTranslator | |
from gradio_calendar import Calendar | |
from datetime import datetime, timedelta | |
import math | |
import json | |
import re | |
import sqlite3 | |
from collections import defaultdict | |
from typing import List, Tuple | |
import rich | |
from fuzzywuzzy import fuzz | |
import calendar | |
import translation_utils | |
import hashlib | |
translation_utils.create_translation_table() | |
# Create a translator instance *once* globally | |
translator = GoogleTranslator(source='auto', target='auto') | |
LANGUAGES_SUPPORTED = translator.get_supported_languages(as_dict=True) # Corrected dictionary name | |
LANGUAGE_CODE_MAP = LANGUAGES_SUPPORTED # Use deep_translator's mapping directly | |
# --- Constants --- | |
DATABASE_FILE = 'gematria.db' | |
MAX_PHRASE_LENGTH_LIMIT = 20 | |
ELS_CACHE_DB = "els_cache.db" | |
DATABASE_TIMEOUT = 60 | |
# --- Database Initialization --- | |
def initialize_database(): | |
global conn | |
conn = sqlite3.connect(DATABASE_FILE) | |
cursor = conn.cursor() | |
cursor.execute(''' | |
CREATE TABLE IF NOT EXISTS results ( | |
gematria_sum INTEGER, | |
words TEXT, | |
translation TEXT, | |
book TEXT, | |
chapter INTEGER, | |
verse INTEGER, | |
phrase_length INTEGER, | |
word_position TEXT, | |
PRIMARY KEY (gematria_sum, words, book, chapter, verse, word_position) | |
) | |
''') | |
cursor.execute(''' | |
CREATE INDEX IF NOT EXISTS idx_results_gematria | |
ON results (gematria_sum) | |
''') | |
cursor.execute(''' | |
CREATE TABLE IF NOT EXISTS processed_books ( | |
book TEXT PRIMARY KEY, | |
max_phrase_length INTEGER | |
) | |
''') | |
conn.commit() | |
# --- Initialize Database --- | |
initialize_database() | |
# --- ELS Cache Functions --- | |
def create_els_cache_table(): | |
with sqlite3.connect(ELS_CACHE_DB) as conn: | |
conn.execute(''' | |
CREATE TABLE IF NOT EXISTS els_cache ( | |
query_hash TEXT PRIMARY KEY, | |
results TEXT | |
) | |
''') | |
def get_query_hash(func, *args, **kwargs): | |
key = (func.__name__, args, tuple(sorted(kwargs.items()))) | |
return hashlib.sha256(json.dumps(key).encode()).hexdigest() | |
def cached_process_json_files(func, *args, **kwargs): | |
query_hash = get_query_hash(func, *args, **kwargs) | |
try: | |
with sqlite3.connect(ELS_CACHE_DB, timeout=DATABASE_TIMEOUT) as conn: | |
cursor = conn.cursor() | |
cursor.execute("SELECT results FROM els_cache WHERE query_hash = ?", (query_hash,)) | |
result = cursor.fetchone() | |
if result: | |
logger.info(f"Cache hit for query: {query_hash}") | |
return json.loads(result[0]) | |
except sqlite3.Error as e: | |
logger.error(f"Database error checking cache: {e}") | |
logger.info(f"Cache miss for query: {query_hash}") | |
results = func(*args, **kwargs) | |
try: | |
with sqlite3.connect(ELS_CACHE_DB, timeout=DATABASE_TIMEOUT) as conn: | |
cursor = conn.cursor() | |
cursor.execute("INSERT INTO els_cache (query_hash, results) VALUES (?, ?)", (query_hash, json.dumps(results))) | |
conn.commit() | |
except sqlite3.Error as e: | |
logger.error(f"Database error caching results: {e}") | |
return results | |
# --- Helper Functions (from Network app.py) --- | |
def flatten_text(text: List) -> str: | |
if isinstance(text, list): | |
return " ".join(flatten_text(item) if isinstance(item, list) else item for item in text) | |
return text | |
def search_gematria_in_db(gematria_sum: int, max_words: int) -> List[Tuple[str, str, int, int, int, str]]: | |
global conn | |
with sqlite3.connect(DATABASE_FILE) as conn: | |
cursor = conn.cursor() | |
cursor.execute(''' | |
SELECT words, book, chapter, verse, phrase_length, word_position | |
FROM results | |
WHERE gematria_sum = ? AND phrase_length <= ? | |
''', (gematria_sum, max_words)) | |
results = cursor.fetchall() | |
return results | |
def get_most_frequent_phrase(results): | |
phrase_counts = defaultdict(int) | |
for words, book, chapter, verse, phrase_length, word_position in results: | |
phrase_counts[words] += 1 | |
most_frequent_phrase = max(phrase_counts, key=phrase_counts.get) if phrase_counts else None # Handle empty results | |
return most_frequent_phrase | |
# --- Functions from BOS app.py --- | |
def create_language_dropdown(label, default_value='English', show_label=True): # Default value must be in LANGUAGE_CODE_MAP | |
return gr.Dropdown( | |
choices=list(LANGUAGE_CODE_MAP.keys()), # Correct choices | |
label=label, | |
value=default_value, | |
show_label=show_label | |
) | |
def calculate_gematria_sum(text, date_words): | |
if text or date_words: | |
combined_input = f"{text} {date_words}" | |
logger.info(f"searching for input: {combined_input}") | |
numbers = re.findall(r'\d+', combined_input) | |
text_without_numbers = re.sub(r'\d+', '', combined_input) | |
number_sum = sum(int(number) for number in numbers) | |
text_gematria = calculate_gematria(strip_diacritics(text_without_numbers)) | |
total_sum = text_gematria + number_sum | |
return total_sum | |
else: | |
return None | |
def perform_els_search(step, rounds_combination, tlang, strip_spaces, strip_in_braces, strip_diacritics_chk, include_torah, include_bible, include_quran, include_hindu, include_tripitaka): | |
if step == 0 or rounds_combination == "0,0": | |
return None | |
results = {} | |
length = 0 | |
selected_language_long = tlang # From the Gradio dropdown (long form) | |
tlang = LANGUAGES_SUPPORTED.get(selected_language_long) #Get the short code. | |
if tlang is None: # Handle unsupported languages | |
tlang = "en" | |
logger.warning(f"Unsupported language selected: {selected_language_long}. Defaulting to English (en).") | |
if include_torah: | |
logger.debug(f"Arguments for Torah: {(1, 39, step, rounds_combination, length, tlang, strip_spaces, strip_in_braces, strip_diacritics_chk)}") | |
results["Torah"] = cached_process_json_files(torah.process_json_files, 1, 39, step, rounds_combination, length, tlang, strip_spaces, strip_in_braces, strip_diacritics_chk) | |
else: | |
results["Torah"] = [] | |
if include_bible: | |
results["Bible"] = cached_process_json_files(bible.process_json_files, 40, 66, step, rounds_combination, length, tlang, strip_spaces, strip_in_braces, strip_diacritics_chk) | |
else: | |
results["Bible"] = [] | |
if include_quran: | |
results["Quran"] = cached_process_json_files(quran.process_json_files, 1, 114, step, rounds_combination, length, tlang, strip_spaces, strip_in_braces, strip_diacritics_chk) | |
else: | |
results["Quran"] = [] | |
if include_hindu: | |
results["Rig Veda"] = cached_process_json_files(hindu.process_json_files, 1, 10, step, rounds_combination, length, tlang, False, strip_in_braces, strip_diacritics_chk) | |
else: | |
results["Rig Veda"] = [] | |
if include_tripitaka: | |
results["Tripitaka"] = cached_process_json_files(tripitaka.process_json_files, 1, 52, step, rounds_combination, length, tlang, strip_spaces, strip_in_braces, strip_diacritics_chk) | |
else: | |
results["Tripitaka"] = [] | |
return results | |
def add_24h_projection(results_dict): #Now takes a dictionary of results | |
for book_name, results in results_dict.items(): # Iterate per book | |
num_results = len(results) | |
if num_results > 0: | |
time_interval = timedelta(minutes=24 * 60 / num_results) | |
current_time = datetime.min.time() | |
for i in range(num_results): | |
next_time = (datetime.combine(datetime.min, current_time) + time_interval).time() | |
time_range_str = f"{current_time.strftime('%H:%M')}-{next_time.strftime('%H:%M')}" | |
results[i]['24h Projection'] = time_range_str | |
current_time = next_time | |
return results_dict | |
def add_monthly_projection(results_dict, selected_date): | |
if selected_date is None: | |
return results_dict # Return if no date is selected | |
for book_name, results in results_dict.items(): # Iterate per book | |
num_results = len(results) | |
if num_results > 0: | |
days_in_month = calendar.monthrange(selected_date.year, selected_date.month)[1] | |
total_seconds = (days_in_month - 1) * 24 * 3600 | |
seconds_interval = total_seconds / num_results | |
start_datetime = datetime(selected_date.year, selected_date.month, 1) | |
current_datetime = start_datetime | |
for i in range(num_results): | |
next_datetime = current_datetime + timedelta(seconds=seconds_interval) | |
current_date = current_datetime.date() # Moved assignment inside loop | |
next_date = next_datetime.date() | |
date_range_str = f"{current_date.strftime('%h %d')} - {next_date.strftime('%h %d')}" | |
results[i]['Monthly Projection'] = date_range_str | |
current_datetime = next_datetime # Add this | |
current_date = next_datetime.date() # Add this too | |
return results_dict | |
def add_yearly_projection(results_dict, selected_date): #Correct name, handle dictionary input | |
if selected_date is None: | |
return results_dict # Return if no date is selected | |
for book_name, results in results_dict.items(): # Iterate per book | |
num_results = len(results) | |
if num_results > 0: | |
days_in_year = 366 if calendar.isleap(selected_date.year) else 365 | |
total_seconds = (days_in_year - 1) * 24 * 3600 | |
seconds_interval = total_seconds / num_results | |
start_datetime = datetime(selected_date.year, 1, 1) | |
current_datetime = start_datetime | |
for i in range(num_results): | |
next_datetime = current_datetime + timedelta(seconds=seconds_interval) | |
current_date = current_datetime.date() # Move assignment inside loop | |
next_date = next_datetime.date() | |
date_range_str = f"{current_date.strftime('%b %d')} - {next_date.strftime('%b %d')}" | |
results[i]['Yearly Projection'] = date_range_str | |
current_datetime = next_datetime # Update current datetime for next iteration | |
return results_dict | |
def sort_results(results): | |
def parse_time(time_str): | |
try: | |
hours, minutes = map(int, time_str.split(':')) | |
return hours * 60 + minutes # Convert to total minutes | |
except ValueError: | |
return 24 * 60 # Sort invalid times to the end | |
return sorted(results, key=lambda x: ( | |
parse_time(x.get('24h Projection', '23:59').split('-')[0]), # Sort by start time first | |
parse_time(x.get('24h Projection', '23:59').split('-')[1]) # Then by end time | |
)) | |
# --- Main Gradio App --- | |
with gr.Blocks() as app: | |
with gr.Column(): | |
with gr.Row(): | |
tlang = create_language_dropdown("Target Language for Result Translation", default_value='english') | |
selected_date = Calendar(type="datetime", label="Date to investigate (optional)", info="Pick a date from the calendar") | |
use_day = gr.Checkbox(label="Use Day", info="Check to include day in search", value=True) | |
use_month = gr.Checkbox(label="Use Month", info="Check to include month in search", value=True) | |
use_year = gr.Checkbox(label="Use Year", info="Check to include year in search", value=True) | |
date_language_input = create_language_dropdown("Language of the person/topic (optional) (Date Word Language)", default_value='english') | |
with gr.Row(): | |
gematria_text = gr.Textbox(label="Name and/or Topic (required)", value="Hans Albert Einstein Mileva Marity-Einstein") | |
date_words_output = gr.Textbox(label="Date in Words Translated (optional)") | |
gematria_result = gr.Number(label="Journal Sum") | |
#with gr.Row(): | |
with gr.Row(): | |
step = gr.Number(label="Jump Width (Steps) for ELS") | |
float_step = gr.Number(visible=False, value=1) | |
half_step_btn = gr.Button("Steps / 2") | |
double_step_btn = gr.Button("Steps * 2") | |
with gr.Column(): | |
round_x = gr.Number(label="Round (1)", value=1) | |
round_y = gr.Number(label="Round (2)", value=-1) | |
rounds_combination = gr.Textbox(label="Combined Rounds", value="1,-1") | |
with gr.Row(): | |
include_torah_chk = gr.Checkbox(label="Include Torah", value=True) | |
include_bible_chk = gr.Checkbox(label="Include Bible", value=True) | |
include_quran_chk = gr.Checkbox(label="Include Quran", value=True) | |
include_hindu_chk = gr.Checkbox(label="Include Rigveda", value=True) | |
include_tripitaka_chk = gr.Checkbox(label="Include Tripitaka", value=True) | |
merge_results_chk = gr.Checkbox(label="Merge Results (Torah-Bible-Quran)", value=True) | |
strip_spaces = gr.Checkbox(label="Strip Spaces from Books", value=True) | |
strip_in_braces = gr.Checkbox(label="Strip Text in Braces from Books", value=True) | |
strip_diacritics_chk = gr.Checkbox(label="Strip Diacritics from Books", value=True) | |
translate_btn = gr.Button("Search with ELS") | |
# --- Output Components --- | |
markdown_output = gr.Dataframe(label="ELS Results") | |
most_frequent_phrase_output = gr.Textbox(label="Most Frequent Phrase in Network Search") | |
json_output = gr.JSON(label="JSON Output") | |
# --- Event Handlers --- | |
def update_date_words(selected_date, date_language_input, use_day, use_month, use_year): | |
if selected_date is None: | |
return "" | |
if not use_year and not use_month and not use_day: | |
return translate_date_to_words(selected_date, date_language_input) | |
year = selected_date.year if use_year else None | |
month = selected_date.month if use_month else None | |
day = selected_date.day if use_day else None | |
if year is not None and month is not None and day is not None: | |
date_obj = selected_date | |
elif year is not None and month is not None: | |
date_obj = str(f"{year}-{month}") | |
elif year is not None: | |
date_obj = str(f"{year}") | |
else: # Return empty string if no date components are selected | |
return "" | |
date_in_words = date_to_words(date_obj) | |
translator = GoogleTranslator(source='auto', target=date_language_input) | |
translated_date_words = translator.translate(date_in_words) | |
return custom_normalize(translated_date_words) | |
def update_journal_sum(gematria_text, date_words_output): | |
sum_value = calculate_gematria_sum(gematria_text, date_words_output) | |
return sum_value, sum_value, sum_value | |
def update_rounds_combination(round_x, round_y): | |
return f"{int(round_x)},{int(round_y)}" | |
def update_step_half(float_step): | |
new_step = math.ceil(float_step / 2) | |
return new_step, float_step / 2 | |
def update_step_double(float_step): | |
new_step = math.ceil(float_step * 2) | |
return new_step, float_step * 2 | |
def find_closest_phrase(target_phrase, phrases): | |
best_match = None | |
best_score = 0 | |
logging.debug(f"Target phrase for similarity search: {target_phrase}") # Log target phrase | |
for phrase, _, _, _, _, _ in phrases: | |
word_length_diff = abs(len(target_phrase.split()) - len(phrase.split())) | |
similarity_score = fuzz.ratio(target_phrase, phrase) | |
combined_score = similarity_score - word_length_diff | |
logging.debug(f"Comparing with phrase: {phrase}") # Log each phrase being compared | |
logging.debug( | |
f"Word Length Difference: {word_length_diff}, Similarity Score: {similarity_score}, Combined Score: {combined_score}") # Log scores | |
if combined_score > best_score: | |
best_score = combined_score | |
best_match = phrase | |
logging.debug(f"Closest phrase found: {best_match} with score: {best_score}") # Log the best match | |
return best_match | |
def perform_search(step, rounds_combination, tlang, strip_spaces, strip_in_braces, strip_diacritics_chk, include_torah, include_bible, include_quran, include_hindu, include_tripitaka, gematria_text, date_words_output, selected_date): | |
# Inside perform_search | |
els_results = perform_els_search(step, rounds_combination, tlang, strip_spaces, strip_in_braces, | |
strip_diacritics_chk, include_torah, include_bible, include_quran, | |
include_hindu, | |
include_tripitaka) | |
# --- Network Search Integration --- | |
most_frequent_phrases = {} | |
combined_and_sorted_results = [] # Combined list to hold all results | |
for book_name, book_results in els_results.items(): | |
if book_results: # Add this check to ensure book_results is not empty | |
most_frequent_phrases[book_name] = "" # Default value | |
for result in book_results: | |
try: | |
gematria_sum = calculate_gematria(result['result_text']) # Calculate gematria | |
max_words = len(result['result_text'].split()) | |
matching_phrases = search_gematria_in_db(gematria_sum, max_words) | |
max_words_limit = 20 | |
while not matching_phrases and max_words < max_words_limit: # Increase max_words for more results | |
max_words += 1 | |
matching_phrases = search_gematria_in_db(gematria_sum, max_words) | |
if matching_phrases: | |
most_frequent_phrase = get_most_frequent_phrase(matching_phrases) | |
most_frequent_phrases[book_name] = most_frequent_phrase | |
else: | |
closest_phrase = find_closest_phrase(result['result_text'], | |
search_gematria_in_db(gematria_sum, max_words_limit)) | |
most_frequent_phrases[ | |
book_name] = closest_phrase or "" # Update most frequent phrases even if no phrase found | |
result['Most Frequent Phrase'] = most_frequent_phrases[book_name] | |
if 'book' in result: | |
if isinstance(result['book'], int): # Torah, Bible, Quran case | |
result['book'] = f"{book_name} {result['book']}." | |
combined_and_sorted_results.append(result) | |
except KeyError as e: | |
print(f"DEBUG: KeyError - Key '{e.args[0]}' not found in result. Skipping this result.") | |
continue | |
# --- Batch Translation --- | |
selected_language_long = tlang | |
tlang_short = LANGUAGES_SUPPORTED.get(selected_language_long) | |
if tlang_short is None: | |
tlang_short = "en" | |
logger.warning(f"Unsupported language selected: {selected_language_long}. Defaulting to English (en).") | |
# Prepare lists for batch translation, including source language | |
phrases_to_translate = [] | |
phrases_source_langs = [] # Source languages for phrases | |
results_to_translate = [] | |
results_source_langs = [] # Source languages for results | |
for result in combined_and_sorted_results: | |
phrases_to_translate.append(result.get('Most Frequent Phrase', '')) | |
# Always use 'iw' as the source language for "Most Frequent Phrase" | |
phrases_source_langs.append("iw") | |
results_to_translate.append(result.get('result_text', '')) | |
results_source_langs.append(result.get("source_language", "auto")) | |
translated_phrases = translation_utils.batch_translate(phrases_to_translate, tlang_short, phrases_source_langs) | |
translated_result_texts = translation_utils.batch_translate(results_to_translate, tlang_short, results_source_langs) | |
for i, result in enumerate(combined_and_sorted_results): | |
result['translated_text'] = translated_result_texts.get(results_to_translate[i], None) | |
result['Translated Most Frequent Phrase'] = translated_phrases.get(phrases_to_translate[i], None) | |
# Time Projections (using els_results dictionary) | |
updated_els_results = add_24h_projection(els_results) # Use original els_results dictionary | |
updated_els_results = add_monthly_projection(updated_els_results, selected_date) # Call correct functions with correct params | |
updated_els_results = add_yearly_projection(updated_els_results, selected_date) | |
combined_and_sorted_results = [] | |
for book_results in updated_els_results.values(): # Combine results for dataframe and json | |
combined_and_sorted_results.extend(book_results) | |
combined_and_sorted_results = sort_results(combined_and_sorted_results) # sort combined results | |
df = pd.DataFrame(combined_and_sorted_results) | |
df.index = range(1, len(df) + 1) | |
df.reset_index(inplace=True) | |
df.rename(columns={'index': 'Result Number'}, inplace=True) | |
for i, result in enumerate(combined_and_sorted_results): # Iterate through the combined list | |
result['Result Number'] = i + 1 | |
search_config = { | |
"step": step, | |
"rounds_combination": rounds_combination, | |
"target_language": tlang, | |
"strip_spaces": strip_spaces, | |
"strip_in_braces": strip_in_braces, | |
"strip_diacritics": strip_diacritics_chk, | |
"include_torah": include_torah, | |
"include_bible": include_bible, | |
"include_quran": include_quran, | |
"include_hindu": include_hindu, | |
"include_tripitaka": include_tripitaka, | |
"gematria_text": gematria_text, | |
"date_words": date_words_output | |
} | |
output_data = { | |
"search_configuration": search_config, | |
"results": combined_and_sorted_results # Use the combined list here | |
} | |
json_data = output_data | |
# --- Return results --- | |
combined_most_frequent = "\n".join( | |
f"{book}: {phrase}" for book, phrase in most_frequent_phrases.items()) # Combine phrases | |
return df, combined_most_frequent, json_data | |
# --- Event Triggers --- | |
round_x.change(update_rounds_combination, inputs=[round_x, round_y], outputs=rounds_combination) | |
round_y.change(update_rounds_combination, inputs=[round_x, round_y], outputs=rounds_combination) | |
selected_date.change(update_date_words, inputs=[selected_date, date_language_input, use_day, use_month, use_year], outputs=[date_words_output]) | |
date_language_input.change(update_date_words, inputs=[selected_date, date_language_input, use_day, use_month, use_year], outputs=[date_words_output]) | |
gematria_text.change(update_journal_sum, inputs=[gematria_text, date_words_output], outputs=[gematria_result, step, float_step]) | |
date_words_output.change(update_journal_sum, inputs=[gematria_text, date_words_output], outputs=[gematria_result, step, float_step]) | |
half_step_btn.click(update_step_half, inputs=[float_step], outputs=[step, float_step]) | |
double_step_btn.click(update_step_double, inputs=[float_step], outputs=[step, float_step]) | |
translate_btn.click( | |
perform_search, | |
inputs=[step, rounds_combination, tlang, strip_spaces, strip_in_braces, strip_diacritics_chk, include_torah_chk, include_bible_chk, include_quran_chk, include_hindu_chk, include_tripitaka_chk, gematria_text, date_words_output, selected_date], | |
outputs=[markdown_output, most_frequent_phrase_output, json_output] | |
) | |
app.load( | |
update_date_words, | |
inputs=[selected_date, date_language_input, use_day, use_month, use_year], # Include all 5 inputs | |
outputs=[date_words_output] | |
) | |
use_day.change( | |
update_date_words, | |
inputs=[selected_date, date_language_input, use_day, use_month, use_year], | |
outputs=[date_words_output] | |
) | |
use_month.change( | |
update_date_words, | |
inputs=[selected_date, date_language_input, use_day, use_month, use_year], | |
outputs=[date_words_output] | |
) | |
use_year.change( | |
update_date_words, | |
inputs=[selected_date, date_language_input, use_day, use_month, use_year], | |
outputs=[date_words_output] | |
) | |
def checkbox_behavior(use_day_value, use_month_value): | |
if use_day_value: # Tick month and year automatically when day is ticked. | |
return True, True | |
return use_month_value, True # return month value unchanged and automatically tick year if month is checked | |
use_day.change(checkbox_behavior, inputs=[use_day, use_month], outputs=[use_month, use_year]) | |
use_month.change(checkbox_behavior, inputs=[use_day, use_month], outputs=[use_month, use_year]) #No need for use_day here, day won't be changed by month | |
if __name__ == "__main__": | |
app.launch(share=False) | |
[File Ends] app.py | |
[File Begins] bible.py | |
import logging | |
import json | |
import os | |
import re | |
from deep_translator import GoogleTranslator | |
from gematria import calculate_gematria | |
import math | |
import csv | |
# Configure the logger | |
# You can uncomment the next line to enable debugging logs | |
# logging.basicConfig(level=logging.DEBUG, format='%(levelname)s:%(message)s') | |
logger = logging.getLogger(__name__) | |
def process_json_files(start=40, end=66, step=1, rounds="1", length=0, tlang="en", strip_spaces=True, | |
strip_in_braces=True, strip_diacritics=True, translate=False): | |
""" | |
Process a CSV file containing biblical texts and perform various text manipulations. | |
Parameters: | |
- start (int): Starting book number. | |
- end (int): Ending book number. | |
- step (int): Step value for character selection. | |
- rounds (str): Comma-separated string of round values (can include floats). | |
- length (int): Maximum length of the result text. | |
- tlang (str): Target language for translation. | |
- strip_spaces (bool): Whether to remove spaces from the text. | |
- strip_in_braces (bool): Whether to remove text within braces. | |
- strip_diacritics (bool): Whether to remove diacritics from the text. | |
- translate (bool): Whether to translate the result text. | |
Returns: | |
- list: A list of dictionaries containing processed data or error messages. | |
""" | |
file_name = "texts/bible/OpenGNT_version3_3.csv" | |
translator = GoogleTranslator(source='auto', target=tlang) if translate else None | |
results = [] | |
# Dictionary for the 27 books of the New Testament (English names) | |
nt_books = { | |
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" | |
} | |
try: | |
with open(file_name, 'r', encoding='utf-8') as file: | |
reader = csv.DictReader(file, delimiter='\t') | |
book_texts = {} | |
current_book = None | |
for row_num, row in enumerate(reader, start=1): | |
try: | |
# Parse the book number from '〔Book|Chapter|Verse〕' field | |
book_field = row['〔Book|Chapter|Verse〕'] | |
book_str = book_field.split('|')[0] # e.g., '〔40' | |
book_num_str = book_str.lstrip('〔') # Remove leading '〔' | |
book = int(book_num_str) | |
if book < start or book > end: | |
continue | |
if current_book != book: | |
current_book = book | |
book_texts[book] = "" | |
# Parse the Greek text from '〔OGNTk|OGNTu|OGNTa|lexeme|rmac|sn〕' field | |
greek_field = row['〔OGNTk|OGNTu|OGNTa|lexeme|rmac|sn〕'] | |
# Extract the first part before '〔' and split by '|' | |
if '〔' in greek_field: | |
greek_text = greek_field.split('〔')[1] | |
greek_text = greek_text.split('|')[0] | |
else: | |
greek_text = greek_field.split('|')[0] | |
book_texts[book] += greek_text + " " | |
except (KeyError, IndexError, ValueError) as e: | |
logger.error(f"Error parsing row {row_num}: {e}") | |
continue # Skip this row and continue | |
for book, full_text in book_texts.items(): | |
logger.debug(f"Processing book {book}") | |
clean_text = full_text | |
if strip_in_braces: | |
clean_text = re.sub(r"\[.*?\]|\{.*?\}|\<.*?\>", "", clean_text, flags=re.DOTALL) | |
if strip_diacritics: | |
# Adjusted regex for Greek diacritics | |
clean_text = re.sub(r"[^\u0370-\u03FF\u1F00-\u1FFF ]+", "", clean_text) | |
# Optionally, remove specific diacritics or punctuation if needed | |
# clean_text = re.sub(r'[additional patterns]', '', clean_text) | |
# Normalize spaces | |
clean_text = clean_text.replace("\n\n ", " ") | |
clean_text = clean_text.replace("\n", " ") | |
clean_text = re.sub(r'\s+', ' ', clean_text).strip() | |
if strip_spaces: | |
clean_text = clean_text.replace(" ", "") | |
text_length = len(clean_text) | |
logger.debug(f"Clean text for book {book}: Length = {text_length}") | |
if text_length == 0: | |
logger.warning(f"No text available for book {book} after cleaning.") | |
continue # Skip processing if there's no text | |
try: | |
rounds_list = list(map(float, rounds.split(','))) # Allow floats | |
except ValueError as e: | |
logger.error(f"Invalid rounds parameter: {e}") | |
return [{"error": f"Invalid rounds parameter: {e}"}] | |
result_text = "" | |
for r in rounds_list: | |
abs_r = abs(r) | |
# Determine the number of full passes and the remainder. | |
full_passes = math.floor(abs_r) | |
remainder = abs_r - full_passes | |
# Base number of characters per pass | |
base_chars = text_length // step | |
if base_chars == 0: | |
if abs_r > 1: # Changed from >=1 to >1 | |
# When step > text_length and rounds >1, pick 1 character per full pass | |
chars_per_full_pass = 1 | |
logger.debug(f"Book {book}: step > text_length ({step} > {text_length}), selecting 1 character per full pass.") | |
else: | |
# No characters to pick | |
chars_per_full_pass = 0 | |
logger.debug(f"Book {book}: step > text_length ({step} > {text_length}) and rounds <=1, no characters selected.") | |
# For remainder, since base_chars=0, no remainder characters | |
chars_for_remainder = 0 | |
else: | |
# Normal case | |
chars_per_full_pass = base_chars | |
chars_for_remainder = math.floor(base_chars * remainder) # Partial pass | |
logger.debug(f"Book {book}: Normal case, chars_per_full_pass = {chars_per_full_pass}, chars_for_remainder = {chars_for_remainder}") | |
if r > 0: | |
current_index = (step - 1) % text_length | |
direction = 1 | |
else: | |
current_index = (text_length - step) % text_length | |
direction = -1 | |
pass_result = "" | |
# Full passes, keep only the last pass | |
for pass_num in range(1, full_passes + 1): | |
current_pass_chars = "" | |
for _ in range(chars_per_full_pass): | |
if chars_per_full_pass == 0: | |
break | |
current_pass_chars += clean_text[current_index] | |
current_index = (current_index + direction * step) % text_length | |
# Keep only the last full pass | |
if pass_num == full_passes: | |
pass_result = current_pass_chars | |
logger.debug(f"Book {book}: Pass {pass_num}, pass_result = {pass_result}") | |
# Remainder pass for fractional rounds | |
if remainder > 0 and chars_for_remainder > 0: | |
current_pass_chars = "" | |
for _ in range(chars_for_remainder): | |
current_pass_chars += clean_text[current_index] | |
current_index = (current_index + direction * step) % text_length | |
pass_result += current_pass_chars | |
logger.debug(f"Book {book}: Remainder pass_result = {pass_result}") | |
# Handle cases where step > text_length and chars_per_full_pass=1 | |
if base_chars == 0 and chars_per_full_pass == 1 and full_passes > 0: | |
# pass_result already contains the last character picked | |
pass | |
elif base_chars == 0 and chars_per_full_pass == 0 and full_passes > 0: | |
# When no characters are picked, skip appending | |
pass | |
result_text += pass_result | |
logger.debug(f"Result text for book {book}: {result_text}") | |
if length != 0: | |
result_text = result_text[:length] | |
logger.debug(f"Book {book}: Result text truncated to length {length}.") | |
# Translate the result text if required | |
try: | |
translated_text = translator.translate(result_text) if translator and result_text else "" | |
except Exception as e: | |
logger.error(f"Book {book}: Translation error: {e}") | |
translated_text = "" | |
# Calculate the Gematria sum | |
try: | |
result_sum = calculate_gematria(result_text) | |
except Exception as e: | |
logger.error(f"Book {book}: Gematria calculation error: {e}") | |
result_sum = None | |
if result_text: | |
result = { | |
'book': f"Bible {book}.", | |
'title': nt_books.get(book, "Unknown Book"), | |
'result_text': result_text, | |
'result_sum': result_sum, | |
'translated_text': translated_text | |
} | |
results.append(result) | |
except FileNotFoundError: | |
logger.error(f"File {file_name} not found.") | |
results.append({"error": f"File {file_name} not found."}) | |
except Exception as e: | |
logger.error(f"An unexpected error occurred: {e}") | |
results.append({"error": f"An unexpected error occurred: {e}"}) | |
return results if results else None | |
# Tests | |
test_results = [ | |
(process_json_files(40,40,386,rounds="1,0.5,-1,-0.5"), "τωιεοννναυοοαμπυρααυοιξοηαϲοιιωομκνοοουομρυοιεχοοδεαλαννοτοκϲααυϲϲτεαδαϲαιεευαιηαεηαμαλκμαιακιγνμυνετνυυθθεγιεδρεαοαντηοκεοατϲνπναολαεοοφεηεϲωμκουμερρυοϲαοοαϲλτιηιωδυνϲυτυιχοονεαηωντολθβοτεαιαυοηετιτεαννυεινϲεενωκωξρυρηρνϲξεαγεαϲατωιεοννναυοοαμπυρααυοιξοηαϲοιιωομκνοοουομρυοιεχοοδεαλαννοτοκϲααυϲϲτεαδαϲαιεευαιηαεηαμαλκμαιακιγνμυνετνυυθθεγιεδρεαοϲτοαϲωθειιυνδνδξλονυταολαϲαττμτννοερτεοροανιεκτεεαιιϲωεαμϲωικμτποκϲϲιορϲπμοκαιουτωτδοωαξεαγωεφτωυπμαλυττταεομττλυαεπατονεαξτομυχαωηνυοβωπτυυκξαπιτααπυενεροοτϲαααυηοανηλταιθεαντινοιλκιβπγοδαιοηωαδαετακυϲοηυουαυνωαεαοττυαεεωτανεκβγεϲτοαϲωθειιυνδνδξλονυταολαϲαττμτννοερτεοροανιεκτεεαιιϲωεαμϲωικμτποκϲϲιορϲπμοκαιουτωτδοωαξεαγωεφτωυπμαλυττταεομττλυαε"), | |
(process_json_files(40,40,386,rounds="1,-1"), "τωιεοννναυοοαμπυρααυοιξοηαϲοιιωομκνοοουομρυοιεχοοδεαλαννοτοκϲααυϲϲτεαδαϲαιεευαιηαεηαμαλκμαιακιγνμυνετνυυθθεγιεδρεαοαντηοκεοατϲνπναολαεοοφεηεϲωμκουμερρυοϲαοοαϲλτιηιωδυνϲυτυιχοονεαηωντολθβοτεαιαυοηετιτεαννυεινϲεενωκωξρυρηρνϲξεαγεαϲαϲτοαϲωθειιυνδνδξλονυταολαϲαττμτννοερτεοροανιεκτεεαιιϲωεαμϲωικμτποκϲϲιορϲπμοκαιουτωτδοωαξεαγωεφτωυπμαλυττταεομττλυαεπατονεαξτομυχαωηνυοβωπτυυκξαπιτααπυενεροοτϲαααυηοανηλταιθεαντινοιλκιβπγοδαιοηωαδαετακυϲοηυουαυνωαεαοττυαεεωτανεκβγε"), | |
#(process_json_files(1, 1, 21, rounds="3", length=0), ""), | |
#(process_json_files(1, 1, 22, rounds="1", length=0), ""), | |
#(process_json_files(1, 1, 22, rounds="3", length=0), ""), | |
#(process_json_files(1, 1, 23, rounds="3", length=0), ""), | |
#(process_json_files(1, 1, 11, rounds="1", length=0), ""), | |
#(process_json_files(1, 1, 2, rounds="1", length=0), ""), | |
#(process_json_files(1, 1, 23, rounds="1", length=0), None), # Expect None, when no results | |
#(process_json_files(1, 1, 23, rounds="-1", length=0), None), # Expect None, when no results | |
#(process_json_files(1, 1, 22, rounds="-1", length=0), ""), | |
#(process_json_files(1, 1, 22, rounds="-2", length=0), ""), | |
#(process_json_files(1, 1, 1, rounds="-1", length=0), ""), # Reversed Hebrew alphabet | |
#(process_json_files(1, 1, 1, rounds="1,-1", length=0), ""), # Combined rounds | |
#(process_json_files(1, 1, 22, rounds="1,-1", length=0, average_compile=True), ""), # average compile test (400+1) / 2 = math.ceil(200.5)=201=200+1="רא" | |
] | |
all_tests_passed = True | |
for result, expected in test_results: | |
if expected is None: # Check if no result is expected | |
if not result: | |
logger.warning(f"Test passed: Expected no results, got no results.") | |
else: | |
logger.error(f"Test failed: Expected no results, but got: {result}") | |
all_tests_passed = False | |
else: | |
# Check if result is not empty before accessing elements | |
if result: | |
result_text = result[0]['result_text'] | |
if result_text == expected: | |
logger.warning(f"Test passed: Expected '{expected}', got '{result_text}'") | |
else: | |
logger.error(f"Test failed: Expected '{expected}', but got '{result_text}'") | |
all_tests_passed = False | |
else: | |
logger.error(f"Test failed: Expected '{expected}', but got no results") | |
all_tests_passed = False | |
if all_tests_passed: | |
logger.info("All round tests passed.") | |
[File Ends] bible.py | |
[File Begins] database-structure.txt | |
Gematria Sum, Words, Translation, Book, Chapter, Verse, Phrase Length, Phrase Position | |
913 בראשית Genesis 1 1 1 1-1 | |
1116 בראשית ברא Genesis 1 1 2 1-2 | |
1762 בראשית ברא אלהים Genesis 1 1 3 1-3 | |
2163 בראשית ברא אלהים את Genesis 1 1 4 1-4 | |
3118 בראשית ברא אלהים את השמים Genesis 1 1 5 1-5 | |
3525 בראשית ברא אלהים את השמים ואת Genesis 1 1 6 1-6 | |
[File Ends] database-structure.txt | |
[File Begins] els_cache.db.initial | |
SQLite format 3 @ .zp | |
3 3 mtableels_cacheels_cacheCREATE TABLE els_cache ( | |
query_hash TEXT PRIMARY KEY, | |
results TEXT | |
)1E indexsqlite_autoindex_els_cache_1els_cache | |