File size: 22,139 Bytes
05a8c83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24be2e1
05a8c83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24be2e1
 
05a8c83
 
 
24be2e1
05a8c83
 
 
 
 
 
 
 
 
24be2e1
05a8c83
 
24be2e1
 
 
 
 
05a8c83
24be2e1
 
 
 
 
 
 
 
 
 
05a8c83
24be2e1
 
05a8c83
24be2e1
05a8c83
24be2e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
05a8c83
 
 
 
 
 
24be2e1
05a8c83
 
24be2e1
05a8c83
 
24be2e1
05a8c83
 
24be2e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
05a8c83
24be2e1
 
 
 
 
 
05a8c83
24be2e1
 
 
 
 
 
 
ee5a998
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24be2e1
ee5a998
24be2e1
 
 
ee5a998
24be2e1
 
ee5a998
 
 
 
 
24be2e1
 
 
 
 
 
 
 
9fdf32e
 
24be2e1
 
 
 
ee5a998
9fdf32e
 
 
24be2e1
 
9fdf32e
24be2e1
9fdf32e
 
24be2e1
 
ee5a998
 
24be2e1
 
 
 
 
 
 
 
 
 
 
ee5a998
24be2e1
 
 
ee5a998
 
 
 
 
 
 
24be2e1
 
 
ee5a998
 
24be2e1
 
ee5a998
 
 
 
 
 
 
 
 
24be2e1
 
 
 
 
 
 
 
 
ee5a998
 
 
 
 
24be2e1
 
 
 
 
 
 
 
 
 
ee5a998
 
 
 
 
 
 
 
 
 
24be2e1
05a8c83
 
 
 
 
 
 
 
 
 
24be2e1
05a8c83
 
 
24be2e1
05a8c83
24be2e1
 
05a8c83
 
24be2e1
05a8c83
 
aba4571
 
 
 
 
 
 
 
05a8c83
24be2e1
 
 
 
 
 
 
 
 
 
05a8c83
 
24be2e1
05a8c83
24be2e1
05a8c83
 
24be2e1
05a8c83
 
24be2e1
05a8c83
 
 
 
24be2e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
05a8c83
 
24be2e1
05a8c83
24be2e1
 
 
 
 
 
 
 
 
05a8c83
 
 
 
24be2e1
05a8c83
 
 
 
 
24be2e1
05a8c83
 
aba4571
 
 
 
 
 
 
 
05a8c83
24be2e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
05a8c83
 
bd1690c
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
"""
TBO Oracle - Hugging Face Space
================================
Temporal Bispectral Operator for blockchain-anchored predictions.

"THE SHAPE IS THE ORACLE" - We reveal, not compute.
"""

import gradio as gr
import numpy as np
import hashlib
import time
from datetime import datetime, timezone
from scipy import stats

# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
# TBO CORE FUNCTIONS
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

def compute_cross_bispectrum_fast(signal, nfft=None):
    """Vectorized bispectrum computation."""
    signal = np.asarray(signal, dtype=np.float64)
    N = len(signal)
    if nfft is None:
        nfft = N
    X = np.fft.fft(signal, n=nfft)
    idx = np.arange(nfft)
    i_grid, j_grid = np.meshgrid(idx, idx, indexing='ij')
    k_grid = (i_grid + j_grid) % nfft
    B = X[i_grid] * X[j_grid] * np.conj(X[k_grid])
    return B


def compute_tbo_scalar(signal, nfft=None):
    """Compute the TBO scalar Lambda."""
    signal = np.asarray(signal, dtype=np.float64)
    N = len(signal)
    if nfft is None:
        nfft = N
    B = compute_cross_bispectrum_fast(signal, nfft=nfft)
    half = nfft // 2
    mask = np.zeros((nfft, nfft), dtype=bool)
    for i in range(1, half):
        for j in range(1, half):
            if i + j < half:
                mask[i, j] = True
    magnitudes = np.abs(B[mask])
    if len(magnitudes) == 0:
        return 0.0
    return float(np.mean(magnitudes))


