File size: 13,442 Bytes
e806249
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
import logging
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)

import gradio as gr
import torah
import bible
import quran
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
import math
import json
import re


def create_language_dropdown(label, default_value='en', show_label=True):
    """Creates a Gradio dropdown menu for language selection."""
    languages = GoogleTranslator(source='en', target='en').get_supported_languages(as_dict=True)
    return gr.Dropdown(
      choices=list(languages.keys()),
      label=label,
      value=default_value,
      show_label=show_label
    )

def calculate_gematria_sum(text, date_words):
    """Calculates the Gematria sum for a text and date words."""
    if text and date_words: # Only calculate if both inputs are provided
        combined_input = f"{text} {date_words}"
        logger.info(f"Combined input for Gematria: {combined_input}")
        sum_value = calculate_gematria(strip_diacritics(combined_input))
        logger.info(f"Gematria sum: {sum_value}")
        return sum_value
    else:
        return None

def perform_els_search(step, rounds_combination, tlang, strip_spaces, strip_in_braces, strip_diacritics_chk, merge_results, include_torah, include_bible, include_quran):  # Removed start and end parameters
    """Performs the Equidistant Letter Sequences (ELS) search based on the selected scriptures."""
    logger.info("Starting ELS search...")
    if step == 0 or rounds_combination == "0,0":
        logger.info("Cant search with step 0 or rounds_combination 0,0")
        return None
    
    torah_results = []
    bible_results = []
    quran_results = []
    
    if include_torah:
        torah_results.extend(torah.process_json_files(1, 39, step, rounds_combination, 0, tlang, strip_spaces, strip_in_braces, strip_diacritics))  # Torah books 1-39
    
    if include_bible:
        bible_results.extend(bible.process_json_files(40, 66, step, rounds_combination, 0, tlang, strip_spaces, strip_in_braces, strip_diacritics))  # Bible books 40-66
    
    if include_quran:
        quran_results.extend(quran.process_json_files(1, 114, step, rounds_combination, 0, tlang, strip_spaces, strip_in_braces, strip_diacritics))  # Quran books 1-114

    # Merge results based on merge_results flag
    if merge_results:
        results = []
        max_length = max(len(torah_results), len(bible_results), len(quran_results))
        for i in range(max_length):
            if i < len(torah_results):
                results.append(torah_results[i])
            if i < len(bible_results):
                results.append(bible_results[i])
            if i < len(quran_results):
                results.append(quran_results[i])
    else:
        results = torah_results + bible_results + quran_results

    df = pd.DataFrame(results)
    df.index = range(1, len(df) + 1)
    df.reset_index(inplace=True)
    df.rename(columns={'index': 'Result Number'}, inplace=True)
    logger.info(f"ELS search results: {df}")
    return df

def generate_json_dump(start, end, step, rounds_combination, tlang, strip_spaces, strip_in_braces, strip_diacritics_chk, search_phrase, results_df):
    """Generates the JSON dump with both configuration and results."""
    config = {
        "Start Book": start,
        "End Book": end,
        "Step": step,
        "Rounds": rounds_combination,
        "Target Language": tlang,
        "Strip Spaces": strip_spaces,
        "Strip Text in Braces": strip_in_braces,
        "Strip Diacritics": strip_diacritics_chk,
        "Search Phrase": search_phrase
    }
    result = {
        "Configuration": config,
        "Results": json.loads(results_df.to_json(orient='records', force_ascii=False))
    }
    logger.info(f"Generated JSON dump: {result}")
    return json.dumps(result, indent=4, ensure_ascii=False)

def download_json_file(config_json, step, rounds_combination, strip_spaces, strip_in_braces, strip_diacritics_chk):
    """Downloads the JSON config file with a descriptive name."""
    filename_suffix = ""
    if strip_spaces:
        filename_suffix += "-stSp"
    if strip_in_braces:
        filename_suffix += "-stBr"
    if strip_diacritics_chk:
        filename_suffix += "-stDc"
    file_path = f"step-{step}-rounds-{rounds_combination}{filename_suffix}.json"  # Include rounds in filename
    with open(file_path, "w", encoding='utf-8') as file:
        file.write(config_json)
    logger.info(f"Downloaded JSON file to: {file_path}")
    return file_path

# --- Load Forbidden Names ---
def load_forbidden_names(filename="c.txt"):
    """Loads forbidden names from the specified file."""
    try:
        with open(filename, "r", encoding='utf-8') as f:
            forbidden_names = [line.strip() for line in f]
        return forbidden_names
    except FileNotFoundError:
        print(f"Error: Forbidden names file '{filename}' not found.")
        return []

# --- Name Similarity Check ---
def check_name_similarity(name, forbidden_names, threshold=80):
    """Checks if a name is similar to any forbidden name."""
    from fuzzywuzzy import fuzz
    for forbidden_name in forbidden_names:
        similarity_ratio = fuzz.ratio(name.lower(), forbidden_name.lower())
        if similarity_ratio >= threshold:
            logging.info(f"Forbidden word {forbidden_name} detected in: {name}")
            return True
    return False

# --- UI Components ---

