File size: 6,641 Bytes
f054e62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
import logging
import argparse
import sys
import os
import re
import math
from gematria import calculate_gematria, HEBREW_GEMATRIA_VALUES

# --- Konfiguration ---
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
BOOK_RANGE = range(1, 40)
INDICES_DIR = "indices_by_book"

# --- Neue Kernfunktionen ---

def xor_with_highest_power(total_sum, query_value):
    """
    Ihre neue XOR-Logik.
    """
    if total_sum <= 0 or query_value <= 1:
        logging.error("Summen und Anfrage-Wert müssen positiv und > 1 sein.")
        return None

    if query_value > total_sum:
        # Wenn der Query-Wert größer als die Summe ist, ist die höchste Potenz 1 (query^0)
        power = 1
    else:
        # Finde die höchste Potenz
        exponent = math.floor(math.log(total_sum, query_value))
        power = query_value ** exponent

    xor_result = total_sum ^ power
    logging.info(f"Kanon-Summe: {total_sum}, Anfrage-Wert: {query_value}")
    logging.info(f"Höchste Potenz von {query_value} <= {total_sum} ist {query_value}^{exponent} = {power}")
    logging.info(f"XOR-Ergebnis: {total_sum} ^ {power} = {xor_result}")
    return xor_result

def prepare_phrase_inventory(all_indices):
    """
    Erstellt eine flache Liste aller einzigartigen Phrasen aus allen Büchern,
    zusammen mit ihrem Gematria-Wert und ihrem Netzwerk-Score.
    """
    logging.info("Erstelle ein Inventar aller Phrasen aus 39 Büchern...")
    inventory = []
    seen_phrases = set()
    for book_num, index in all_indices.items():
        for gematria_val_str, data in index.items():
            gematria_val = int(gematria_val_str)
            pagerank = data.get('pagerank', 0)
            for phrase_data in data.get('phrases', []):
                phrase_text = phrase_data['text']
                if phrase_text not in seen_phrases:
                    count = phrase_data.get('count', 1)
                    # Definiere den "Bedeutungs-Score" (network)
                    score = pagerank / count if count > 0 else 0
                    inventory.append({
                        "text": phrase_text,
                        "gematria": gematria_val,
                        "score": score,
                        "source_book": book_num
                    })
                    seen_phrases.add(phrase_text)

    # Sortiere das Inventar, um Phrasen mit hohem Score und kleinem Wert zu bevorzugen
    inventory.sort(key=lambda x: (-x['score'], x['gematria']))
    logging.info(f"{len(inventory)} einzigartige Phrasen im Inventar gefunden.")
    return inventory

def find_phrase_combination(target_sum, inventory):
    """
    Findet eine Kombination von Phrasen, die die Ziel-Summe ergibt,
    indem es die Phrasen mit dem höchsten Score bevorzugt (Greedy-Algorithmus).
    """
    logging.info(f"Suche nach einer bedeutungsvollen Phrasen-Kombination für die Ziel-Summe: {target_sum}...")

    combination = []
    current_sum = 0

    # Gehe durch das nach Bedeutung sortierte Inventar
    for item in inventory:
        # Wenn die Phrase passt, ohne die Summe zu überschreiten, füge sie hinzu
        if current_sum + item['gematria'] <= target_sum:
            combination.append(item)
            current_sum += item['gematria']
            logging.debug(f"  + Phrase '{item['text']}' (G:{item['gematria']}) hinzugefügt. Aktuelle Summe: {current_sum}")

    logging.info(f"Kombination gefunden. Erreichte Summe: {current_sum} (Differenz zur Ziel-Summe: {target_sum - current_sum})")
    return combination

# --- Hauptprogramm ---

def main(args):
    # Lade alle Indizes
    all_indices = {}
    for i in BOOK_RANGE:
        index_path = os.path.join(INDICES_DIR, f"book_{i:02}_index.json")
        if os.path.exists(index_path):
            with open(index_path, 'r', encoding='utf-8') as f:
                all_indices[i] = json.load(f)
    if not all_indices:
        sys.exit("Keine Index-Dateien gefunden. Bitte 'build_indices.py' ausführen.")

    # 1. Berechne die Gematria-Summe jedes Buches und die Kanon-Summe
    logging.info("Berechne Gematria-Summen für jedes Buch...")
    kanon_sum = 0
    for i in BOOK_RANGE:
        book_sum = 0
        try:
            with open(f"texts/torah/{i:02}.json", 'r', encoding='utf-8') as file:
                data = json.load(file)
                full_text = ' '.join([' '.join(block) for block in data.get("text", [])])
                clean_text = re.sub(r"[^\u05D0-\u05EA]+", "", re.sub(r"\[.*?\]", "", full_text, flags=re.DOTALL))
                book_sum = calculate_gematria(clean_text)
                logging.debug(f"Buch {i:02}: Summe = {book_sum}")
                kanon_sum += book_sum
        except FileNotFoundError:
            continue
    logging.info(f"Gesamte Kanon-Summe berechnet: {kanon_sum}")

    # 2. Berechne den Gematria-Wert der Anfrage
    query_value = calculate_gematria(args.query)
    if query_value <= 1:
        sys.exit(f"Anfrage '{args.query}' hat einen ungültigen Gematria-Wert ({query_value}). Wert muss > 1 sein.")

    # 3. Wende die neue XOR-Operation an
    target_sum = xor_with_highest_power(kanon_sum, query_value)
    if target_sum is None:
        sys.exit("Fehler bei der XOR-Berechnung.")

    # 4. Bereite das Phrasen-Inventar vor
    phrase_inventory = prepare_phrase_inventory(all_indices)

    # 5. Finde die Phrasen-Kombination
    result_combination = find_phrase_combination(target_sum, phrase_inventory)

    # 6. Gib das Ergebnis aus
    print("\n" + "="*15 + " ERGEBNIS DER KONSEPTIONELLEN SUMMEN-ANALYSE " + "="*15)
    print(f"Anfrage: '{args.query}' (Gematria: {query_value})")
    print(f"Kanon-Summe: {kanon_sum}")
    print(f"Ziel-Summe nach XOR: {target_sum}")
    print("-" * 50)

    final_sum = 0
    if result_combination:
        print("Gefundene Phrasen-Kombination (geordnet nach Bedeutung):")
        for item in result_combination:
            final_sum += item['gematria']
            print(f"- {item['text']:<25} (G: {item['gematria']:<5} | Score: {item['score']:.4f} | Quelle: B{item['source_book']:02d})")
        print("-" * 50)
        print(f"Gesamtsumme der gefundenen Phrasen: {final_sum}")
        print(f"Differenz zum Ziel: {target_sum - final_sum} (Dieser Rest konnte nicht mit hoch-relevanten Phrasen gefüllt werden)")
    else:
        print("Keine passende Phrasen-Kombination gefunden.")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Conceptual Sum Gematria Engine.")
    parser.add_argument("query", type=str, help="Die Abfragephrase (z.B. 'יהוה').")
    args = parser.parse_args()
    main(args)