File size: 10,477 Bytes
2ecf673
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
# ============================================================
# AQARIONZ β€” POLYGLOT RESEARCH, SIMULATION & TRAINING ENGINE
# ============================================================
# Fully Integrated Domains:
# - Audio FFT analysis
# - Laser audio modulation (simulated)
# - Solar / photodiode reception (simulated)
# - Cymatic visualization
# - Experiment logging
# - Memory system
# - Knowledge graph (nodes + relations)
# - Creative output tracking
# - Full JSON export for training pipelines
# ============================================================

import os
import json
import uuid
import sqlite3
import datetime
from typing import Dict, Any

import numpy as np
import gradio as gr
import matplotlib.pyplot as plt

# ============================================================
# CONFIG
# ============================================================
DB_PATH = "aqarionz_system.db"
EXPORT_DIR = "exports"
os.makedirs(EXPORT_DIR, exist_ok=True)

# ============================================================
# DATABASE LAYER
# ============================================================
class AqarionzDB:
    def __init__(self, path=DB_PATH):
        self.conn = sqlite3.connect(path, check_same_thread=False)
        self.conn.row_factory = sqlite3.Row
        self._init_schema()

    def _init_schema(self):
        c = self.conn.cursor()

        c.execute("""
        CREATE TABLE IF NOT EXISTS experiments (
            id TEXT PRIMARY KEY,
            timestamp TEXT,
            description TEXT,
            parameters TEXT,
            results TEXT
        )
        """)

        c.execute("""
        CREATE TABLE IF NOT EXISTS memories (
            id TEXT PRIMARY KEY,
            timestamp TEXT,
            content TEXT,
            emotion TEXT,
            tags TEXT,
            source TEXT
        )
        """)

        c.execute("""
        CREATE TABLE IF NOT EXISTS creative_outputs (
            id TEXT PRIMARY KEY,
            timestamp TEXT,
            title TEXT,
            content TEXT,
            tags TEXT
        )
        """)

        c.execute("""
        CREATE TABLE IF NOT EXISTS knowledge_nodes (
            id TEXT PRIMARY KEY,
            label TEXT,
            description TEXT,
            tags TEXT,
            created_at TEXT
        )
        """)

        c.execute("""
        CREATE TABLE IF NOT EXISTS relationships (
            id TEXT PRIMARY KEY,
            from_id TEXT,
            to_id TEXT,
            relation TEXT,
            weight REAL,
            created_at TEXT
        )
        """)

        self.conn.commit()

    def _now(self):
        return datetime.datetime.utcnow().isoformat()

    # ---------------- INSERT ----------------
    def log_experiment(self, desc, params, results):
        eid = str(uuid.uuid4())
        self.conn.execute(
            "INSERT INTO experiments VALUES (?, ?, ?, ?, ?)",
            (eid, self._now(), desc, json.dumps(params), json.dumps(results))
        )
        self.conn.commit()
        return eid

    def add_memory(self, content, emotion, tags, source="user"):
        mid = str(uuid.uuid4())
        self.conn.execute(
            "INSERT INTO memories VALUES (?, ?, ?, ?, ?, ?)",
            (mid, self._now(), content, emotion, tags, source)
        )
        self.conn.commit()
        return mid

    def add_creative(self, title, content, tags):
        cid = str(uuid.uuid4())
        self.conn.execute(
            "INSERT INTO creative_outputs VALUES (?, ?, ?, ?, ?)",
            (cid, self._now(), title, content, tags)
        )
        self.conn.commit()
        return cid

    def add_node(self, label, description, tags):
        nid = str(uuid.uuid4())
        self.conn.execute(
            "INSERT INTO knowledge_nodes VALUES (?, ?, ?, ?, ?)",
            (nid, label, description, tags, self._now())
        )
        self.conn.commit()
        return nid

    def add_relationship(self, from_id, to_id, relation, weight):
        rid = str(uuid.uuid4())
        self.conn.execute(
            "INSERT INTO relationships VALUES (?, ?, ?, ?, ?, ?)",
            (rid, from_id, to_id, relation, weight, self._now())
        )
        self.conn.commit()
        return rid

    # ---------------- EXPORT ----------------
    def export_all(self):
        data = {}
        for table in [
            "experiments",
            "memories",
            "creative_outputs",
            "knowledge_nodes",
            "relationships"
        ]:
            rows = self.conn.execute(f"SELECT * FROM {table}").fetchall()
            data[table] = [dict(r) for r in rows]

        path = os.path.join(EXPORT_DIR, f"aqarionz_export_{uuid.uuid4()}.json")
        with open(path, "w", encoding="utf-8") as f:
            json.dump(data, f, indent=2)

        return path

db = AqarionzDB()

# ============================================================
# SIGNAL PROCESSING
# ============================================================
def compute_fft(audio, sr):
    freqs = np.fft.rfftfreq(len(audio), 1 / sr)
    mags = np.abs(np.fft.rfft(audio))
    return freqs, mags

def modulate_laser(audio, depth=0.5):
    norm = audio / (np.max(np.abs(audio)) + 1e-9)
    return norm * depth

def simulate_solar(laser_signal):
    noise = np.random.normal(0, 0.02, size=laser_signal.shape)
    return laser_signal + noise

