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 = """
WhatsApp Session Active
DAEMON ONLINE
""" qr_html = "
✅ Session authenticated. Device tracker actively probing targets.
" raw_qr = "Authenticated — No QR Code required" elif manager.last_qr_svg: status_html = """
WhatsApp Pairing Required
SCAN QR OR PASTE STRING
""" qr_html = f"""
WhatsApp QR Code

WhatsApp Linked Devices

""" raw_qr = manager.last_qr_raw or "" else: status_html = """
Connecting WhatsApp Client...
CONNECTING
""" qr_html = "
Connecting to WhatsApp network...
" 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("""

🧠 NeuroBench AI Studio

Multimodal Neural Benchmark & Inference Latency Profiling Suite

""") 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("NeuroBench AI Studio · ZeroGPU Runtime · Hugging Face Spaces") 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("""

📱 WhatsApp Device Intelligence

""") 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, )