""" 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"""
{result_emoji}
{consensus}
Confidence: {confidence} • Probability: {prob:.1%}
{votes}/4 sources agree • Mean |z| = {mean_z:.2f}
""" # 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')} ---
🔬 Methodology - **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."*
""" 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("""
TBO Oracle
""") 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("""
Bispectral Waveform Visualization
""") gr.Markdown(""" --- ### 📚 How It Works

🌊 Bispectral Analysis

Detects third-order phase coupling invisible to standard power spectrum analysis.

🔄 H₂=0 Topology

Manifold closure condition ensuring prediction convergence through topological constraints.

⏳ TSVF Framework

Two-State Vector Formalism from quantum mechanics enables retrocausal signal detection.

📡 4 Independent Sources

Entropy, clock jitter, hash chains, and cyclotomic signals vote independently.

### 🏆 Track Record | Date | Question | Prediction | Outcome | |------|----------|------------|---------| | Feb 2026 | Canada wins Hockey Gold | NO | ✅ **Correct** (USA won) | ---
📄 [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*
""") if __name__ == "__main__": demo.launch(server_name="0.0.0.0", server_port=7860)