def cymatic_plot(freqs, mags):
    fig, ax = plt.subplots(figsize=(4, 4))
    ax.pcolormesh(
        freqs,
        np.arange(len(mags)),
        np.tile(mags, (len(mags), 1)),
        shading="auto"
    )
    ax.set_title("Cymatic Pattern (Synthetic)")
    ax.set_xlabel("Frequency (Hz)")
    ax.set_ylabel("Mode Index")
    plt.tight_layout()
    return fig

# ============================================================
# INFERENCE HELPERS
# ============================================================
def infer_emotion(text):
    t = text.lower()
    if any(w in t for w in ["love", "hope", "joy", "peace"]):
        return "positive"
    if any(w in t for w in ["fear", "anger", "sad", "loss"]):
        return "negative"
    if any(w in t for w in ["why", "how", "what"]):
        return "curious"
    return "neutral"

def auto_tags(text):
    keys = []
    for k in ["system", "signal", "memory", "knowledge", "future", "graph", "audio"]:
        if k in text.lower():
            keys.append(k)
    return ",".join(keys)

# ============================================================
# UI ACTIONS
# ============================================================
def audio_fft_ui(file):
    if file is None:
        return None, "No audio provided"

    sr, data = file
    data = data.astype(np.float32)

    freqs, mags = compute_fft(data, sr)
    peak = float(freqs[np.argmax(mags)])

    eid = db.log_experiment(
        "Audio FFT Analysis",
        {"sample_rate": sr, "length": len(data)},
        {"peak_frequency": peak}
    )

    fig = cymatic_plot(freqs, mags)
    return fig, f"Experiment {eid}\nPeak Frequency: {peak:.2f} Hz"

def laser_sim_ui(file):
    if file is None:
        return "No audio provided"

    sr, audio = file
    audio = audio.astype(np.float32)

    laser = modulate_laser(audio)
    solar = simulate_solar(laser)

    f_tx, m_tx = compute_fft(laser, sr)
    f_rx, m_rx = compute_fft(solar, sr)

    result = {
        "tx_peak": float(f_tx[np.argmax(m_tx)]),
        "rx_peak": float(f_rx[np.argmax(m_rx)])
    }

    eid = db.log_experiment(
        "Laser β†’ Solar Simulation",
        {"sample_rate": sr},
        result
    )

    return f"Experiment {eid}\nTX Peak: {result['tx_peak']:.1f} Hz\nRX Peak: {result['rx_peak']:.1f} Hz"

def add_memory_ui(text):
    emotion = infer_emotion(text)
    tags = auto_tags(text)
    mid = db.add_memory(text, emotion, tags)
    return f"Memory stored\nID: {mid}\nEmotion: {emotion}\nTags: {tags}"

def add_creative_ui(title, content):
    tags = auto_tags(content)
    cid = db.add_creative(title, content, tags)
    return f"Creative output saved\nID: {cid}"

def add_node_ui(label, desc):
    tags = auto_tags(desc)
    nid = db.add_node(label, desc, tags)
    return f"Knowledge node created\nID: {nid}"

def link_nodes_ui(from_id, to_id, relation, weight):
    rid = db.add_relationship(from_id, to_id, relation, weight)
    return f"Relationship created\nID: {rid}"

def export_ui():
    path = db.export_all()
    return f"Export complete:\n{path}"

# ============================================================
# GRADIO UI
# ============================================================
with gr.Blocks(title="AQARIONZ POLYGLOT ENGINE") as app:
    gr.Markdown("""
# 🌐 AQARIONZ POLYGLOT RESEARCH & TRAINING ENGINE
Signal β€’ Simulation β€’ Memory β€’ Knowledge β€’ Export
""")

    with gr.Tabs():

        with gr.Tab("πŸ”Š Audio FFT"):
            audio_in = gr.Audio(type="numpy")
            plot = gr.Plot()
            txt = gr.Textbox()
            gr.Button("Run FFT").click(audio_fft_ui, audio_in, [plot, txt])

        with gr.Tab("πŸ”¦ Laser / Solar"):
            laser_audio = gr.Audio(type="numpy")
            out = gr.Textbox()
            gr.Button("Simulate").click(laser_sim_ui, laser_audio, out)

        with gr.Tab("πŸ“ Memory"):
            mem = gr.Textbox(lines=6)
            mem_out = gr.Textbox(lines=6)
            gr.Button("Store").click(add_memory_ui, mem, mem_out)

        with gr.Tab("✨ Creative"):
            title = gr.Textbox()
            content = gr.Textbox(lines=6)
            cre_out = gr.Textbox(lines=6)
            gr.Button("Save").click(add_creative_ui, [title, content], cre_out)

        with gr.Tab("🧠 Knowledge"):
            label = gr.Textbox()
            desc = gr.Textbox(lines=6)
            node_out = gr.Textbox()
            gr.Button("Create Node").click(add_node_ui, [label, desc], node_out)

        with gr.Tab("πŸ”— Relations"):
            f = gr.Textbox(label="From ID")
            t = gr.Textbox(label="To ID")
            r = gr.Textbox(label="Relation")
            w = gr.Slider(0, 10, value=1)
            rel_out = gr.Textbox()
            gr.Button("Link").click(link_nodes_ui, [f, t, r, w], rel_out)

        with gr.Tab("πŸ“¦ Export"):
            exp_out = gr.Textbox(lines=6)
            gr.Button("Export All").click(export_ui, None, exp_out)

    gr.Markdown("""
---
**State:** Unified  
**Mode:** Simulation + Research + Training  
**Output:** JSON / DB / ML-ready
""")

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