def compute_tbo_zscore(signal, n_null=100, seed=None):
    """Compute z-score relative to null distribution."""
    rng = np.random.default_rng(seed)
    signal = np.asarray(signal, dtype=np.float64)
    lam_obs = compute_tbo_scalar(signal)
    null_lambdas = np.empty(n_null)
    for i in range(n_null):
        perm = rng.permutation(signal)
        null_lambdas[i] = compute_tbo_scalar(perm)
    mu = np.mean(null_lambdas)
    sigma = np.std(null_lambdas, ddof=1)
    if sigma < 1e-15:
        sigma = 1e-15
    z = (lam_obs - mu) / sigma
    return float(z), float(lam_obs), float(mu), float(sigma), null_lambdas


def classify_signal(z_score):
    """Classify based on z-score."""
    if z_score < -1.96:
        return 'DEFICIT'
    elif z_score > 1.96:
        return 'EXCESS'
    return 'NORMAL'


def _sieve_primes(limit):
    """Sieve of Eratosthenes."""
    is_prime = [True] * (limit + 1)
    is_prime[0] = is_prime[1] = False
    for i in range(2, int(limit**0.5) + 1):
        if is_prime[i]:
            for j in range(i * i, limit + 1, i):
                is_prime[j] = False
    return [i for i in range(2, limit + 1) if is_prime[i]]


