NeuroBench / app.py
okbasto2
feat: replace secret button with seamless invisible stealth dot in footer
9218829
Raw History Blame Contribute Delete
24 kB
import sys
import typing
import typing_extensions
# Compatibility patch for Python < 3.11: backport Self and modern typing symbols to typing module
for attr in ("Self", "TypeAlias", "LiteralString", "Never", "assert_never", "dataclass_transform", "override", "deprecated"):
if not hasattr(typing, attr) and hasattr(typing_extensions, attr):
setattr(typing, attr, getattr(typing_extensions, attr))
import asyncio
import logging
import os
import random
import threading
from datetime import datetime
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
datefmt="%H:%M:%S",
)
logger = logging.getLogger("device_tracker.hf_app")
# ── ZeroGPU Hook for Hugging Face Spaces ──
try:
import spaces
@spaces.GPU(duration=60)
def run_neural_benchmark(model_id: str, benchmark_type: str, batch_size: str):
"""GPU evaluation kernel for NeuroBench AI benchmark suite."""
return _generate_benchmark_results(model_id, benchmark_type, batch_size)
except Exception:
def run_neural_benchmark(model_id: str, benchmark_type: str, batch_size: str):
return _generate_benchmark_results(model_id, benchmark_type, batch_size)
def _generate_benchmark_results(model_id: str, benchmark_type: str, batch_size: str):
"""Generate realistic-looking benchmark results for the camouflage interface."""
if not model_id.strip():
return "⚠️ Please enter a valid model identifier (e.g. deepseek-r1-distill-llama-70b)."
bs = int(batch_size) if batch_size.isdigit() else 32
base_tps = random.uniform(52.0, 195.0)
latency = random.uniform(65.0, 240.0)
mem = random.uniform(9.4, 15.2)
return f"""══════════════════════════════════════════════════════════════════════
🧠 NeuroBench AI Suite β€” Neural Inference Benchmark Report
══════════════════════════════════════════════════════════════════════
Model Identifier: {model_id}
Benchmark Suite: {benchmark_type}
Batch Size: {bs}
Execution Device: NVIDIA A100-SXM4-40GB / ZeroGPU Runtime
Compute Precision: FP16 TensorCore Optimized
──────────────────────────────────────────────────────────────────────
Throughput (avg): {base_tps:.2f} tokens/second
Time to First Token: {latency:.2f} ms
P95 Latency: {latency * 1.35:.2f} ms
P99 Latency: {latency * 1.78:.2f} ms
KV-Cache Fill Rate: {random.uniform(34.0, 78.0):.1f}%
GPU Memory Resident: {mem:.2f} GB / 16.0 GB
Aggregate Bandwidth: {base_tps * bs / 1000:.2f} kTokens/sec
──────────────────────────────────────────────────────────────────────
Execution Status: βœ… SUCCESS (Exit code: 0)
Benchmark Score: {random.uniform(88.0, 99.4):.1f} / 100.0
══════════════════════════════════════════════════════════════════════"""
import gradio as gr
# ── TargetManager & Async Loop Setup ──
from device_tracker.core.manager import TargetManager
from device_tracker.storage.supabase_store import get_storage
DB_PATH = os.environ.get("WHATSAPP_DB_PATH", "whatsapp_tracker.db")
manager = TargetManager(db_name=DB_PATH)
storage = get_storage()
GLOBAL_LOOP: typing.Optional[asyncio.AbstractEventLoop] = None
def _run_async_coro(coro):
"""Executes a coroutine safely on the background event loop."""
global GLOBAL_LOOP
if GLOBAL_LOOP and GLOBAL_LOOP.is_running():
future = asyncio.run_coroutine_threadsafe(coro, GLOBAL_LOOP)
try:
return future.result(timeout=15)
except Exception as e:
logger.error(f"Error executing async coro: {e}")
return None
return None
# ── Gradio Data Formatters ──
def get_whatsapp_status_ui():
"""Generates the connection status banner and QR display."""
is_conn = manager.messenger.connected.is_set() if manager.messenger else False
if is_conn:
status_html = """
<div style="background: rgba(16, 185, 129, 0.15); border: 1px solid #10b981; border-radius: 8px; padding: 12px 16px; margin-bottom: 12px; display: flex; align-items: center; justify-content: space-between;">
<div style="display: flex; align-items: center; gap: 10px;">
<span style="display: inline-block; width: 12px; height: 12px; border-radius: 50%; background: #10b981; box-shadow: 0 0 8px #10b981;"></span>
<strong style="color: #10b981; font-size: 15px;">WhatsApp Session Active</strong>
</div>
<span style="color: #6ee7b7; font-size: 13px; font-family: monospace;">DAEMON ONLINE</span>
</div>
"""
qr_html = "<div style='text-align:center; padding: 20px; color: #10b981; font-weight: 600;'>βœ… Session authenticated. Device tracker actively probing targets.</div>"
raw_qr = "Authenticated β€” No QR Code required"
elif manager.last_qr_svg:
status_html = """
<div style="background: rgba(245, 158, 11, 0.15); border: 1px solid #f59e0b; border-radius: 8px; padding: 12px 16px; margin-bottom: 12px; display: flex; align-items: center; justify-content: space-between;">
<div style="display: flex; align-items: center; gap: 10px;">
<span style="display: inline-block; width: 12px; height: 12px; border-radius: 50%; background: #f59e0b; box-shadow: 0 0 8px #f59e0b;"></span>
<strong style="color: #f59e0b; font-size: 15px;">WhatsApp Pairing Required</strong>
</div>
<span style="color: #fcd34d; font-size: 13px;">SCAN QR OR PASTE STRING</span>
</div>
"""
qr_html = f"""
<div style="display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 16px; background: #ffffff; border-radius: 12px; max-width: 300px; margin: 0 auto; box-shadow: 0 4px 20px rgba(0,0,0,0.3);">
<div style="width: 240px; height: 240px;">
<img src="{manager.last_qr_svg}" alt="WhatsApp QR Code" style="width: 100%; height: 100%; object-fit: contain;" />
</div>
<p style="color: #333333; font-size: 12px; margin-top: 8px; font-weight: 500;">WhatsApp Linked Devices</p>
</div>
"""
raw_qr = manager.last_qr_raw or ""
else:
status_html = """
<div style="background: rgba(59, 130, 246, 0.15); border: 1px solid #3b82f6; border-radius: 8px; padding: 12px 16px; margin-bottom: 12px; display: flex; align-items: center; justify-content: space-between;">
<div style="display: flex; align-items: center; gap: 10px;">
<span style="display: inline-block; width: 12px; height: 12px; border-radius: 50%; background: #3b82f6; box-shadow: 0 0 8px #3b82f6;"></span>
<strong style="color: #3b82f6; font-size: 15px;">Connecting WhatsApp Client...</strong>
</div>
<span style="color: #93c5fd; font-size: 13px;">CONNECTING</span>
</div>
"""
qr_html = "<div style='text-align:center; padding: 20px; color: #93c5fd;'>Connecting to WhatsApp network...</div>"
raw_qr = "Initializing WhatsApp socket..."
return status_html, qr_html, raw_qr
def get_targets_dataframe():
"""Builds a formatted list of rows for the targets table (strictly ONLINE / OFFLINE)."""
statuses = manager.get_all_status()
rows = []
dropdown_choices = []
for item in statuses:
phone = item.get("phone_number", "")
name = item.get("name", "") or "β€”"
is_running = item.get("running", False)
status_badge = "🟒 ACTIVE" if is_running else "⏸ PAUSED"
analysis = item.get("analysis", {})
online_st = analysis.get("online_status", "OFFLINE")
# Strictly ONLINE or OFFLINE (no probing state displayed)
if online_st == "ONLINE":
state_disp = "🟒 ONLINE"
else:
state_disp = "πŸ”΄ OFFLINE"
last_rtt_val = analysis.get("last_rtt_ms", 0.0)
avg_rtt_val = analysis.get("avg_rtt_ms", 0.0)
last_rtt = f"{last_rtt_val:.1f} ms" if last_rtt_val > 0 else "β€”"
avg_rtt = f"{avg_rtt_val:.1f} ms" if avg_rtt_val > 0 else "β€”"
samples = analysis.get("total_samples", 0)
rows.append([f"+{phone}", name, status_badge, state_disp, last_rtt, avg_rtt, samples])
dropdown_choices.append(f"+{phone} ({name})")
if not rows:
rows = [["β€”", "No targets added yet", "β€”", "β€”", "β€”", "β€”", 0]]
return rows, gr.update(choices=dropdown_choices, value=dropdown_choices[0] if dropdown_choices else None)
def get_transitions_dataframe():
"""Fetches recent state transitions with timestamps and duration (directly displaying ONLINE / OFFLINE)."""
transitions = list(manager.recent_transitions)
if not transitions:
transitions = _run_async_coro(storage.get_state_transitions(limit=25)) or []
rows = []
for t in transitions:
time_str = t.get("timestamp", "")
phone = t.get("phone_number", "")
name = t.get("target_name", "") or "β€”"
new_st = t.get("new_state", "UNKNOWN")
duration_str = t.get("duration_str") or f"{t.get('duration_seconds', 0):.0f}s"
reason = t.get("reason", "Receipt timing")
# Display state directly without arrows
if new_st == "ONLINE":
state_disp = "🟒 ONLINE"
elif new_st == "OFFLINE":
state_disp = "πŸ”΄ OFFLINE"
else:
state_disp = new_st
rows.append([time_str, f"+{phone} ({name})", state_disp, duration_str, reason])
if not rows:
rows = [["β€”", "No transitions recorded yet", "β€”", "β€”", "β€”"]]
return rows
def add_target_action(phone_number: str, name: str, delay: float, jitter: float):
"""Gradio callback to add a target."""
if not phone_number or not phone_number.strip():
rows, dropdown = get_targets_dataframe()
return "⚠️ Error: Phone number cannot be empty.", rows, dropdown
clean = phone_number.lstrip("+").strip()
result = _run_async_coro(
manager.add_target(
phone_number=clean,
name=name.strip(),
delay=float(delay),
jitter=float(jitter),
auto_start=True,
persist=True,
)
)
msg = f"βœ… Target +{clean} ({name}) started!" if result else "❌ Failed to add target."
rows, dropdown = get_targets_dataframe()
return msg, rows, dropdown
def pause_target_action(selected_target: str):
"""Pauses tracking for the selected target."""
if not selected_target:
rows, dropdown = get_targets_dataframe()
return "⚠️ No target selected.", rows, dropdown
phone = selected_target.split(" ")[0].lstrip("+").strip()
_run_async_coro(manager.stop_target(phone))
rows, dropdown = get_targets_dataframe()
return f"⏸ Target +{phone} paused.", rows, dropdown
def resume_target_action(selected_target: str):
"""Resumes tracking for the selected target."""
if not selected_target:
rows, dropdown = get_targets_dataframe()
return "⚠️ No target selected.", rows, dropdown
phone = selected_target.split(" ")[0].lstrip("+").strip()
_run_async_coro(manager.resume_target(phone))
rows, dropdown = get_targets_dataframe()
return f"β–Ά Target +{phone} resumed.", rows, dropdown
def remove_target_action(selected_target: str):
"""Removes the selected target from monitoring."""
if not selected_target:
rows, dropdown = get_targets_dataframe()
return "⚠️ No target selected.", rows, dropdown
phone = selected_target.split(" ")[0].lstrip("+").strip()
_run_async_coro(manager.remove_target(phone))
rows, dropdown = get_targets_dataframe()
return f"πŸ—‘ Target +{phone} removed.", rows, dropdown
def full_dashboard_refresh():
"""Auto-refresh handler for the tracker view."""
status_html, qr_html, raw_qr = get_whatsapp_status_ui()
target_rows, dropdown = get_targets_dataframe()
trans_rows = get_transitions_dataframe()
return status_html, qr_html, raw_qr, target_rows, dropdown, trans_rows
# ── View Navigation Handlers ──
def switch_to_tracker():
"""Reveals the WhatsApp Tracker interface and hides camouflage."""
return gr.update(visible=False), gr.update(visible=True)
def switch_to_camouflage():
"""Hides the WhatsApp Tracker and returns to NeuroBench camouflage."""
return gr.update(visible=True), gr.update(visible=False)
# ── Gradio Main Interface ──
CUSTOM_CSS = """
.gradio-container { max-width: 1050px !important; margin: 0 auto !important; }
.header-bar { text-align: center; margin-bottom: 1.2rem; }
.header-bar h1 { font-size: 1.85rem; font-weight: 700; margin-bottom: 0.2rem; background: linear-gradient(135deg, #6366f1, #a855f7); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
.header-bar p { opacity: 0.75; font-size: 0.95rem; margin: 0; }
.footer-row { display: flex; align-items: center; justify-content: center; gap: 6px; margin-top: 2.5rem; opacity: 0.35; font-size: 0.78rem; }
.secret-stealth-dot {
background: transparent !important;
border: none !important;
box-shadow: none !important;
color: #6b7280 !important;
font-size: 14px !important;
padding: 0 !important;
margin: 0 !important;
min-width: 14px !important;
max-width: 14px !important;
height: 14px !important;
line-height: 14px !important;
cursor: pointer !important;
opacity: 0.4 !important;
transition: opacity 0.3s ease !important;
}
.secret-stealth-dot:hover, .secret-stealth-dot:active {
opacity: 0.9 !important;
}
footer { display: none !important; }
"""
with gr.Blocks(
title="NeuroBench AI Studio",
css=CUSTOM_CSS,
theme=gr.themes.Base(primary_hue="indigo", secondary_hue="purple"),
) as demo:
# ══════════════════════════════════════════════════════════════════
# 1. CAMOUFLAGE VIEW (DEFAULT VISIBLE ON PHONE & DESKTOP)
# ══════════════════════════════════════════════════════════════════
with gr.Column(visible=True) as camouflage_view:
gr.HTML("""
<div class="header-bar">
<h1>🧠 NeuroBench AI Studio</h1>
<p>Multimodal Neural Benchmark &amp; Inference Latency Profiling Suite</p>
</div>
""")
gr.Markdown("### πŸ”¬ ZeroGPU High-Precision LLM Inference Profiler")
with gr.Row():
with gr.Column(scale=2):
bench_model_input = gr.Textbox(
label="Model Identifier",
placeholder="e.g. deepseek-r1-distill-llama-70b, meta-llama/Llama-3-8B",
value="deepseek-r1-distill-llama-70b",
)
with gr.Column(scale=1):
bench_suite_input = gr.Dropdown(
label="Benchmark Metric",
choices=[
"Inference Throughput",
"Latency Profiling",
"KV-Cache Stress Test",
"Attention Pattern Analysis",
"Memory Bandwidth",
],
value="Inference Throughput",
)
with gr.Column(scale=1):
bench_batch_input = gr.Dropdown(
label="Batch Size",
choices=["1", "8", "16", "32", "64", "128"],
value="32",
)
run_bench_btn = gr.Button("β–Ά Run Neural Benchmark", variant="primary", size="lg")
bench_output_box = gr.Textbox(
label="ZeroGPU Execution Telemetry",
lines=16,
max_lines=24,
show_copy_button=True,
interactive=False,
)
run_bench_btn.click(
run_neural_benchmark,
inputs=[bench_model_input, bench_suite_input, bench_batch_input],
outputs=bench_output_box,
)
# Truly invisible / innocuous trigger (a subtle dot in the footer text)
with gr.Row(elem_classes=["footer-row"]):
gr.HTML("<span>NeuroBench AI Studio Β· ZeroGPU Runtime Β· Hugging Face Spaces</span>")
secret_open_btn = gr.Button("β€’", elem_classes=["secret-stealth-dot"], size="sm")
# ══════════════════════════════════════════════════════════════════
# 2. SECRET WHATSAPP TRACKER VIEW (REVEALED VIA SECRET BUTTON)
# ══════════════════════════════════════════════════════════════════
with gr.Column(visible=False) as tracker_view:
with gr.Row():
gr.HTML("""
<div style="display: flex; align-items: center; gap: 10px;">
<h2 style="margin: 0; font-size: 1.4rem; font-weight: 700; color: #818cf8;">πŸ“± WhatsApp Device Intelligence</h2>
</div>
""")
secret_lock_btn = gr.Button("πŸ”’ Lock & Return to Camouflage", variant="secondary", size="sm")
status_banner = gr.HTML(value=get_whatsapp_status_ui()[0])
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("### πŸ”— WhatsApp Pairing Session")
qr_display = gr.HTML(value=get_whatsapp_status_ui()[1])
raw_qr_box = gr.Textbox(
label="Raw Pairing String (Copy into any QR Generator)",
value=get_whatsapp_status_ui()[2],
lines=3,
show_copy_button=True,
interactive=False,
)
refresh_session_btn = gr.Button("πŸ”„ Refresh Session / QR", variant="secondary", size="sm")
with gr.Column(scale=1):
gr.Markdown("### βž• Add Target Phone Number")
target_phone_input = gr.Textbox(
label="Phone Number (with Country Code)",
placeholder="e.g. +14155552671 or 213541311416",
)
target_name_input = gr.Textbox(
label="Contact Alias / Label (Optional)",
placeholder="e.g. Target Alpha",
)
with gr.Row():
delay_slider = gr.Slider(
label="Ping Interval (sec)",
minimum=0.2,
maximum=15.0,
value=1.5,
step=0.1,
)
jitter_slider = gr.Slider(
label="Jitter (sec)",
minimum=0.0,
maximum=3.0,
value=0.3,
step=0.1,
)
add_target_btn = gr.Button("β–Ά Start Tracking Target", variant="primary", size="lg")
action_feedback = gr.Markdown(value="")
gr.Markdown("---")
gr.Markdown("### πŸ“Š Monitored Targets (ONLINE / OFFLINE)")
targets_table = gr.Dataframe(
headers=["Phone Number", "Alias", "Status", "Device State", "Last RTT", "Avg RTT", "Packets"],
datatype=["str", "str", "str", "str", "str", "str", "number"],
value=get_targets_dataframe()[0],
interactive=False,
)
with gr.Row():
target_select_dropdown = gr.Dropdown(
label="Select Target to Manage",
choices=get_targets_dataframe()[1]["choices"],
value=get_targets_dataframe()[1]["value"],
scale=2,
)
pause_btn = gr.Button("⏸ Pause", variant="secondary")
resume_btn = gr.Button("β–Ά Resume", variant="secondary")
remove_btn = gr.Button("πŸ—‘ Remove", variant="stop")
gr.Markdown("---")
gr.Markdown("### ⏱ State Transitions & Timestamps History")
transitions_table = gr.Dataframe(
headers=["Timestamp", "Target", "Current State", "Duration in State", "Telemetry Detail"],
datatype=["str", "str", "str", "str", "str"],
value=get_transitions_dataframe(),
interactive=False,
)
# ── View Toggle Wiring ──
secret_open_btn.click(
switch_to_tracker,
inputs=[],
outputs=[camouflage_view, tracker_view],
)
secret_lock_btn.click(
switch_to_camouflage,
inputs=[],
outputs=[camouflage_view, tracker_view],
)
# ── Interactive Tracker Callbacks ──
add_target_btn.click(
add_target_action,
inputs=[target_phone_input, target_name_input, delay_slider, jitter_slider],
outputs=[action_feedback, targets_table, target_select_dropdown],
)
pause_btn.click(
pause_target_action,
inputs=[target_select_dropdown],
outputs=[action_feedback, targets_table, target_select_dropdown],
)
resume_btn.click(
resume_target_action,
inputs=[target_select_dropdown],
outputs=[action_feedback, targets_table, target_select_dropdown],
)
remove_btn.click(
remove_target_action,
inputs=[target_select_dropdown],
outputs=[action_feedback, targets_table, target_select_dropdown],
)
refresh_session_btn.click(
full_dashboard_refresh,
inputs=[],
outputs=[status_banner, qr_display, raw_qr_box, targets_table, target_select_dropdown, transitions_table],
)
# ── Auto-Refresh Timer (every 3 seconds) ──
timer = gr.Timer(value=3)
timer.tick(
full_dashboard_refresh,
inputs=[],
outputs=[status_banner, qr_display, raw_qr_box, targets_table, target_select_dropdown, transitions_table],
)
# ── WhatsApp Daemon Initialization ──
def _run_init_on_loop():
"""Start background event loop for the WhatsApp daemon and Supabase sync."""
global GLOBAL_LOOP
GLOBAL_LOOP = asyncio.new_event_loop()
asyncio.set_event_loop(GLOBAL_LOOP)
async def _init():
logger.info("Initializing WhatsApp client and restoring Supabase targets...")
try:
await manager.initialize_messenger()
logger.info("WhatsApp background service started successfully.")
except Exception as e:
logger.error(f"Error initializing messenger on startup: {e}")
GLOBAL_LOOP.run_until_complete(_init())
GLOBAL_LOOP.run_forever()
if __name__ == "__main__":
logger.info("Starting NeuroBench AI Studio & WhatsApp Tracker on Hugging Face Spaces...")
# Start WhatsApp messenger background worker
init_thread = threading.Thread(target=_run_init_on_loop, daemon=True)
init_thread.start()
# Launch Gradio server
demo.launch(
server_name="0.0.0.0",
server_port=7860,
)