with gr.Blocks() as app:
    with gr.Row():
        tlang = create_language_dropdown("Target Language for Translation", default_value='english')
        selected_date = Calendar(type="datetime", label="Date to investigate (optional)", info="Pick a date from the calendar")
        date_language_input = create_language_dropdown("Language of the person/topic (optional) (Date Word Language)", default_value='english')
        date_words_output = gr.Textbox(label="Date in Words Translated (optional)")

    with gr.Row():
        gematria_text = gr.Textbox(label="Name and/or Topic (required)", value="Hans Albert Einstein")
        gematria_result = gr.Number(label="Journal Sum")

    with gr.Row():
        #start = gr.Number(label="Start Book", value=1)
        #end = gr.Number(label="End Book", value=180)
        step = gr.Number(label="Jump Width (Steps) for ELS")
        #rounds = gr.Number(label="Rounds through Books", value=1)
        float_step = gr.Number(visible=False, value=1)  # For half/double step calculations
        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)
            
        #average_combine_chk = gr.Checkbox(label="Average-Combine Combined Rounds (hacky)", value=False)
        #mirror_book_numbers = gr.Checkbox(label="Mirror book numbers for negative rounds (axis=book 20)", value=False)

        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)
        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)
        acknowledgment_chk = gr.Checkbox(
            label="The User of this App or this Api acknowledges that the results may be prone to bugs or translation errors. The User hereby accepts that the User will not harm or stalk anyone with this information, or bet on any of this information, in any regards.",  # Add your full disclaimer here
            value=True
        )

    translate_btn = gr.Button("Search with ELS")

    markdown_output = gr.Dataframe()
    json_output = gr.Textbox(label="JSON Configuration Output")
    json_download_btn = gr.Button("Prepare .json for Download")
    json_file = gr.File(label="Download Config JSON", file_count="single")

    # --- Load Forbidden Names ---

    forbidden_names = load_forbidden_names()

    # --- Event Handlers ---


    def update_date_words(selected_date, date_language_input):
        """Automatically updates the date words when the date or language changes."""
        return translate_date_to_words(selected_date, date_language_input)

    def update_journal_sum(gematria_text, date_words_output):
        """Automatically updates the journal sum when the text or date words change."""
        return calculate_journal_sum(gematria_text, date_words_output)

    def update_rounds_combination(round_x, round_y):
        """Updates the rounds_combination textbox based on round_x and round_y."""
        return f"{int(round_x)},{int(round_y)}"


    def calculate_journal_sum(text, date_words):
        """Calculates the journal sum and updates the step value."""
        if check_name_similarity(text, forbidden_names):
            return 0, 0, 0  # Raise an error if the name is forbidden
        if check_name_similarity(date_words, forbidden_names):
            return 0, 0, 0  # Raise an error if the name is forbidden
        sum_value = calculate_gematria_sum(text, date_words)
        return sum_value, sum_value, sum_value  # Returning the same value three times

    def update_step_half(float_step):
        """Updates the step value to half."""
        new_step = math.ceil(float_step / 2)
        return new_step, float_step / 2

    def update_step_double(float_step):
        """Updates the step value to double."""
        new_step = math.ceil(float_step * 2)
        return new_step, float_step * 2


    # Update rounds_combination when round_x or round_y changes
    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)

    # Trigger date word calculation on date or language change
    selected_date.change(update_date_words, inputs=[selected_date, date_language_input], outputs=[date_words_output])
    date_language_input.change(update_date_words, inputs=[selected_date, date_language_input], outputs=[date_words_output])

    # Trigger journal sum calculation on text or date word change
    gematria_text.change(update_journal_sum, inputs=[gematria_text, date_words_output], outputs=[gematria_result, step, float_step]) # Add float_step here
    date_words_output.change(update_journal_sum, inputs=[gematria_text, date_words_output], outputs=[gematria_result, step, float_step]) # Add float_step here

    def handle_json_download(config_json, step, rounds_combination, strip_spaces, strip_in_braces, strip_diacritics_chk):
        """Handles the download of the JSON config file."""
        return download_json_file(config_json, step, rounds_combination, strip_spaces, strip_in_braces, strip_diacritics_chk)

    def perform_search_and_create_json(step, rounds_combination, tlang, strip_spaces, strip_in_braces, strip_diacritics_chk, gematria_text, date_words_output, merge_results, include_torah, include_bible, include_quran):
        """Performs the ELS search, creates the JSON config, and displays the results."""
        df = perform_els_search(step, rounds_combination, tlang, strip_spaces, strip_in_braces, strip_diacritics_chk, merge_results, include_torah, include_bible, include_quran)  # Removed start, end arguments
        search_phrase = f"{date_words_output} {gematria_text}"
        config_json = generate_json_dump(1, 180, step, rounds_combination, tlang, strip_spaces, strip_in_braces, strip_diacritics_chk, search_phrase, df)  # Use dummy values for start and end for JSON dump
        return config_json, df


    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_and_create_json,
        inputs=[step, rounds_combination, tlang, strip_spaces, 
                strip_in_braces, strip_diacritics_chk, gematria_text, date_words_output, 
                merge_results_chk, include_torah_chk, include_bible_chk, include_quran_chk],
        outputs=[json_output, markdown_output]
    )

    json_download_btn.click(
        handle_json_download,
        inputs=[json_output, step, rounds_combination, strip_spaces, strip_in_braces, strip_diacritics_chk],  # Pass rounds to download function
        outputs=[json_file]
    )


    app.load(
        update_date_words, 
        inputs=[selected_date, date_language_input], 
        outputs=[date_words_output]
    )
    app.load(
        update_journal_sum, 
        inputs=[gematria_text, date_words_output], 
        outputs=[gematria_result, step, float_step]
    )

if __name__ == "__main__":
    app.launch(share=False)