def generate_cyclotomic(N, order=7, seed=None):
    """Generate cyclotomic signal with prime harmonics."""
    rng = np.random.default_rng(seed)
    t = np.arange(N, dtype=np.float64)
    primes = _sieve_primes(N // 2)[:order]
    signal = np.zeros(N)
    for p in primes:
        amp = rng.uniform(0.5, 2.0)
        phase = rng.uniform(0, 2 * np.pi)
        signal += amp * np.sin(2 * np.pi * p * t / N + phase)
    signal += 0.1 * rng.standard_normal(N)
    return signal


# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
# SIGNAL COLLECTORS
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

def collect_entropy(n=256, seed=None):
    """System entropy signal."""
    rng = np.random.default_rng(seed)
    arr = rng.integers(0, 2**32, size=n, dtype=np.uint32).astype(np.float64)
    return (arr - arr.mean()) / (arr.std() + 1e-15)


def collect_clock_jitter(n=256):
    """Clock timing jitter."""
    timestamps = []
    for _ in range(n * 4):
        timestamps.append(time.perf_counter_ns())
    deltas = np.diff(timestamps).astype(np.float64)
    block = len(deltas) // n
    signal = np.array([deltas[i*block:(i+1)*block].mean() for i in range(n)])
    return (signal - signal.mean()) / (signal.std() + 1e-15)


def collect_hash_chain(n=256, seed=None):
    """SHA-256 hash chain."""
    rng = np.random.default_rng(seed)
    h = rng.bytes(32)
    values = np.empty(n, dtype=np.float64)
    for i in range(n):
        h = hashlib.sha256(h + i.to_bytes(4, 'big')).digest()
        values[i] = float(int.from_bytes(h[:4], 'big'))
    return (values - values.mean()) / (values.std() + 1e-15)


def collect_cyclotomic(n=256, seed=None):
    """Cyclotomic calibration signal."""
    signal = generate_cyclotomic(n, order=7, seed=seed)
    return (signal - signal.mean()) / (signal.std() + 1e-15)


# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
# ORACLE PREDICTION
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

def run_oracle_prediction(question: str, deadline: str, n_samples: int = 256, n_null: int = 100):
    """Run full TBO Oracle prediction."""
    
    # Generate question-based seed
    q_hash = hashlib.sha256(question.encode()).hexdigest()
    base_seed = int(q_hash[:8], 16)
    
    # Collect signals from 4 sources
    sources = {
        "entropy": collect_entropy(n_samples, seed=base_seed),
        "clock": collect_clock_jitter(n_samples),
        "hash_chain": collect_hash_chain(n_samples, seed=base_seed + 1),
        "cyclotomic": collect_cyclotomic(n_samples, seed=base_seed + 2),
    }
    
    results = {}
    predictions = []
    z_scores = []
    
    for name, signal in sources.items():
        z, lam, mu, sigma, null_dist = compute_tbo_zscore(signal, n_null=n_null, seed=base_seed)
        classification = classify_signal(z)
        prediction = 1 if z < -1.96 else 0
        
        results[name] = {
            "z_score": round(z, 4),
            "lambda": round(lam, 6),
            "classification": classification,
            "prediction": "YES" if prediction else "NO",
        }
        predictions.append(prediction)
        z_scores.append(abs(z))
    
    # Consensus
    vote_count = sum(predictions)
    consensus = "YES" if vote_count >= 2 else "NO"
    
    # Confidence
    mean_z = np.mean(z_scores)
    if mean_z >= 10:
        confidence = "VERY HIGH"
    elif mean_z >= 5:
        confidence = "HIGH"
    elif mean_z >= 3:
        confidence = "MEDIUM"
    elif mean_z >= 1.5:
        confidence = "LOW"
    else:
        confidence = "UNCERTAIN"
    
    # Probability estimate
    k = 0.25
    prob = 1.0 / (1.0 + np.exp(-k * mean_z))
    prob = max(0.5, min(prob, 0.95))
    
    return results, consensus, confidence, prob, vote_count, mean_z


def create_source_chart(results):
    """Create a visual bar chart of z-scores."""
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    
    sources = list(results.keys())
    z_scores = [results[s]["z_score"] for s in sources]
    colors = []
    for z in z_scores:
        if z < -1.96:
            colors.append('#10b981')  # green - deficit
        elif z > 1.96:
            colors.append('#8b5cf6')  # purple - excess
        else:
            colors.append('#6b7280')  # gray - normal
    
    fig, ax = plt.subplots(figsize=(8, 4), facecolor='#0f172a')
    ax.set_facecolor('#0f172a')
    
    bars = ax.barh(sources, z_scores, color=colors, height=0.6, edgecolor='#1e293b', linewidth=2)
    
    # Add threshold lines
    ax.axvline(x=-1.96, color='#10b981', linestyle='--', alpha=0.5, label='Deficit threshold')
    ax.axvline(x=1.96, color='#8b5cf6', linestyle='--', alpha=0.5, label='Excess threshold')
    ax.axvline(x=0, color='#475569', linestyle='-', alpha=0.3)
    
    # Style
    ax.set_xlabel('Z-Score', color='#e2e8f0', fontsize=12)
    ax.set_title('Source Analysis', color='#e2e8f0', fontsize=14, fontweight='bold')
    ax.tick_params(colors='#e2e8f0')
    ax.spines['bottom'].set_color('#334155')
    ax.spines['left'].set_color('#334155')
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    
    # Add value labels
    for bar, z in zip(bars, z_scores):
        width = bar.get_width()
        ax.text(width + 0.1 if width >= 0 else width - 0.5, bar.get_y() + bar.get_height()/2,
                f'{z:.2f}', ha='left' if width >= 0 else 'right', va='center', 
                color='#e2e8f0', fontsize=10)
    
    plt.tight_layout()
    return fig


def predict(question: str, deadline: str, n_samples: int, n_null: int):
    """Main prediction function for Gradio."""
    
    if not question.strip():
        return "โŒ Please enter a question.", None, "", ""
    
    if not deadline:
        return "โŒ Please select a deadline.", None, "", ""
    
    try:
        results, consensus, confidence, prob, votes, mean_z = run_oracle_prediction(
            question, deadline, int(n_samples), int(n_null)
        )
        
        # Create chart
        chart = create_source_chart(results)
        
        # Big result display
        if consensus == "YES":
            result_emoji = "โœ…"
            result_color = "green"
        else:
            result_emoji = "โŒ"
            result_color = "red"
        
        big_result = f"""
<div style="text-align: center; padding: 30px; background: linear-gradient(135deg, #1e293b 0%, #0f172a 100%); border-radius: 20px; border: 2px solid #334155; margin: 20px 0;">
    <div style="font-size: 72px; margin-bottom: 10px;">{result_emoji}</div>
    <div style="font-size: 48px; font-weight: bold; color: {'#10b981' if consensus == 'YES' else '#ef4444'}; text-shadow: 0 0 20px {'#10b98155' if consensus == 'YES' else '#ef444455'};">
        {consensus}
    </div>
    <div style="font-size: 18px; color: #94a3b8; margin-top: 10px;">
        Confidence: <span style="color: #e2e8f0; font-weight: bold;">{confidence}</span> โ€ข 
        Probability: <span style="color: #e2e8f0; font-weight: bold;">{prob:.1%}</span>
    </div>
    <div style="font-size: 14px; color: #64748b; margin-top: 5px;">
        {votes}/4 sources agree โ€ข Mean |z| = {mean_z:.2f}
    </div>
</div>
"""
        
        # Detailed breakdown
        details = f"""
### ๐Ÿ“Š Source Breakdown

| Source | Z-Score | Status | Vote |
|--------|---------|--------|------|
"""
        for name, data in results.items():
            emoji = "๐ŸŸข" if data["classification"] == "DEFICIT" else "โšช" if data["classification"] == "NORMAL" else "๐ŸŸฃ"
            vote_emoji = "โœ“" if data["prediction"] == "YES" else "โœ—"
            details += f"| {name.title()} | {data['z_score']:.2f} | {emoji} {data['classification']} | {vote_emoji} {data['prediction']} |\n"
        
        details += f"""
---

**Question:** {question}  
**Deadline:** {deadline}  
**Timestamp:** {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')}

---

<details>
<summary>๐Ÿ”ฌ Methodology</summary>

- **Algorithm:** Temporal Bispectral Operator (TBO)
- **Signal Sources:** 4 independent channels (entropy, clock, hash_chain, cyclotomic)
- **Null Surrogates:** {n_null} permutations per source
- **Threshold:** z < -1.96 (95% confidence deficit)
- **Philosophy:** *"The shape is the oracle โ€” we reveal, not compute."*

</details>
"""
        
        return big_result, chart, details, f"๐Ÿ”ฎ Prediction: {consensus} ({confidence})"
        
    except Exception as e:
        return f"โŒ Error: {str(e)}", None, "", ""


# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
# CUSTOM CSS
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

CUSTOM_CSS = """
/* Dark theme overrides */
.gradio-container {
    background: linear-gradient(180deg, #0f172a 0%, #1e1b4b 100%) !important;
    max-width: 1000px !important;
}

/* ALL TEXT WHITE/LIGHT */
.gradio-container, .gradio-container * {
    color: #e2e8f0 !important;
}

/* Labels */
label, .gr-label, .label-wrap, span.svelte-1gfkn6j {
    color: #e2e8f0 !important;
}

/* Prose/Markdown text */
.prose, .prose *, .markdown-body, .markdown-body * {
    color: #e2e8f0 !important;
}

.prose p, .prose li, .prose td, .prose th {
    color: #cbd5e1 !important;
}

.prose h1, .prose h2, .prose h3, .prose h4 {
    color: #f1f5f9 !important;
}

/* Header styling - gradient text */
.prose h1:first-of-type {
    background: linear-gradient(90deg, #10b981, #06b6d4, #8b5cf6) !important;
    -webkit-background-clip: text !important;
    -webkit-text-fill-color: transparent !important;
    background-clip: text !important;
    font-size: 2.5rem !important;
    text-align: center !important;
}

/* Input styling */
.gr-input, .gr-textarea, input, textarea {
    background: #1e293b !important;
    border: 1px solid #334155 !important;
    color: #f1f5f9 !important;
}

.gr-input::placeholder, .gr-textarea::placeholder, input::placeholder, textarea::placeholder {
    color: #94a3b8 !important;
}

.gr-input:focus, .gr-textarea:focus {
    border-color: #10b981 !important;
    box-shadow: 0 0 0 3px #10b98133 !important;
}

/* Button styling */
.gr-button-primary, button.primary {
    background: linear-gradient(135deg, #059669 0%, #0891b2 50%, #7c3aed 100%) !important;
    border: none !important;
    font-size: 1.2rem !important;
    padding: 15px 30px !important;
    transition: all 0.3s ease !important;
    color: #ffffff !important;
    font-weight: 700 !important;
    text-shadow: 0 1px 2px rgba(0,0,0,0.3) !important;
    letter-spacing: 0.5px !important;
}

.gr-button-primary:hover, button.primary:hover {
    transform: translateY(-2px) !important;
    box-shadow: 0 10px 40px -10px #05966977 !important;
    background: linear-gradient(135deg, #047857 0%, #0e7490 50%, #6d28d9 100%) !important;
}

/* Card/Box styling */
.gr-box, .gr-panel, .gr-form, .block {
    background: #1e293b !important;
    border: 1px solid #334155 !important;
    border-radius: 12px !important;
}

/* Slider styling */
.gr-slider input[type="range"] {
    background: linear-gradient(90deg, #10b981, #8b5cf6) !important;
}

/* Example table */
.gr-samples-table, table {
    background: #1e293b !important;
}

table th {
    background: #334155 !important;
    color: #f1f5f9 !important;
}

table td {
    color: #e2e8f0 !important;
    background: #1e293b !important;
}

table tr:hover td {
    background: #334155 !important;
}

/* Accordion */
.gr-accordion, details {
    background: #1e293b !important;
    border: 1px solid #334155 !important;
    color: #e2e8f0 !important;
}

summary {
    color: #e2e8f0 !important;
}

/* Quote styling */
blockquote {
    border-left: 4px solid #10b981 !important;
    background: #1e293b !important;
    padding: 15px !important;
    margin: 20px 0 !important;
    border-radius: 0 8px 8px 0 !important;
    color: #94a3b8 !important;
}

blockquote * {
    color: #94a3b8 !important;
}

/* Links */
a {
    color: #10b981 !important;
}

a:hover {
    color: #06b6d4 !important;
}

/* Info text */
.gr-info, .info, small, .caption {
    color: #94a3b8 !important;
}

/* Plot area */
.gr-plot {
    background: #1e293b !important;
}
"""

# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
# GRADIO INTERFACE
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

EXAMPLES = [
    ["Will BTC exceed $150k by December 2026?", "2026-12-31", 256, 100],
    ["Will there be a major AI breakthrough in 2026?", "2026-12-31", 256, 100],
    ["Will SpaceX land humans on Mars by 2030?", "2030-12-31", 256, 100],
    ["Will the Fed cut rates in Q2 2026?", "2026-06-30", 256, 100],
    ["Will a nuclear fusion plant achieve net energy gain by 2027?", "2027-12-31", 256, 100],
]

with gr.Blocks(
    title="๐Ÿ”ฎ TBO Oracle",
    theme=gr.themes.Base(
        primary_hue="emerald",
        secondary_hue="cyan",
        neutral_hue="slate",
    ),
    css=CUSTOM_CSS,
) as demo:
    
    gr.HTML("""
<div style="text-align: center; margin-bottom: 20px;">
    <img src="https://huggingface.co/spaces/GotThatData/TBO-Oracle/resolve/main/assets/hero.png" 
         alt="TBO Oracle" 
         style="max-width: 100%; border-radius: 16px; box-shadow: 0 20px 60px -20px rgba(16, 185, 129, 0.4);">
</div>
""")
    
    gr.Markdown("""
# ๐Ÿ”ฎ TBO Oracle

### Temporal Bispectral Operator โ€” Blockchain-Anchored Predictions

> *"The shape is the oracle โ€” we reveal, not compute."*

TBO Oracle uses **bispectral analysis** and **Two-State Vector Formalism (TSVF)** 
to detect retrocausal signals in independent noise sources. When sources converge 
despite their independence, the topology reveals the answer.
""")
    
    with gr.Row():
        with gr.Column(scale=3):
            question = gr.Textbox(
                label="๐ŸŽฏ Your Question",
                placeholder="Ask a binary yes/no question about the future...",
                lines=2,
                max_lines=4,
            )
            deadline = gr.Textbox(
                label="๐Ÿ“… Resolution Deadline",
                placeholder="YYYY-MM-DD",
                value="2026-12-31",
            )
        
        with gr.Column(scale=2):
            with gr.Accordion("โš™๏ธ Advanced Settings", open=False):
                n_samples = gr.Slider(
                    label="Signal Length",
                    minimum=64,
                    maximum=512,
                    value=256,
                    step=64,
                    info="More samples = more precision"
                )
                n_null = gr.Slider(
                    label="Null Surrogates",
                    minimum=50,
                    maximum=200,
                    value=100,
                    step=25,
                    info="More surrogates = better z-score estimation"
                )
    
    predict_btn = gr.Button("๐Ÿ”ฎ Query the Oracle", variant="primary", size="lg")
    status = gr.Textbox(label="Status", visible=False)
    
    # Results section
    with gr.Row():
        result_html = gr.HTML(label="Prediction")
    
    with gr.Row():
        with gr.Column(scale=1):
            chart = gr.Plot(label="๐Ÿ“Š Z-Score Analysis")
        with gr.Column(scale=1):
            details = gr.Markdown(label="Details")
    
    predict_btn.click(
        fn=predict,
        inputs=[question, deadline, n_samples, n_null],
        outputs=[result_html, chart, details, status],
    )
    
    gr.Examples(
        examples=EXAMPLES,
        inputs=[question, deadline, n_samples, n_null],
        label="๐Ÿ’ก Example Questions"
    )
    
    gr.HTML("""
<div style="text-align: center; margin: 30px 0;">
    <img src="https://huggingface.co/spaces/GotThatData/TBO-Oracle/resolve/main/assets/waveform.png" 
         alt="Bispectral Waveform Visualization" 
         style="max-width: 600px; width: 100%; border-radius: 12px; box-shadow: 0 10px 40px -10px rgba(139, 92, 246, 0.3);">
</div>
""")
    
    gr.Markdown("""
---

### ๐Ÿ“š How It Works

<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin: 20px 0;">

<div style="background: #1e293b; padding: 20px; border-radius: 12px; border: 1px solid #334155;">
<h4 style="color: #10b981; margin-top: 0;">๐ŸŒŠ Bispectral Analysis</h4>
<p style="color: #94a3b8; font-size: 14px;">Detects third-order phase coupling invisible to standard power spectrum analysis.</p>
</div>

<div style="background: #1e293b; padding: 20px; border-radius: 12px; border: 1px solid #334155;">
<h4 style="color: #06b6d4; margin-top: 0;">๐Ÿ”„ Hโ‚‚=0 Topology</h4>
<p style="color: #94a3b8; font-size: 14px;">Manifold closure condition ensuring prediction convergence through topological constraints.</p>
</div>

<div style="background: #1e293b; padding: 20px; border-radius: 12px; border: 1px solid #334155;">
<h4 style="color: #8b5cf6; margin-top: 0;">โณ TSVF Framework</h4>
<p style="color: #94a3b8; font-size: 14px;">Two-State Vector Formalism from quantum mechanics enables retrocausal signal detection.</p>
</div>

<div style="background: #1e293b; padding: 20px; border-radius: 12px; border: 1px solid #334155;">
<h4 style="color: #f59e0b; margin-top: 0;">๐Ÿ“ก 4 Independent Sources</h4>
<p style="color: #94a3b8; font-size: 14px;">Entropy, clock jitter, hash chains, and cyclotomic signals vote independently.</p>
</div>

</div>

### ๐Ÿ† Track Record

| Date | Question | Prediction | Outcome |
|------|----------|------------|---------|
| Feb 2026 | Canada wins Hockey Gold | NO | โœ… **Correct** (USA won) |

---

<div style="text-align: center; color: #64748b; font-size: 14px;">

๐Ÿ“„ [On-Chain Paper (BSV)](https://whatsonchain.com) โ€ข 
๐Ÿ”— [GitHub](https://github.com/OriginNeuralAI/Oracle) โ€ข 
๐Ÿง  [SmartLedger Solutions](https://smartledger.solutions)

*Built by Bryan Daugherty | SmartLedger Solutions | 2026*

</div>
""")

if __name__ == "__main__":
    demo.launch(server_name="0.0.0.0", server_port=7860)