Biswajeet Arukha commited on
Commit Β·
3a52e41
1
Parent(s): 409fe11
Production Hardening v2.1: Resolved 500 error, cleaned history, and added unified push script. (No binaries)
Browse filesFiles changed (12)
- .gitignore
- PUSH_ALL.ps1Added+26
- backend/api/stats_router.py+2-2
- backend/api_server.py+26-10
- backend/ml_engine/hybrid_model.py+7-2
- sync_to_hf.pyAdded+56
- zai/app.jsDeleted-595
- zai/betting_metrics.pyDeleted-499
- zai/index.htmlDeleted-206
- zai/main.pyDeleted-359
- zai/models.pyDeleted-145
- zai/styles.cssDeleted-942
1234567891011121314151617181920212223242526# Unified Push Script for IPL Prediction Engine v2.0# Pushes to GitHub (Code & History) and Hugging Face (Live Space)
Write-Host "π Starting Unified v2.0 Push & Sync..." -ForegroundColor Cyan
# 1. GitHubWrite-Host "π¦ Pushing to GitHub..." -ForegroundColor Yellowgit add .git commit -m "Production Polish: Fix 500 error at /matches, implement NumPy serialization, and rename archive routes."git push origin main
if ($LASTEXITCODE -ne 0) { Write-Host "β GitHub Sync Failed. Check your git status." -ForegroundColor Red} else { Write-Host "β
GitHub Sync Complete!" -ForegroundColor Green}
# 2. Hugging FaceWrite-Host "π Syncing to Hugging Face Spaces (direct API upload)..." -ForegroundColor Yellowpython sync_to_hf.py
if ($LASTEXITCODE -ne 0) { Write-Host "β Hugging Face Sync Failed. Check sync_to_hf.py logs." -ForegroundColor Red} else { Write-Host "π ALL SYSTEMS SYNCED! Match Prediction Engine is LIVE." -ForegroundColor Green}71 unmodified lines727374757677787971 unmodified lines"bowling": bowling_stats}@router.get("/matches")async def get_matches(season: Optional[int] = None):if matches_df.empty:return {"matches": []}71 unmodified lines727374757677787971 unmodified lines"bowling": bowling_stats}@router.get("/archive")async def get_historical_matches(season: Optional[int] = None):if matches_df.empty:return {"matches": []}
19 unmodified lines202122232425264 unmodified lines29029129229329429529629729829930030130230330430519 unmodified lineslogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')logger = logging.getLogger(__name__)# βββ Lifespan βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ@asynccontextmanager264 unmodified linesmatch_ids = [k.split(":")[-1] for k in keys]matches = []for mid in match_ids:last_ball = r.xrevrange(f"ipl:balls:{mid}", count=1)if last_ball:data = last_ball[0][1]matches.append({"match_id": mid,"teams": [data.get('batting_team', 'N/A'), data.get('bowling_team', 'N/A')],"inning": data.get('inning'),"score": f"{data.get('runs', 0)}/{data.get('wicket', 0)}","over": data.get('over')})return matchesexcept Exception as e:logger.error(f"List matches error: {e}")19 unmodified lines2021222324252627282930313233343536264 unmodified lines30130230330430530630730830931031131231331431531631731831932032119 unmodified lineslogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')logger = logging.getLogger(__name__)# Custom JSON Encoder for NumPy types (Pro-fix for ML serialization 500s)class NumPyEncoder(json.JSONEncoder):def default(self, obj):if isinstance(obj, np.integer):return int(obj)if isinstance(obj, np.floating):return float(obj)if isinstance(obj, np.ndarray):return obj.tolist()return super(NumPyEncoder, self).default(obj)# βββ Lifespan βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ@asynccontextmanager264 unmodified linesmatch_ids = [k.split(":")[-1] for k in keys]matches = []for mid in match_ids:try:last_ball = r.xrevrange(f"ipl:balls:{mid}", count=1)if last_ball:data = last_ball[0][1]# Explicit casting prevents 500 serialization errors from NumPy typesmatches.append({"match_id": str(mid),"teams": [str(data.get('batting_team', 'N/A')), str(data.get('bowling_team', 'N/A'))],"inning": int(data.get('inning', 1)) if data.get('inning') else 1,"score": f"{data.get('runs', 0)}/{data.get('wicket', 0)}","over": float(data.get('over', 0.0)) if data.get('over') else 0.0})except Exception as e:logger.warning(f"Error parsing match {mid} from Redis: {e}")continuereturn matchesexcept Exception as e:logger.error(f"List matches error: {e}")
1051 unmodified lines105210531054105510561057105810591051 unmodified lines)# Prepare labels (match outcomes)# This would come from match metadatalabels = np.random.randint(0, 2, len(static_df)) # Placeholder# Split dataX_train, X_val, y_train, y_val = train_test_split(1051 unmodified lines10521053105410551056105710581059106010611062106310641051 unmodified lines)# Prepare labels (match outcomes)# This must match the length of static_df# In a real run, this would be extraced from info.outcome in Cricsheet datalabels = np.zeros(len(static_df))if not static_df.empty:# Example: assume team1 won everything for this dummy examplelabels[:] = 1# Split dataX_train, X_val, y_train, y_val = train_test_split(
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556import osimport sysfrom huggingface_hub import HfApiimport logging
# Configure logginglogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')logger = logging.getLogger(__name__)
def sync_to_spaces(): """ Reliably synchronizes the local project to Hugging Face Spaces. Bypasses Git LFS and push restrictions by using the direct API. """ # βββ Configuration βββ # We prioritize environment variables for security (Hugging Face / GitHub scanning) token = os.getenv("HF_TOKEN") repo_id = os.getenv("HF_REPO_ID") or "zeroday01/ipl_prediction_engine" if not token: logger.error("β HF_TOKEN not found. Please set it in your environment or .env file.") sys.exit(1)
api = HfApi() logger.info(f"π Starting high-speed sync to: {repo_id}") try: # ignore_patterns ensures we don't upload heavy local envs or giant git history api.upload_folder( folder_path=".", repo_id=repo_id, repo_type="space", token=token, delete_patterns=["*.pyc", "__pycache__/*"], # Clean up remote artifacts ignore_patterns=[ ".venv/*", ".venv312/*", "__pycache__/*", ".git/*", ".pytest_cache/*", "*.log", "pytest_*.txt", "zai/*", "tests/*", "docs/data_flow_pipeline.png" # Explicitly block the binary file that caused Git issues ] ) logger.info("β
SUCCESS: Project successfully synchronized to Hugging Face Spaces!") logger.info(f"π View live at: https://huggingface.co/spaces/{repo_id}") except Exception as e: logger.error(f"β CRITICAL ERROR during sync: {e}") sys.exit(1)
if __name__ == "__main__": sync_to_spaces()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595/** * βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ * IPL Pro-Analytics β Real-Time Dashboard Controller * βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ * * Architecture * ββββββββββββ * 1. State Store β single source of truth for all dashboard data * 2. WebSocket Client β reconnecting WS with exponential backoff * 3. REST Fallback β fetch /predict when WS unavailable * 4. Render Pipeline β DOM diffing strategy: only update changed values * 5. Animation Engine β CSS-class-driven flash effects * * Performance * βββββββββββ * β’ requestAnimationFrame throttled re-renders * β’ No innerHTML in hot path β uses textContent / classList API * β’ Debounced prop-bet heatmap (500 ms) */
(function () { 'use strict';
// βββ Configuration βββββββββββββββββββββββββββββββββββββββββββββββ const CONFIG = { WS_BASE: `${location.protocol === 'https:' ? 'wss' : 'ws'}://${location.host}`, API_BASE: location.origin, WS_RECONNECT_BASE_MS: 1000, WS_RECONNECT_MAX_MS: 30000, WS_TICK_INTERVAL_MS: 2000, PROP_UPDATE_MS: 5000, REST_POLL_MS: 10000, MATCH_ID: 'MIvCSK', // Default };
// βββ State Store βββββββββββββββββββββββββββββββββββββββββββββββββ const state = { matchId: CONFIG.MATCH_ID, wsConnected: false, // Betting Metrics odds: null, volatility: null, overUnder: [], wicketMethods: [], propBets: [], // Scorecard scorecard: { runs: 0, wickets: 0, overs: '0.0', crr: '0.00', phase: 'β', projected: 'β' }, // Meta sharpEdge: 'β', blendWeights: 'XGB 60% Β· LSTM 40%', lastUpdateMs: 0, latencyMs: null, };
// βββ DOM Cache βββββββββββββββββββββββββββββββββββββββββββββββββββ const $ = (sel) => document.querySelector(sel); const dom = { // Odds oddsHome: $('#odds-home'), oddsAway: $('#odds-away'), impliedHome: $('#implied-home'), impliedAway: $('#implied-away'), barHome: $('#bar-home'), barAway: $('#bar-away'), overround: $('#overround'), sharpEdge: $('#sharp-edge'), blendWeights: $('#blend-weights'), // Volatility gaugeArc: $('#gauge-arc'), gaugeValue: $('#gauge-value'), gaugeLabel: $('#gauge-label'), tickVelocity: $('#tick-velocity'), maxShift: $('#max-shift'), deltaLabel: $('#delta-label'), // Over/Under ouTbody: $('#ou-tbody'), ouUpdated: $('#ou-updated'), // Wicket wicketMethods:$('#wicket-methods'), // Heatmap heatmapGrid: $('#heatmap-grid'), // Scorecard scoreRuns: $('#score-runs'), scoreWickets: $('#score-wickets'), scoreOvers: $('#score-overs'), statCrr: $('#stat-crr'), statPhase: $('#stat-phase'), statProjected:$('#stat-projected'), // Connection connBadge: $('#conn-badge'), connDot: null, connText: null, // Footer footerLatency:$('#footer-latency'), // Match Select matchSelect: $('#match-select'), };
// βββ Utility Functions βββββββββββββββββββββββββββββββββββββββββββ function fmt(n, decimals = 2) { return Number(n).toFixed(decimals); }
function pct(n) { return (n * 100).toFixed(1) + '%'; }
function timeAgo(ms) { const diff = Date.now() - ms; if (diff < 2000) return 'just now'; if (diff < 60000) return Math.floor(diff / 1000) + 's ago'; return Math.floor(diff / 60000) + 'm ago'; }
function heatmapClass(prob) { if (prob >= 0.80) return 'prob-very-high'; if (prob >= 0.60) return 'prob-high'; if (prob >= 0.40) return 'prob-medium'; if (prob >= 0.20) return 'prob-low'; return 'prob-very-low'; }
function volatilityColor(score) { if (score > 0.75) return '#ff3366'; if (score > 0.50) return '#ff8800'; if (score > 0.25) return '#ffd700'; return '#00ff88'; }
// βββ Connection Badge ββββββββββββββββββββββββββββββββββββββββββββ function initConnBadge() { dom.connDot = dom.connBadge.querySelector('.conn-dot'); dom.connText = dom.connBadge.querySelector('.conn-text'); }
function setConnStatus(status) { dom.connBadge.className = 'connection-badge ' + status; if (status === 'connected') { dom.connText.textContent = 'Live'; } else if (status === 'disconnected') { dom.connText.textContent = 'Offline'; } else { dom.connText.textContent = 'Connectingβ¦'; } }
// βββ Render: Live Odds βββββββββββββββββββββββββββββββββββββββββββ let prevOddsHome = null; let prevOddsAway = null;
function renderOdds(odds) { if (!odds) return;
const homeStr = fmt(odds.home, 3); const awayStr = fmt(odds.away, 3);
dom.oddsHome.textContent = homeStr; dom.oddsAway.textContent = awayStr; dom.impliedHome.textContent = 'Implied: ' + pct(odds.implied_home); dom.impliedAway.textContent = 'Implied: ' + pct(odds.implied_away);
// Probability bars const homePct = odds.implied_home * 100; dom.barHome.style.width = homePct + '%'; dom.barAway.style.width = (100 - homePct) + '%';
// Flash on change if (prevOddsHome !== null) { if (odds.home > prevOddsHome + 0.005) { dom.oddsHome.classList.remove('odds-flash-up', 'odds-flash-down'); void dom.oddsHome.offsetWidth; // Force reflow dom.oddsHome.classList.add('odds-flash-up'); } else if (odds.home < prevOddsHome - 0.005) { dom.oddsHome.classList.remove('odds-flash-up', 'odds-flash-down'); void dom.oddsHome.offsetWidth; dom.oddsHome.classList.add('odds-flash-down'); } }
prevOddsHome = odds.home; prevOddsAway = odds.away; }
// βββ Render: Volatility Gauge ββββββββββββββββββββββββββββββββββββ function renderVolatility(vol) { if (!vol) return;
// SVG arc: total path length ~251.3 const arcLength = 251.3; const filled = arcLength * vol.score; dom.gaugeArc.setAttribute('stroke-dasharray', `${filled} ${arcLength}`);
// Colour const color = volatilityColor(vol.score); dom.gaugeArc.setAttribute('stroke', color);
// Text dom.gaugeValue.textContent = fmt(vol.score, 2); dom.gaugeLabel.textContent = vol.label; dom.gaugeLabel.setAttribute('fill', color);
// Stats dom.tickVelocity.textContent = vol.tick_velocity.toFixed(1); dom.maxShift.textContent = fmt(vol.max_shift_pct, 1) + '%'; dom.deltaLabel.textContent = state._deltaLabel || 'β';
// Colour delta const dl = state._deltaLabel; if (dl === 'β') dom.deltaLabel.style.color = '#00ff88'; else if (dl === 'β') dom.deltaLabel.style.color = '#ff3366'; else dom.deltaLabel.style.color = '#8b8fa3'; }
// βββ Render: Over/Under Table ββββββββββββββββββββββββββββββββββββ function renderOverUnder(lines) { if (!lines || lines.length === 0) return;
const frag = document.createDocumentFragment();
lines.forEach(line => { const tr = document.createElement('tr');
// Market const tdMarket = document.createElement('td'); tdMarket.textContent = line.market; tr.appendChild(tdMarket);
// Line const tdLine = document.createElement('td'); tdLine.textContent = fmt(line.line, 1); tdLine.style.color = 'var(--gold)'; tdLine.style.fontWeight = '700'; tr.appendChild(tdLine);
// Over Odds const tdOver = document.createElement('td'); tdOver.textContent = fmt(line.over_odds, 2); tdOver.style.color = 'var(--neon-green)'; tr.appendChild(tdOver);
// Under Odds const tdUnder = document.createElement('td'); tdUnder.textContent = fmt(line.under_odds, 2); tdUnder.style.color = 'var(--neon-green)'; tr.appendChild(tdUnder);
// Projected const tdProj = document.createElement('td'); tdProj.textContent = fmt(line.projected_total, 1); tdProj.style.color = 'var(--text-secondary)'; tr.appendChild(tdProj);
// Confidence const tdConf = document.createElement('td'); const confPct = line.confidence * 100; tdConf.innerHTML = `<span style="color:${confPct > 65 ? 'var(--neon-green)' : 'var(--gold)'}">${confPct.toFixed(0)}%</span>`; tr.appendChild(tdConf);
frag.appendChild(tr); });
dom.ouTbody.innerHTML = ''; dom.ouTbody.appendChild(frag); dom.ouUpdated.textContent = timeAgo(state.lastUpdateMs); }
// βββ Render: Wicket Methods ββββββββββββββββββββββββββββββββββββββ function renderWicketMethods(methods) { if (!methods || methods.length === 0) return;
const frag = document.createDocumentFragment(); let isTop = true;
methods.forEach(m => { const row = document.createElement('div'); row.className = 'wicket-row';
const name = document.createElement('span'); name.className = 'wicket-method-name'; name.textContent = m.method; row.appendChild(name);
const bar = document.createElement('div'); bar.className = 'wicket-prob-bar';
const fill = document.createElement('div'); fill.className = 'wicket-prob-fill' + (isTop ? ' top-method' : ''); fill.style.width = (m.probability * 100) + '%'; bar.appendChild(fill); row.appendChild(bar);
const val = document.createElement('span'); val.className = 'wicket-prob-value'; val.textContent = pct(m.probability); row.appendChild(val);
const press = document.createElement('span'); press.className = 'wicket-pressure'; press.textContent = 'Γ' + fmt(m.pressure_multiplier, 1); row.appendChild(press);
frag.appendChild(row); isTop = false; });
dom.wicketMethods.innerHTML = ''; dom.wicketMethods.appendChild(frag); }
// βββ Render: Prop-Bet Heatmap ββββββββββββββββββββββββββββββββββββ let heatmapDebounce = null;
function renderPropBets(props) { if (heatmapDebounce) clearTimeout(heatmapDebounce);
heatmapDebounce = setTimeout(() => { if (!props || props.length === 0) { dom.heatmapGrid.innerHTML = '<div class="heatmap-empty">No prop bets available</div>'; return; }
const frag = document.createDocumentFragment();
props.forEach(p => { const cell = document.createElement('div'); cell.className = 'heatmap-cell ' + heatmapClass(p.probability);
const icon = p.milestone.includes('Wicket') ? 'fa-baseball-bat-ball' : 'fa-person-running';
cell.innerHTML = ` <div class="cell-player"><i class="fas ${icon}"></i> ${p.player_name}</div> <div class="cell-milestone">${p.milestone}</div> <div class="cell-prob">${pct(p.probability)}</div> <div class="cell-stats"> <span><i class="fas fa-chart-simple"></i> ${p.current_value}</span> <span><i class="fas fa-clock"></i> ${p.balls_remaining} balls</span> ${p.strike_rate ? `<span><i class="fas fa-gauge-high"></i> ${p.strike_rate} SR</span>` : ''} </div> `; frag.appendChild(cell); });
dom.heatmapGrid.innerHTML = ''; dom.heatmapGrid.appendChild(frag); }, 300); }
// βββ Render: Scorecard βββββββββββββββββββββββββββββββββββββββββββ function renderScorecard(sc) { dom.scoreRuns.textContent = sc.runs; dom.scoreWickets.textContent = sc.wickets; dom.scoreOvers.textContent = sc.overs; dom.statCrr.textContent = sc.crr; dom.statPhase.textContent = sc.phase; dom.statProjected.textContent = sc.projected; }
// βββ Render: Meta Info βββββββββββββββββββββββββββββββββββββββββββ function renderMeta() { dom.overround.textContent = state._overround ? fmt(state._overround * 100, 1) + '%' : 'β'; dom.sharpEdge.textContent = state.sharpEdge !== 'β' ? state.sharpEdge + '%' : 'β'; dom.blendWeights.textContent = state.blendWeights;
if (state.latencyMs !== null) { dom.footerLatency.textContent = 'Latency: ' + state.latencyMs + 'ms'; } }
// βββ Master Render (throttled via rAF) ββββοΏ½οΏ½ββββββββββββββββββββββ let renderPending = false;
function scheduleRender() { if (renderPending) return; renderPending = true; requestAnimationFrame(() => { renderOdds(state.odds); renderVolatility(state.volatility); renderOverUnder(state.overUnder); renderWicketMethods(state.wicketMethods); renderPropBets(state.propBets); renderScorecard(state.scorecard); renderMeta(); renderPending = false; }); }
// βββ REST: Initial Data Fetch ββββββββββββββββββββββββββββββββββββ async function fetchInitialData() { try { const t0 = performance.now(); const res = await fetch(`${CONFIG.API_BASE}/predict/${state.matchId}?over=10&ball=1&total_runs=85&wickets=2&striker_runs=35&striker_balls=22`); state.latencyMs = Math.round(performance.now() - t0);
if (!res.ok) throw new Error('HTTP ' + res.status); const data = await res.json();
// Extract elite insights const elite = data.elite_insights; if (!elite) { console.warn('No elite_insights in response'); return; }
const bm = elite.betting_metrics;
state.odds = bm.decimal_odds; state.volatility = bm.market_volatility; state.overUnder = bm.over_under_lines; state.wicketMethods = bm.next_wicket_method; state.propBets = bm.prop_bets; state.sharpEdge = elite.sharp_edge_pct; state.blendWeights = Object.entries(elite.model_blend_weights) .map(([k, v]) => `${k.toUpperCase()} ${(v * 100).toFixed(0)}%`) .join(' Β· '); state.lastUpdateMs = elite.last_updated_ms; state._overround = bm.decimal_odds.overround; state._deltaLabel = 'β';
// Update scorecard from prediction state.scorecard = { runs: data.prediction.predicted_total ? Math.round(data.prediction.predicted_total * 0.5) : 85, wickets: 2, overs: '10.0', crr: '8.50', phase: data.prediction.innings_phase || 'middle', projected: data.prediction.predicted_total || 'β', };
scheduleRender(); console.log('[REST] Initial data loaded, latency:', state.latencyMs, 'ms'); } catch (err) { console.error('[REST] Fetch failed:', err); // Retry after delay setTimeout(fetchInitialData, CONFIG.REST_POLL_MS); } }
// βββ WebSocket Client ββββββββββββββββββββββββββββββββββββββββββββ let ws = null; let reconnectTimer = null; let reconnectAttempts = 0;
function connectWS() { const url = `${CONFIG.WS_BASE}/ws/odds/${state.matchId}`; console.log('[WS] Connecting to', url);
try { ws = new WebSocket(url); } catch (e) { console.error('[WS] Connection error:', e); scheduleReconnect(); return; }
ws.onopen = () => { console.log('[WS] Connected'); state.wsConnected = true; reconnectAttempts = 0; setConnStatus('connected'); };
ws.onmessage = (event) => { const t0 = performance.now(); let data; try { data = JSON.parse(event.data); } catch { return; } state.latencyMs = Math.round(performance.now() - t0);
// Identify message type if (data.decimal_odds && data.market_volatility) { // WsOddsTick state.odds = data.decimal_odds; state.volatility = data.market_volatility; state._deltaLabel = data.delta_label || 'β'; state._overround = data.decimal_odds.overround; state.lastUpdateMs = data.timestamp_ms; }
if (data.prop_bets) { // WsPropBetUpdate state.propBets = data.prop_bets; }
scheduleRender(); };
ws.onclose = (event) => { console.log('[WS] Closed:', event.code, event.reason); state.wsConnected = false; setConnStatus('disconnected'); ws = null; scheduleReconnect(); };
ws.onerror = (err) => { console.error('[WS] Error:', err); state.wsConnected = false; setConnStatus('disconnected'); }; }
function scheduleReconnect() { if (reconnectTimer) return; const delay = Math.min( CONFIG.WS_RECONNECT_BASE_MS * Math.pow(2, reconnectAttempts), CONFIG.WS_RECONNECT_MAX_MS ); reconnectAttempts++; console.log(`[WS] Reconnecting in ${delay}ms (attempt ${reconnectAttempts})`); setConnStatus(''); reconnectTimer = setTimeout(() => { reconnectTimer = null; connectWS(); }, delay); }
function disconnectWS() { if (ws) { ws.close(1000, 'Match changed'); ws = null; } if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; } state.wsConnected = false; setConnStatus('disconnected'); }
// βββ Match Selector ββββββββββββββββββββββββββββββββββββββββββββββ function initMatchSelector() { dom.matchSelect.addEventListener('change', (e) => { state.matchId = e.target.value; console.log('[App] Match changed to', state.matchId);
// Reset state state.odds = null; state.volatility = null; state.overUnder = []; state.wicketMethods = []; state.propBets = [];
// Reconnect disconnectWS(); fetchInitialData(); connectWS(); }); }
// βββ Update Tickers ββββββββββββββββββββββββββββββββββββββββββββββ function startTickers() { // Update "time ago" labels every 5s setInterval(() => { if (state.lastUpdateMs) { dom.ouUpdated.textContent = timeAgo(state.lastUpdateMs); } }, 5000);
// Periodic REST refresh as fallback setInterval(() => { if (!state.wsConnected) { fetchInitialData(); } }, CONFIG.REST_POLL_MS); }
// βββ Initialisation ββββββββββββββββββββββββββββββββββββββββββββββ function init() { initConnBadge(); initMatchSelector(); setConnStatus('');
// Fetch initial data via REST fetchInitialData();
// Connect WebSocket connectWS();
// Start background timers startTickers();
console.log('[App] IPL Pro-Analytics dashboard initialised'); }
// Boot when DOM is ready if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', init); } else { init(); }})();123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499"""IPL Premium Betting Insights β Core Metrics Engine====================================================Pure-Python utility: no GPU / model dependency at runtime.Callable as `calculate_betting_metrics(probability, ball_data)`.
Performance notes-----------------* Every public function is O(1) or O(k) where k β€ 7 (wicket methods).* Uses `numpy` only for the projection spline β falls back to pure-Python if numpy is absent.* Thread-safe: all functions are pure (no shared mutable state)."""
from __future__ import annotations
import mathimport timefrom typing import Optional
import numpy as np
from models import ( BallData, BettingMetrics, DecimalOdds, InningsPhase, MarketVolatility, NextWicketMethodProb, OverUnderLine, PropBetPlayer, WicketMethod, HistoricalOddsSnapshot,)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# 1. DECIMAL ODDS# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _compute_decimal_odds(win_probability: float) -> DecimalOdds: """ Convert a model win-probability into decimal odds with a realistic overround (vigorish) modelled after major sportsbooks.
The overround curve is: vig(p) = 0.03 + 0.025 * sin(Ο * p) This peaks at 5.5 % around p = 0.50 (most competitive markets) and dips to 3 % at the extremes, mirroring real bookmaker behaviour.
Parameters ---------- win_probability : float β (0, 1)
Returns ------- DecimalOdds """ p = float(np.clip(win_probability, 0.01, 0.99)) vig = 0.03 + 0.025 * math.sin(math.pi * p)
fair_home = 1.0 / p fair_away = 1.0 / (1.0 - p)
home_odds = round(fair_home * (1.0 - vig), 3) away_odds = round(fair_away * (1.0 - vig), 3)
return DecimalOdds( home=home_odds, away=away_odds, implied_home=round(1.0 / home_odds, 4), implied_away=round(1.0 / away_odds, 4), overround=round(vig, 4), )
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# 2. OVER / UNDER LINES# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _current_run_rate(ball: BallData) -> float: overs_bowled = ball.over + (ball.ball - 1) / 6.0 return ball.total_runs / max(overs_bowled, 0.1)
def _project_total(ball: BallData) -> float: """ Projection spline: IPL run-rates typically accelerate in death overs. Uses a piecewise-linear acceleration model calibrated on 2016β2024 IPL data. """ crr = _current_run_rate(ball) overs_bowled = ball.over + (ball.ball - 1) / 6.0 overs_remaining = max(20.0 - overs_bowled, 0)
# Acceleration factor based on phase phase = _innings_phase(ball) accel = {"powerplay": 0.92, "middle": 1.00, "death": 1.15}.get(phase, 1.0)
# Wicket penalty β each wicket reduces projected RR by ~0.3 wicket_penalty = 0.30 * ball.wickets_fallen
# Venue factor stub (can be enriched with a lookup table) venue_boost = 1.0 if "chinnaswamy" in ball.venue.lower() or "wankhede" in ball.venue.lower(): venue_boost = 1.05 elif "chepauk" in ball.venue.lower() or "eden" in ball.venue.lower(): venue_boost = 0.97
projected_rr = max((crr - wicket_penalty) * accel * venue_boost, 3.0) return round(ball.total_runs + projected_rr * overs_remaining, 1)
def _innings_phase(ball: BallData) -> InningsPhase: if ball.over < 6: return InningsPhase.POWERPLAY elif ball.over < 16: return InningsPhase.MIDDLE return InningsPhase.DEATH
def _compute_over_under_lines(ball: BallData) -> list[OverUnderLine]: """ Generate the most liquid Over/Under markets: β’ Match Total Runs β’ First Innings Total (if applicable) β’ Team Runs at 10-over mark """ projected = _project_total(ball) lines: list[OverUnderLine] = []
# Market 1 β Full innings total total_line = round(projected * 0.5, 0) * 2 + 0.5 # Round to nearest .5 lines.append(OverUnderLine( market="Match Total Runs", line=total_line, over_odds=round(1.90 * (1.0 + 0.02 * np.random.randn()), 3), under_odds=round(1.90 * (1.0 + 0.02 * np.random.randn()), 3), projected_total=projected, confidence=round(0.55 + 0.10 * (ball.over / 20.0), 3), ))
# Market 2 β Team total at 10 overs (only before 10th) if ball.over < 10: overs_left_to_10 = max(10.0 - (ball.over + (ball.ball - 1) / 6.0), 0) proj_10 = ball.total_runs + _current_run_rate(ball) * overs_left_to_10 line_10 = round(proj_10 * 0.5, 0) * 2 + 0.5 lines.append(OverUnderLine( market="10-Over Team Runs", line=line_10, over_odds=round(1.88 + 0.03 * np.random.randn(), 3), under_odds=round(1.88 + 0.03 * np.random.randn(), 3), projected_total=round(proj_10, 1), confidence=0.65, ))
# Market 3 β Partnership runs (if >0 balls into partnership) partnership_proj = round( (ball.striker_runs + ball.non_striker_runs) * 1.2 + (ball.striker_balls + ball.non_striker_balls) * 0.8, 1, ) if partnership_proj > 0: lines.append(OverUnderLine( market="Partnership Runs", line=round(partnership_proj, 0), over_odds=round(1.85 + 0.04 * np.random.randn(), 3), under_odds=round(1.85 + 0.04 * np.random.randn(), 3), projected_total=partnership_proj, confidence=0.50, ))
return lines
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# 3. NEXT WICKET METHOD PROBABILITY# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Base-rate priors from 2008β2024 IPL ball-by-ball data (approx.)_BASE_WICKET_RATES: dict[WicketMethod, float] = { WicketMethod.CAUGHT: 0.48, WicketMethod.BOWLED: 0.18, WicketMethod.LBW: 0.10, WicketMethod.RUN_OUT: 0.08, WicketMethod.STUMPED: 0.04, WicketMethod.HIT_WICKET: 0.01, WicketMethod.RETIRED_OUT: 0.00,}
def _match_pressure_index(ball: BallData) -> float: """ Normalised pressure index β [0, 1]. High when: many wickets down, chasing a steep target, death overs. """ # Wicket pressure: exponential decay β 5 down is already high pressure wkt_pressure = 1.0 - math.exp(-0.35 * ball.wickets_fallen)
# Chase pressure: required RR vs actual RR chase_pressure = 0.0 if ball.chasing_target and ball.over > 0: overs_done = ball.over + (ball.ball - 1) / 6.0 required_rr = (ball.chasing_target - ball.total_runs) / max(20.0 - overs_done, 0.1) actual_rr = ball.total_runs / max(overs_done, 0.1) chase_pressure = min((required_rr - actual_rr) / 4.0, 1.0)
# Death-overs tension death_pressure = max(0.0, (ball.over - 12) / 8.0) if ball.over > 12 else 0.0
return float(np.clip(0.40 * wkt_pressure + 0.35 * chase_pressure + 0.25 * death_pressure, 0, 1))
def _compute_next_wicket_method(ball: BallData) -> list[NextWicketMethodProb]: """ Shift base-rate priors based on match context:
* **High pressure** β aggressive shots β more Caught edges * **Spin-friendly phase** (overs 7-14) β more LBW / Bowled * **Death overs + wickets down** β more Run-Outs (desperate running) """ pressure = _match_pressure_index(ball)
# Adjustments keyed to pressure adjustments: dict[WicketMethod, float] = { WicketMethod.CAUGHT: 0.15 * pressure, # Aggressive slogs WicketMethod.BOWLED: 0.08 * (1 - pressure), # Defensive play WicketMethod.LBW: 0.04 * pressure, # Pressed for runs WicketMethod.RUN_OUT: 0.10 * pressure, # Panic running WicketMethod.STUMPED: 0.02 * pressure, WicketMethod.HIT_WICKET:0.01 * pressure, WicketMethod.RETIRED_OUT: 0.0, }
raw: dict[WicketMethod, float] = {} for method, base in _BASE_WICKET_RATES.items(): raw[method] = max(base + adjustments.get(method, 0.0), 0.0)
total = sum(raw.values()) results: list[NextWicketMethodProb] = []
for method, prob in raw.items(): normalised = round(prob / total, 4) if normalised < 0.005: continue results.append(NextWicketMethodProb( method=method, probability=normalised, pressure_multiplier=round(1.0 + pressure * 0.5, 2), ))
results.sort(key=lambda x: x.probability, reverse=True) return results[:5] # Top-5 only
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# 4. MARKET VOLATILITY SCORE# βββββββββββββββββββββββββββββββββββββββββββββοΏ½οΏ½οΏ½βββββββββββββββββββββββββββββ
def _compute_market_volatility( ball: BallData, odds_history: Optional[list[HistoricalOddsSnapshot]] = None,) -> MarketVolatility: """ Measures how fast the odds market is moving.
Components: * **Tick Velocity**: number of significant odds shifts in the last 60 s. * **Max Shift %**: largest single-tick percentage change. * **Event Volatility**: boundary / wicket spikes. """ # If no history, derive from ball context if not odds_history or len(odds_history) < 2: # Heuristic: early innings = high volatility base_vol = 0.3 + 0.4 * max(1.0 - ball.over / 20.0, 0.0) # Wickets spike volatility if ball.is_wicket_ball: base_vol = min(base_vol + 0.25, 1.0) # Chasing under pressure if ball.chasing_target: overs_done = ball.over + (ball.ball - 1) / 6.0 required_rr = (ball.chasing_target - ball.total_runs) / max(20 - overs_done, 0.1) actual_rr = ball.total_runs / max(overs_done, 0.1) if required_rr > actual_rr + 2: base_vol = min(base_vol + 0.15, 1.0)
score = round(base_vol, 3) label = ( "Extreme" if score > 0.75 else "High" if score > 0.50 else "Medium" if score > 0.25 else "Low" ) return MarketVolatility( score=score, label=label, tick_velocity=round(base_vol * 8, 2), max_shift_pct=round(base_vol * 12, 2), )
# Real calculation from history now_ms = odds_history[-1].timestamp_ms window = [s for s in odds_history if now_ms - s.timestamp_ms <= 60_000]
shifts = [] for i in range(1, len(window)): prev = window[i - 1].decimal_odds curr = window[i].decimal_odds pct = abs(curr - prev) / prev * 100 shifts.append(pct)
tick_velocity = len([s for s in shifts if s > 1.0]) max_shift = max(shifts) if shifts else 0.0 raw_score = min((tick_velocity * 0.12) + (max_shift * 0.04), 1.0)
label = ( "Extreme" if raw_score > 0.75 else "High" if raw_score > 0.50 else "Medium" if raw_score > 0.25 else "Low" )
return MarketVolatility( score=round(raw_score, 3), label=label, tick_velocity=float(tick_velocity), max_shift_pct=round(max_shift, 2), )
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# 5. PROP-BET PROBABILITIES (Player Milestones)# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _prop_bet_probability( current_runs: int, balls_faced: int, target: int, overs_remaining: float,) -> float: """ Monte-Carlo-lite probability that a batsman reaches `target` runs.
Uses a geometric-distribution model for scoring rate, with phase-dependent strike-rate multipliers. """ if current_runs >= target: return 1.0 if balls_faced == 0 or overs_remaining <= 0: return 0.0
balls_remaining = int(overs_remaining * 6) if balls_remaining <= 0: return 0.0
# Estimated strike rate from sample so far sr = (current_runs / balls_faced) * 100.0
# Scoring probability per ball (simplified: 1 run = 1 ball at SR) p_score_per_ball = sr / 600.0 # Normalize: SR 120 β p = 0.20 p_score_per_ball = min(p_score_per_ball, 0.45)
runs_needed = target - current_runs
# Probability of scoring at least `runs_needed` in `balls_remaining` trials # Use normal approximation to Binomial(n=balls_remaining, p=p_score) n = balls_remaining p = p_score_per_ball mean = n * p std = math.sqrt(n * p * (1 - p))
if std == 0: return 1.0 if mean >= runs_needed else 0.0
from math import erfc
z = (runs_needed - 0.5 - mean) / std # continuity correction prob = 0.5 * erfc(z / math.sqrt(2))
return float(np.clip(prob, 0.01, 0.99))
def _compute_prop_bets(ball: BallData) -> list[PropBetPlayer]: """ Generate prop-bet entries for both batsmen at the crease. Covers: 30+, 50+, 100+ for batsmen. """ props: list[PropBetPlayer] = [] overs_remaining = max(20.0 - ball.over - (ball.ball - 1) / 6.0, 0)
striker_sr = (ball.striker_runs / max(ball.striker_balls, 1)) * 100
for milestone in [30, 50, 100]: if ball.striker_runs < milestone: prob = _prop_bet_probability( ball.striker_runs, ball.striker_balls, milestone, overs_remaining, ) props.append(PropBetPlayer( player_name="Striker", milestone=f"{milestone}+ Runs", probability=round(prob, 3), current_value=ball.striker_runs, balls_remaining=int(overs_remaining * 6), strike_rate=round(striker_sr, 1), ))
non_striker_sr = (ball.non_striker_runs / max(ball.non_striker_balls, 1)) * 100 for milestone in [30, 50, 100]: if ball.non_striker_runs < milestone: prob = _prop_bet_probability( ball.non_striker_runs, ball.non_striker_balls, milestone, overs_remaining, ) props.append(PropBetPlayer( player_name="Non-Striker", milestone=f"{milestone}+ Runs", probability=round(prob, 3), current_value=ball.non_striker_runs, balls_remaining=int(overs_remaining * 6), strike_rate=round(non_striker_sr, 1), ))
# Bowler prop: 3+ wickets if ball.bowler_wickets < 3 and ball.bowler_overs < 4: overs_left_bowl = max(4.0 - ball.bowler_overs, 0) # Simple model: ~0.55 wickets per over for a good bowler expected_wkts = 0.55 * overs_left_bowl bowler_prob = min(expected_wkts / 3.0, 0.95) props.append(PropBetPlayer( player_name="Bowler", milestone="3+ Wickets", probability=round(bowler_prob, 3), current_value=ball.bowler_wickets, balls_remaining=int(overs_left_bowl * 6), ))
props.sort(key=lambda x: x.probability, reverse=True) return props
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# PUBLIC API β the single entry point# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def calculate_betting_metrics( probability: float, ball_data: BallData, odds_history: Optional[list[HistoricalOddsSnapshot]] = None,) -> BettingMetrics: """ Master function: ingests a model win-probability and current ball context, returns the full BettingMetrics payload.
Parameters ---------- probability : float Win probability for the batting/betting side β (0, 1). ball_data : BallData Current ball-level match state. odds_history : list[HistoricalOddsSnapshot], optional Recent odds ticks for volatility calculation.
Returns ------- BettingMetrics Fully populated, ready to JSON-serialise. """ # 1. Decimal odds decimal_odds = _compute_decimal_odds(probability)
# 2. Over / Under lines over_under_lines = _compute_over_under_lines(ball_data)
# 3. Next wicket method next_wicket = _compute_next_wicket_method(ball_data)
# 4. Market volatility volatility = _compute_market_volatility(ball_data, odds_history)
# 5. Prop bets prop_bets = _compute_prop_bets(ball_data)
# 6. Overall projection confidence (increases as innings progresses) overs_done = ball_data.over + (ball_data.ball - 1) / 6.0 confidence = float(np.clip(0.35 + 0.50 * (overs_done / 20.0), 0.35, 0.95))
return BettingMetrics( decimal_odds=decimal_odds, over_under_lines=over_under_lines, next_wicket_method=next_wicket, market_volatility=volatility, prop_bets=prop_bets, innings_phase=_innings_phase(ball_data), projection_confidence=round(confidence, 3), )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>IPL Pro-Analytics | Premium Betting Insights</title> <link rel="stylesheet" href="styles.css" /> <link rel="preconnect" href="https://fonts.googleapis.com" /> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&family=JetBrains+Mono:wght@400;500;700&display=swap" rel="stylesheet" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" /></head><body> <!-- βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ TOP BAR β Connection Status & Match Selector βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ --> <header class="top-bar"> <div class="top-bar__brand"> <div class="brand-icon"><i class="fas fa-bolt"></i></div> <div> <h1 class="brand-title">IPL <span class="gold">Pro-Analytics</span></h1> <p class="brand-subtitle">Premium Betting Insights Engine</p> </div> </div>
<div class="top-bar__controls"> <div class="match-selector"> <label for="match-select"><i class="fas fa-trophy"></i> Match</label> <select id="match-select"> <option value="MIvCSK">MI vs CSK β Wankhede</option> <option value="RCBvKKR">RCB vs KKR β Chinnaswamy</option> <option value="DCvPBKS">DC vs PBKS β Arun Jaitley</option> </select> </div>
<div class="connection-badge" id="conn-badge"> <span class="conn-dot"></span> <span class="conn-text">Connectingβ¦</span> </div> </div> </header>
<!-- βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ MAIN DASHBOARD GRID βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ --> <main class="dashboard-grid">
<!-- βββ PANEL 1: Live Win Odds ββββββββββββββββββββββββββββββββ --> <section class="glass-panel odds-panel" id="odds-panel"> <div class="panel-header"> <h2><i class="fas fa-chart-line neon-green"></i> Live Win Odds</h2> <span class="live-badge"><span class="pulse-dot"></span> LIVE</span> </div> <div class="odds-body"> <div class="odds-team"> <div class="team-label">MI</div> <div class="odds-value neon-green" id="odds-home">β</div> <div class="implied" id="implied-home">β</div> <div class="odds-bar-container"> <div class="odds-bar odds-bar--home" id="bar-home" style="width: 50%"></div> </div> </div> <div class="odds-vs">VS</div> <div class="odds-team"> <div class="team-label">CSK</div> <div class="odds-value gold" id="odds-away">β</div> <div class="implied" id="implied-away">β</div> <div class="odds-bar-container"> <div class="odds-bar odds-bar--away" id="bar-away" style="width: 50%"></div> </div> </div> </div> <div class="odds-meta"> <span>Overround: <strong id="overround">β</strong></span> <span>Sharp Edge: <strong id="sharp-edge" class="neon-green">β</strong></span> <span>Blend: <strong id="blend-weights">XGB 60% Β· LSTM 40%</strong></span> </div> </section>
<!-- βββ PANEL 2: Market Volatility Gauge ββββββββββββββββββββββ --> <section class="glass-panel volatility-panel" id="volatility-panel"> <div class="panel-header"> <h2><i class="fas fa-wave-square gold"></i> Market Volatility</h2> </div> <div class="gauge-container"> <svg class="gauge-svg" viewBox="0 0 200 120"> <path class="gauge-bg" d="M 20 100 A 80 80 0 0 1 180 100" fill="none" stroke="rgba(255,255,255,0.08)" stroke-width="14" stroke-linecap="round"/> <path class="gauge-fill" id="gauge-arc" d="M 20 100 A 80 80 0 0 1 180 100" fill="none" stroke="#00ff88" stroke-width="14" stroke-linecap="round" stroke-dasharray="0 251"/> <text x="100" y="90" text-anchor="middle" class="gauge-value" id="gauge-value">β</text> <text x="100" y="110" text-anchor="middle" class="gauge-label" id="gauge-label">Low</text> </svg> </div> <div class="volatility-stats"> <div class="stat-item"> <span class="stat-label">Tick Velocity</span> <span class="stat-value" id="tick-velocity">β</span> </div> <div class="stat-item"> <span class="stat-label">Max Shift %</span> <span class="stat-value" id="max-shift">β</span> </div> <div class="stat-item"> <span class="stat-label">Delta</span> <span class="stat-value" id="delta-label">β</span> </div> </div> </section>
<!-- βββ PANEL 3: Over/Under Lines Table βββββββββββββββββββββββ --> <section class="glass-panel ou-panel" id="ou-panel"> <div class="panel-header"> <h2><i class="fas fa-arrows-up-down neon-green"></i> Over / Under Lines</h2> <span class="update-time" id="ou-updated">β</span> </div> <div class="table-wrapper"> <table class="styled-table"> <thead> <tr> <th>Market</th> <th>Line</th> <th>Over <span class="odds-col">(Odds)</span></th> <th>Under <span class="odds-col">(Odds)</span></th> <th>Projected</th> <th>Confidence</th> </tr> </thead> <tbody id="ou-tbody"> <tr class="skeleton-row"><td colspan="6">Loadingβ¦</td></tr> </tbody> </table> </div> </section>
<!-- βββ PANEL 4: Next Wicket Method βββββββββββββββββββββββββββ --> <section class="glass-panel wicket-panel" id="wicket-panel"> <div class="panel-header"> <h2><i class="fas fa-baseball-bat-ball gold"></i> Next Wicket Method</h2> </div> <div class="wicket-methods" id="wicket-methods"> <div class="wicket-empty">Awaiting dataβ¦</div> </div> </section>
<!-- βββ PANEL 5: Prop-Bet Heatmap βββββββββββββββββββββββββββββ --> <section class="glass-panel heatmap-panel" id="heatmap-panel"> <div class="panel-header"> <h2><i class="fas fa-fire neon-green"></i> Prop-Bet Heatmap</h2> <span class="panel-badge">Player Milestones</span> </div> <div class="heatmap-grid" id="heatmap-grid"> <div class="heatmap-empty">Connecting to live feedβ¦</div> </div> <div class="heatmap-legend"> <span class="legend-item"><span class="legend-swatch" style="background:#ff3333"></span> < 20%</span> <span class="legend-item"><span class="legend-swatch" style="background:#ff8800"></span> 20β40%</span> <span class="legend-item"><span class="legend-swatch" style="background:#ffd700"></span> 40β60%</span> <span class="legend-item"><span class="legend-swatch" style="background:#88ff44"></span> 60β80%</span> <span class="legend-item"><span class="legend-swatch" style="background:#00ff88"></span> > 80%</span> </div> </section>
<!-- βββ PANEL 6: Match Scorecard ββββββββββββββββββββββββββββββ --> <section class="glass-panel scorecard-panel" id="scorecard-panel"> <div class="panel-header"> <h2><i class="fas fa-clipboard-list gold"></i> Live Scorecard</h2> </div> <div class="scorecard-body" id="scorecard-body"> <div class="score-main"> <div class="score-total"> <span class="score-runs" id="score-runs">0</span> <span class="score-wickets">/ <span id="score-wickets">0</span></span> </div> <div class="score-overs">(<span id="score-overs">0.0</span> ov)</div> </div> <div class="score-extras" id="score-extras"> <div class="extra-stat"> <span>CRR</span> <strong id="stat-crr">0.00</strong> </div> <div class="extra-stat"> <span>Phase</span> <strong id="stat-phase">β</strong> </div> <div class="extra-stat"> <span>Proj.</span> <strong id="stat-projected">β</strong> </div> </div> </div> </section>
</main>
<!-- βββ FOOTER βββββββββββββββββββββββββββββββββββββββββββββββββββββββ --> <footer class="app-footer"> <span>IPL Pro-Analytics Engine v2.0</span> <span>Β·</span> <span>Hybrid XGBoost + LSTM</span> <span>Β·</span> <span id="footer-latency">Latency: β</span> </footer>
<!-- βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ --> <script src="app.js"></script></body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359"""IPL Prediction Engine β FastAPI Application=============================================Main entry-point. Mounts: β’ REST endpoints (/predict/{match_id}, /health) β’ WebSocket (/ws/odds/{match_id}) β’ Static frontend (/ β serves index.html)
Integration Guide-----------------To wire `calculate_betting_metrics` into your EXISTING `/predict/{match_id}`endpoint, locate the "β οΈ INTEGRATION POINT" comments below. Copy thehighlighted block into your own route β nothing else needs to change."""
from __future__ import annotations
import asyncioimport jsonimport loggingimport timefrom contextlib import asynccontextmanagerfrom pathlib import Pathfrom typing import Optional
import numpy as npfrom fastapi import FastAPI, WebSocket, WebSocketDisconnect, Queryfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import HTMLResponse, FileResponsefrom fastapi.staticfiles import StaticFiles
from models import ( BallData, BettingMetrics, EliteInsights, WsOddsTick, WsPropBetUpdate, HistoricalOddsSnapshot,)from betting_metrics import calculate_betting_metrics
# βββ Logging ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββlogging.basicConfig(level=logging.INFO)logger = logging.getLogger("ipl-engine")
# βββ Lifespan βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ@asynccontextmanagerasync def lifespan(app: FastAPI): """Startup / shutdown hooks β initialise shared state here.""" # In-memory odds-history ring buffer per match (max 200 ticks) app.state.odds_history: dict[str, list[HistoricalOddsSnapshot]] = {} # WebSocket connection manager app.state.ws_clients: dict[str, list[WebSocket]] = {} logger.info("IPL Prediction Engine started β") yield logger.info("IPL Prediction Engine shutting down β¦")
# βββ App Factory ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββBASE_DIR = Path(__file__).parent.parentFRONTEND_DIR = BASE_DIR / "frontend"
app = FastAPI( title="IPL Premium Prediction Engine", version="2.0.0", description="Hybrid XGBoost + LSTM model with Premium Betting Insights", lifespan=lifespan,)
# CORS β allow the frontend dev server during developmentapp.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"],)
# βββ Simulated Model Inference (replace with your actual model) ββββββββββdef _run_xgboost_inference(match_id: str, ball: BallData) -> float: """ β οΈ REPLACE this stub with your actual XGBoost model inference. Expected return: win probability β (0, 1). """ # Simulated: slight random walk around 0.5 + innings context base = 0.45 + 0.05 * ball.total_runs / 160.0 - 0.03 * ball.wickets_fallen return float(np.clip(base + 0.02 * np.random.randn(), 0.05, 0.95))
def _run_lstm_inference(match_id: str, ball: BallData) -> float: """ β οΈ REPLACE this stub with your actual LSTM model inference. Expected return: win probability β (0, 1). """ # Simulated LSTM with slightly different prior base = 0.48 + 0.04 * ball.total_runs / 160.0 - 0.025 * ball.wickets_fallen return float(np.clip(base + 0.015 * np.random.randn(), 0.05, 0.95))
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# REST ENDPOINTS# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.get("/health")async def health(): return {"status": "ok", "engine": "ipl-premium-v2"}
@app.get("/predict/{match_id}")async def predict_match( match_id: str, over: float = Query(10.0, ge=0, le=20), ball: int = Query(1, ge=1, le=6), total_runs: int = Query(85, ge=0), wickets: int = Query(2, ge=0, le=10), striker_runs: int = Query(35, ge=0), striker_balls: int = Query(22, ge=0), target: Optional[int] = Query(None, ge=1),): """ β οΈ INTEGRATION POINT ββββββββββββββββββββ This endpoint is a DROP-IN REPLACEMENT for your existing /predict/{match_id}. The `elite_insights` key is appended β your existing keys stay untouched.
Copy the block marked with βββ ELITE INSIGHTS INJECTION βββ into your existing handler. Everything else is your original code. """
# ββ Build ball context ββββββββββββββββββββββββββββββββββββββββββββ ball_data = BallData( over=over, ball=ball, total_runs=total_runs, wickets_fallen=wickets, striker_runs=striker_runs, striker_balls=striker_balls, non_striker_runs=int(striker_runs * 0.6), non_striker_balls=int(striker_balls * 0.8), chasing_target=target, )
# ββ Your existing model inference βββββββββββββββββββββββββββββββββ xgb_prob = _run_xgboost_inference(match_id, ball_data) lstm_prob = _run_lstm_inference(match_id, ball_data)
# Hybrid blend (XGBoost 60 % + LSTM 40 %) blend_weights = {"xgboost": 0.6, "lstm": 0.4} win_probability = ( blend_weights["xgboost"] * xgb_prob + blend_weights["lstm"] * lstm_prob )
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ # β β‘ ELITE INSIGHTS INJECTION β‘ β # β Copy this block into your existing /predict endpoint. β # β It requires: ball_data (BallData), win_probability (float). β # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Fetch odds history for volatility (optional but recommended) history = app.state.odds_history.get(match_id, [])
# Core betting-metrics computation β O(1), no GPU needed betting_metrics: BettingMetrics = calculate_betting_metrics( probability=win_probability, ball_data=ball_data, odds_history=history, )
# Compute sharp edge: |model_prob - implied_prob| / implied_prob implied = betting_metrics.decimal_odds.implied_home sharp_edge = abs(win_probability - implied) / max(implied, 0.01)
# Package into EliteInsights envelope elite_insights = EliteInsights( betting_metrics=betting_metrics, model_blend_weights=blend_weights, sharp_edge_pct=round(sharp_edge * 100, 2), last_updated_ms=int(time.time() * 1000), )
# Update odds history ring buffer snapshot = HistoricalOddsSnapshot( timestamp_ms=int(time.time() * 1000), decimal_odds=betting_metrics.decimal_odds.home, ) if match_id not in app.state.odds_history: app.state.odds_history[match_id] = [] app.state.odds_history[match_id].append(snapshot) if len(app.state.odds_history[match_id]) > 200: app.state.odds_history[match_id] = app.state.odds_history[match_id][-200:]
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# ββ Your existing response structure (extended with elite_insights) β return { "match_id": match_id, "prediction": { "win_probability": round(win_probability, 4), "xgboost_prob": round(xgb_prob, 4), "lstm_prob": round(lstm_prob, 4), "predicted_total": round(betting_metrics.over_under_lines[0].projected_total, 1), "innings_phase": betting_metrics.innings_phase.value, }, # β‘ NEW FIELD β the premium insights payload "elite_insights": elite_insights.model_dump(), }
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# WEBSOCKET β Real-Time Odds Stream# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class ConnectionManager: """Manages WebSocket clients per match."""
def __init__(self): self.active: dict[str, list[WebSocket]] = {}
async def connect(self, match_id: str, ws: WebSocket): await ws.accept() if match_id not in self.active: self.active[match_id] = [] self.active[match_id].append(ws) logger.info(f"WS client connected for match {match_id} " f"(total: {len(self.active[match_id])})")
def disconnect(self, match_id: str, ws: WebSocket): if match_id in self.active: self.active[match_id].remove(ws) if not self.active[match_id]: del self.active[match_id]
async def broadcast(self, match_id: str, message: dict): if match_id not in self.active: return dead = [] for ws in self.active[match_id]: try: await ws.send_json(message) except Exception: dead.append(ws) for ws in dead: self.disconnect(match_id, ws)
manager = ConnectionManager()
@app.websocket("/ws/odds/{match_id}")async def ws_odds_stream(websocket: WebSocket, match_id: str): """ Real-time WebSocket endpoint for live odds ticks. Clients receive two types of messages: 1. WsOddsTick β every 2 seconds (odds + volatility) 2. WsPropBetUpdate β every 5 seconds (prop-bet recalc) """ await manager.connect(match_id, websocket)
# Send initial snapshot immediately ball_data = BallData(over=10, ball=1, total_runs=85, wickets_fallen=2, striker_runs=35, striker_balls=22) history = app.state.odds_history.get(match_id, []) metrics = calculate_betting_metrics(0.55, ball_data, history) tick = WsOddsTick( match_id=match_id, timestamp_ms=int(time.time() * 1000), decimal_odds=metrics.decimal_odds, market_volatility=metrics.market_volatility, delta_label="β", ) await websocket.send_json(tick.model_dump())
try: odds_counter = 0 prop_counter = 0
while True: # Simulate live ball updates (replace with your real feed) await asyncio.sleep(0.5) # 2 Hz tick rate
# Simulate progressing match state ball_data.total_runs += int(np.random.choice([0, 1, 1, 2, 4, 6], p=[0.30, 0.25, 0.20, 0.15, 0.07, 0.03])) ball_data.ball += 1 if ball_data.ball > 6: ball_data.ball = 1 ball_data.over += 1 ball_data.striker_runs = int(np.random.randint(0, 50)) ball_data.striker_balls = int(np.random.randint(5, 40)) if ball_data.over >= 20: ball_data.over = 10 # Reset for demo
history = app.state.odds_history.get(match_id, []) win_p = float(np.clip(0.55 + 0.01 * np.random.randn(), 0.10, 0.90)) metrics = calculate_betting_metrics(win_p, ball_data, history)
# Update ring buffer snapshot = HistoricalOddsSnapshot( timestamp_ms=int(time.time() * 1000), decimal_odds=metrics.decimal_odds.home, ) if match_id not in app.state.odds_history: app.state.odds_history[match_id] = [] app.state.odds_history[match_id].append(snapshot) if len(app.state.odds_history[match_id]) > 200: app.state.odds_history[match_id] = app.state.odds_history[match_id][-200:]
# Determine delta direction prev_snapshot = history[-1] if history else None delta = "β" if prev_snapshot: diff = metrics.decimal_odds.home - prev_snapshot.decimal_odds delta = "β" if diff > 0.005 else "β" if diff < -0.005 else "β"
odds_counter += 1 prop_counter += 1
# Broadcast odds tick every 4 ticks (~2 s) if odds_counter >= 4: odds_counter = 0 tick = WsOddsTick( match_id=match_id, timestamp_ms=int(time.time() * 1000), decimal_odds=metrics.decimal_odds, market_volatility=metrics.market_volatility, delta_label=delta, ) await manager.broadcast(match_id, tick.model_dump())
# Broadcast prop-bet update every 10 ticks (~5 s) if prop_counter >= 10: prop_counter = 0 prop_update = WsPropBetUpdate( match_id=match_id, timestamp_ms=int(time.time() * 1000), prop_bets=metrics.prop_bets, ) await manager.broadcast(match_id, prop_update.model_dump())
except WebSocketDisconnect: manager.disconnect(match_id, websocket) logger.info(f"WS client disconnected from match {match_id}")
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# STATIC FRONTEND# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.get("/", response_class=HTMLResponse)async def serve_frontend(): """Serve the Pro-Analytics dashboard.""" index_path = FRONTEND_DIR / "index.html" if index_path.exists(): return index_path.read_text(encoding="utf-8") return HTMLResponse("<h1>Frontend not found. Place index.html in /frontend/</h1>")
app.mount("/static", StaticFiles(directory=str(FRONTEND_DIR)), name="static")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145"""IPL Premium Betting Insights β Pydantic Data Models=====================================================Defines every schema flowing through the prediction + betting pipeline.All models are JSON-serialisable and typed for IDE / OpenAPI docs."""
from __future__ import annotations
from enum import Enumfrom typing import Optionalfrom pydantic import BaseModel, Field
# βββ Enums ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββclass WicketMethod(str, Enum): CAUGHT = "Caught" BOWLED = "Bowled" LBW = "LBW" RUN_OUT = "Run Out" STUMPED = "Stumped" HIT_WICKET = "Hit Wicket" RETIRED_OUT = "Retired Out"
class InningsPhase(str, Enum): POWERPLAY = "powerplay" # Overs 1-6 MIDDLE = "middle" # Overs 7-15 DEATH = "death" # Overs 16-20
# βββ Request / Context Models ββββββββββββββββββββββββββββββββββββββββββββclass BallData(BaseModel): """Raw ball-level feed consumed by the metrics engine.""" over: float = Field(..., ge=0, le=20, description="Current over") ball: int = Field(..., ge=1, le=6, description="Ball within the over") runs_scored: int = Field(0, ge=0, description="Runs scored off this ball") wickets_fallen: int = Field(0, ge=0, le=10, description="Wickets down so far") total_runs: int = Field(0, ge=0, description="Team total at this point") striker_runs: int = Field(0, ge=0, description="Batsman on strike β runs") striker_balls: int = Field(0, ge=0, description="Batsman on strike β balls faced") non_striker_runs: int = Field(0, ge=0) non_striker_balls: int = Field(0, ge=0) is_wicket_ball: bool = False wicket_method: Optional[WicketMethod] = None extra_type: Optional[str] = None # wide, noball, bye, legbye bowler_wickets: int = Field(0, ge=0) bowler_runs: int = Field(0, ge=0) bowler_overs: float = Field(0, ge=0, le=4) venue: str = "neutral" chasing_target: Optional[int] = None
class HistoricalOddsSnapshot(BaseModel): """A single point in the odds-history timeline for volatility calc.""" timestamp_ms: int decimal_odds: float
# βββ Betting-Metrics Response Models βββββββββββββββββββββββββββββββββββββclass DecimalOdds(BaseModel): home: float = Field(..., gt=0, description="Home team decimal odds") away: float = Field(..., gt=0, description="Away team decimal odds") implied_home: float = Field(..., ge=0, le=1) implied_away: float = Field(..., ge=0, le=1) overround: float = Field(..., description="Bookmaker margin (0 = fair)")
class Config: json_schema_extra = { "example": { "home": 1.85, "away": 2.05, "implied_home": 0.5405, "implied_away": 0.4878, "overround": 0.0283 } }
class OverUnderLine(BaseModel): market: str = Field(..., description="e.g. 'Total Runs', 'Team A Runs'") line: float over_odds: float under_odds: float projected_total: float = Field(..., description="Model-projected value") confidence: float = Field(..., ge=0, le=1)
class NextWicketMethodProb(BaseModel): method: WicketMethod probability: float = Field(..., ge=0, le=1) pressure_multiplier: float = Field(1.0, description="Adjusted by match context")
class MarketVolatility(BaseModel): score: float = Field(..., ge=0, description="0 = calm, 1 = extreme") label: str = Field(..., description="Low / Medium / High / Extreme") tick_velocity: float = Field(..., description="Odds-shifts per minute") max_shift_pct: float = Field(..., description="Largest single-tick % shift")
class PropBetPlayer(BaseModel): player_name: str milestone: str = Field(..., description="e.g. '50+', '100+', '3+ Wickets'") probability: float = Field(..., ge=0, le=1) current_value: int = Field(..., description="Runs / wickets right now") balls_remaining: int = Field(..., ge=0) strike_rate: Optional[float] = None
class BettingMetrics(BaseModel): """Top-level response returned by `calculate_betting_metrics`.""" decimal_odds: DecimalOdds over_under_lines: list[OverUnderLine] next_wicket_method: list[NextWicketMethodProb] market_volatility: MarketVolatility prop_bets: list[PropBetPlayer] innings_phase: InningsPhase projection_confidence: float = Field(..., ge=0, le=1)
# βββ Elite Insights Envelope (attached to /predict) βββββββββββββββββββββclass EliteInsights(BaseModel): betting_metrics: BettingMetrics model_blend_weights: dict[str, float] = Field( default_factory=lambda: {"xgboost": 0.6, "lstm": 0.4} ) sharp_edge_pct: float = Field( ..., description="% edge model has over closing line" ) last_updated_ms: int
# βββ WebSocket Messages βββββββββββββββββββββββββββββββββββββββββββββββββclass WsOddsTick(BaseModel): """Pushed every time the odds engine recalculates.""" match_id: str timestamp_ms: int decimal_odds: DecimalOdds market_volatility: MarketVolatility delta_label: str = Field(..., description="β / β / β")
class WsPropBetUpdate(BaseModel): match_id: str timestamp_ms: int prop_bets: list[PropBetPlayer]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942/* βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ IPL Pro-Analytics β Glassmorphism Dark Theme βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ Colour System βββββββββββββ β’ Background: #0a0a0f β #0d1117 gradient β’ Glass panels: rgba(255,255,255,0.04) blur(24px) β’ Primary accent: #00ff88 (Neon Green) β’ Secondary: #ffd700 (Gold) β’ Danger: #ff3366 β’ Text: #e8e8e8 / #8b8fa3 βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */
/* βββ Reset & Base ββββββββββββββββββββββββββββββββββββββββββββββββββββ */*, *::before, *::after { margin: 0; padding: 0; box-sizing: border-box;}
:root { --bg-deep: #06060b; --bg-primary: #0a0a0f; --bg-secondary: #0d1117; --bg-elevated: #161b22;
--glass-bg: rgba(255, 255, 255, 0.04); --glass-border: rgba(255, 255, 255, 0.08); --glass-hover: rgba(255, 255, 255, 0.07); --glass-blur: 24px;
--neon-green: #00ff88; --neon-green-dim: #00cc6a; --neon-green-bg: rgba(0, 255, 136, 0.08);
--gold: #ffd700; --gold-dim: #ccac00; --gold-bg: rgba(255, 215, 0, 0.08);
--danger: #ff3366; --danger-bg: rgba(255, 51, 102, 0.08);
--text-primary: #e8e8ec; --text-secondary: #8b8fa3; --text-muted: #525569;
--radius-sm: 8px; --radius-md: 14px; --radius-lg: 20px; --radius-xl: 28px;
--font-main: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif; --font-mono: 'JetBrains Mono', 'Fira Code', monospace;
--shadow-glow-green: 0 0 30px rgba(0, 255, 136, 0.15), 0 0 60px rgba(0, 255, 136, 0.05); --shadow-glow-gold: 0 0 30px rgba(255, 215, 0, 0.15), 0 0 60px rgba(255, 215, 0, 0.05);
--transition-fast: 150ms cubic-bezier(0.4, 0, 0.2, 1); --transition-smooth: 300ms cubic-bezier(0.4, 0, 0.2, 1);}
html { font-size: 16px; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale;}
body { font-family: var(--font-main); background: linear-gradient(145deg, var(--bg-deep) 0%, var(--bg-primary) 40%, var(--bg-secondary) 100%); color: var(--text-primary); min-height: 100vh; overflow-x: hidden; line-height: 1.6;}
/* Animated background particles */body::before { content: ''; position: fixed; inset: 0; background: radial-gradient(2px 2px at 20% 30%, var(--neon-green), transparent), radial-gradient(2px 2px at 40% 70%, var(--gold), transparent), radial-gradient(1px 1px at 60% 20%, rgba(255,255,255,0.3), transparent), radial-gradient(1px 1px at 80% 60%, rgba(255,255,255,0.2), transparent), radial-gradient(2px 2px at 10% 80%, var(--neon-green-dim), transparent), radial-gradient(1px 1px at 90% 40%, var(--gold-dim), transparent); background-size: 250px 250px, 300px 300px, 200px 200px, 350px 350px, 280px 280px, 320px 320px; animation: particleDrift 80s linear infinite; pointer-events: none; z-index: 0;}
@keyframes particleDrift { 0% { transform: translate(0, 0); } 100% { transform: translate(-250px, -250px); }}
/* βββ Utility Classes ββββββββββββββββββββββββββββββββββββββββββββββββ */.neon-green { color: var(--neon-green); }.gold { color: var(--gold); }.danger { color: var(--danger); }
/* βββ Glass Panel ββββββββββββββββββββββββββββββββββββββββββββββββββββ */.glass-panel { background: var(--glass-bg); backdrop-filter: blur(var(--glass-blur)); -webkit-backdrop-filter: blur(var(--glass-blur)); border: 1px solid var(--glass-border); border-radius: var(--radius-lg); padding: 1.5rem; position: relative; overflow: hidden; transition: border-color var(--transition-smooth), box-shadow var(--transition-smooth); z-index: 1;}
.glass-panel::before { content: ''; position: absolute; top: 0; left: 0; right: 0; height: 1px; background: linear-gradient(90deg, transparent, rgba(255,255,255,0.15), transparent);}
.glass-panel:hover { border-color: rgba(255, 255, 255, 0.12); box-shadow: 0 8px 40px rgba(0, 0, 0, 0.3);}
.panel-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 1.25rem;}
.panel-header h2 { font-size: 1rem; font-weight: 600; letter-spacing: 0.02em; display: flex; align-items: center; gap: 0.5rem;}
.panel-header h2 i { font-size: 0.9rem;}
.panel-badge { font-size: 0.7rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.08em; color: var(--text-muted); background: rgba(255,255,255,0.05); padding: 0.25rem 0.6rem; border-radius: 100px; border: 1px solid rgba(255,255,255,0.06);}
/* βββ Top Bar ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */.top-bar { display: flex; align-items: center; justify-content: space-between; padding: 1rem 2rem; background: rgba(10, 10, 15, 0.8); backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px); border-bottom: 1px solid var(--glass-border); position: sticky; top: 0; z-index: 100;}
.top-bar__brand { display: flex; align-items: center; gap: 0.85rem;}
.brand-icon { width: 42px; height: 42px; display: flex; align-items: center; justify-content: center; background: linear-gradient(135deg, var(--neon-green), var(--gold)); border-radius: var(--radius-md); font-size: 1.1rem; color: var(--bg-deep); animation: iconPulse 3s ease-in-out infinite;}
@keyframes iconPulse { 0%, 100% { box-shadow: 0 0 15px rgba(0,255,136,0.3); } 50% { box-shadow: 0 0 25px rgba(255,215,0,0.3); }}
.brand-title { font-size: 1.2rem; font-weight: 800; letter-spacing: -0.02em;}
.brand-subtitle { font-size: 0.7rem; color: var(--text-muted); letter-spacing: 0.04em; text-transform: uppercase;}
.top-bar__controls { display: flex; align-items: center; gap: 1.25rem;}
.match-selector { display: flex; align-items: center; gap: 0.5rem;}
.match-selector label { font-size: 0.75rem; color: var(--text-muted);}
.match-selector select { background: var(--bg-elevated); border: 1px solid var(--glass-border); color: var(--text-primary); padding: 0.4rem 0.75rem; border-radius: var(--radius-sm); font-family: var(--font-main); font-size: 0.8rem; cursor: pointer; outline: none; transition: border-color var(--transition-fast);}
.match-selector select:focus { border-color: var(--neon-green);}
.connection-badge { display: flex; align-items: center; gap: 0.4rem; font-size: 0.75rem; font-weight: 500; padding: 0.35rem 0.75rem; border-radius: 100px; background: rgba(255,255,255,0.04); border: 1px solid var(--glass-border);}
.conn-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--text-muted); animation: blink 2s infinite;}
.connection-badge.connected .conn-dot { background: var(--neon-green); box-shadow: 0 0 8px var(--neon-green); animation: none;}
.connection-badge.disconnected .conn-dot { background: var(--danger); box-shadow: 0 0 8px var(--danger); animation: none;}
@keyframes blink { 0%, 100% { opacity: 1; } 50% { opacity: 0.3; }}
/* βββ Dashboard Grid βββββββββββββββββββββββββββββββββββββββββββββββββ */.dashboard-grid { display: grid; grid-template-columns: 1fr 1fr; grid-template-rows: auto; gap: 1.25rem; padding: 1.5rem 2rem; max-width: 1440px; margin: 0 auto;}
/* Panel 1 β Odds: spans full width */.odds-panel { grid-column: 1 / -1;}
/* Panel 2 β Volatility: 1 col */.volatility-panel { grid-column: 1;}
/* Panel 3 β Over/Under: 1 col */.ou-panel { grid-column: 2;}
/* Panel 4 β Wicket Method */.wicket-panel { grid-column: 1;}
/* Panel 5 β Heatmap: spans full width */.heatmap-panel { grid-column: 1 / -1;}
/* Panel 6 β Scorecard */.scorecard-panel { grid-column: 1 / -1;}
/* βββ Live Odds Panel ββββββββββββββββββββββββββββββββββββββββββββββββ */.odds-body { display: flex; align-items: center; justify-content: center; gap: 2rem; margin-bottom: 1rem;}
.odds-team { flex: 1; text-align: center;}
.team-label { font-size: 1.6rem; font-weight: 800; letter-spacing: 0.05em; margin-bottom: 0.25rem;}
.odds-value { font-family: var(--font-mono); font-size: 2.8rem; font-weight: 700; line-height: 1.1; transition: color var(--transition-fast);}
.implied { font-size: 0.75rem; color: var(--text-muted); margin-top: 0.2rem;}
.odds-bar-container { height: 6px; background: rgba(255,255,255,0.06); border-radius: 100px; margin-top: 0.75rem; overflow: hidden;}
.odds-bar { height: 100%; border-radius: 100px; transition: width var(--transition-smooth);}
.odds-bar--home { background: linear-gradient(90deg, var(--neon-green), var(--neon-green-dim));}
.odds-bar--away { background: linear-gradient(90deg, var(--gold-dim), var(--gold));}
.odds-vs { font-size: 0.85rem; font-weight: 700; color: var(--text-muted); letter-spacing: 0.1em;}
.odds-meta { display: flex; justify-content: center; gap: 1.5rem; font-size: 0.72rem; color: var(--text-muted); padding-top: 1rem; border-top: 1px solid var(--glass-border);}
.odds-meta strong { color: var(--text-secondary);}
.live-badge { display: flex; align-items: center; gap: 0.4rem; font-size: 0.7rem; font-weight: 700; color: var(--danger); text-transform: uppercase; letter-spacing: 0.08em;}
.pulse-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--danger); animation: pulse 1.5s ease-in-out infinite;}
@keyframes pulse { 0%, 100% { transform: scale(1); opacity: 1; } 50% { transform: scale(1.5); opacity: 0.5; }}
/* βββ Volatility Gauge βββββββββββββββββββββββββββββββββββββββββββββββ */.gauge-container { display: flex; justify-content: center; padding: 0.5rem 0;}
.gauge-svg { width: 220px; height: 140px;}
.gauge-bg { stroke: rgba(255,255,255,0.06);}
.gauge-fill { transition: stroke-dasharray 0.8s cubic-bezier(0.4, 0, 0.2, 1), stroke 0.5s ease; filter: drop-shadow(0 0 8px currentColor);}
.gauge-value { fill: var(--text-primary); font-family: var(--font-mono); font-size: 28px; font-weight: 700;}
.gauge-label { fill: var(--text-secondary); font-size: 13px; font-weight: 500;}
.volatility-stats { display: grid; grid-template-columns: repeat(3, 1fr); gap: 0.75rem; margin-top: 1rem;}
.stat-item { text-align: center; padding: 0.6rem; background: rgba(255,255,255,0.03); border-radius: var(--radius-sm); border: 1px solid rgba(255,255,255,0.04);}
.stat-label { display: block; font-size: 0.65rem; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.06em; margin-bottom: 0.2rem;}
.stat-value { font-family: var(--font-mono); font-size: 1rem; font-weight: 600; color: var(--text-primary);}
/* βββ Over/Under Table βββββββββββββββββββββββββββββββββββββββββββββββ */.table-wrapper { overflow-x: auto;}
.styled-table { width: 100%; border-collapse: separate; border-spacing: 0; font-size: 0.82rem;}
.styled-table thead th { text-align: left; font-size: 0.68rem; font-weight: 600; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.06em; padding: 0.6rem 0.75rem; border-bottom: 1px solid var(--glass-border); white-space: nowrap;}
.odds-col { font-weight: 400; color: var(--text-muted);}
.styled-table tbody td { padding: 0.65rem 0.75rem; border-bottom: 1px solid rgba(255,255,255,0.03); font-family: var(--font-mono); font-size: 0.8rem; vertical-align: middle;}
.styled-table tbody tr { transition: background var(--transition-fast);}
.styled-table tbody tr:hover { background: rgba(255,255,255,0.03);}
.styled-table tbody td:first-child { font-family: var(--font-main); font-weight: 500; color: var(--text-secondary);}
.update-time { font-size: 0.65rem; color: var(--text-muted); font-family: var(--font-mono);}
.skeleton-row td { text-align: center; color: var(--text-muted); font-family: var(--font-main); font-style: italic;}
/* βββ Wicket Method ββββββββββββββββββββββββββββββββββββββββββββββββββ */.wicket-methods { display: flex; flex-direction: column; gap: 0.6rem;}
.wicket-row { display: flex; align-items: center; gap: 0.75rem; padding: 0.6rem 0.75rem; background: rgba(255,255,255,0.02); border-radius: var(--radius-sm); border: 1px solid rgba(255,255,255,0.04); transition: all var(--transition-fast);}
.wicket-row:hover { background: rgba(255,255,255,0.05); border-color: rgba(255,255,255,0.08);}
.wicket-method-name { font-size: 0.82rem; font-weight: 500; color: var(--text-secondary); min-width: 80px;}
.wicket-prob-bar { flex: 1; height: 8px; background: rgba(255,255,255,0.06); border-radius: 100px; overflow: hidden;}
.wicket-prob-fill { height: 100%; border-radius: 100px; transition: width var(--transition-smooth); background: linear-gradient(90deg, var(--neon-green-dim), var(--neon-green));}
.wicket-prob-fill.top-method { background: linear-gradient(90deg, var(--gold-dim), var(--gold));}
.wicket-prob-value { font-family: var(--font-mono); font-size: 0.82rem; font-weight: 600; color: var(--text-primary); min-width: 50px; text-align: right;}
.wicket-pressure { font-size: 0.65rem; font-family: var(--font-mono); color: var(--neon-green); background: var(--neon-green-bg); padding: 0.15rem 0.45rem; border-radius: 100px;}
.wicket-empty { text-align: center; color: var(--text-muted); font-size: 0.85rem; padding: 1rem;}
/* βββ Prop-Bet Heatmap βββββββββββββββββββββββββββββββββββββββββββββββ */.heatmap-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 0.75rem; min-height: 80px;}
.heatmap-cell { padding: 1rem; border-radius: var(--radius-md); border: 1px solid rgba(255,255,255,0.06); position: relative; overflow: hidden; transition: all var(--transition-smooth); cursor: default;}
.heatmap-cell:hover { transform: translateY(-2px); box-shadow: 0 8px 30px rgba(0, 0, 0, 0.3);}
.heatmap-cell::after { content: ''; position: absolute; top: 0; right: 0; width: 60px; height: 60px; border-radius: 50%; background: inherit; filter: blur(25px); opacity: 0.4; pointer-events: none;}
.heatmap-cell .cell-player { font-size: 0.75rem; font-weight: 600; color: var(--text-primary); margin-bottom: 0.2rem; display: flex; align-items: center; gap: 0.4rem;}
.heatmap-cell .cell-player i { font-size: 0.65rem; opacity: 0.6;}
.heatmap-cell .cell-milestone { font-size: 0.65rem; color: var(--text-muted); margin-bottom: 0.6rem; text-transform: uppercase; letter-spacing: 0.04em;}
.heatmap-cell .cell-prob { font-family: var(--font-mono); font-size: 1.4rem; font-weight: 700; margin-bottom: 0.3rem;}
.heatmap-cell .cell-stats { font-size: 0.65rem; color: var(--text-muted); display: flex; gap: 0.6rem;}
.heatmap-cell .cell-stats span { display: flex; align-items: center; gap: 0.2rem;}
/* Heatmap colour bands */.heatmap-cell.prob-very-low { background: rgba(255, 51, 51, 0.08); border-color: rgba(255, 51, 51, 0.15); }.heatmap-cell.prob-low { background: rgba(255, 136, 0, 0.08); border-color: rgba(255, 136, 0, 0.15); }.heatmap-cell.prob-medium { background: rgba(255, 215, 0, 0.08); border-color: rgba(255, 215, 0, 0.15); }.heatmap-cell.prob-high { background: rgba(136, 255, 68, 0.08); border-color: rgba(136, 255, 68, 0.15); }.heatmap-cell.prob-very-high { background: rgba(0, 255, 136, 0.08); border-color: rgba(0, 255, 136, 0.20); box-shadow: 0 0 20px rgba(0, 255, 136, 0.06); }
.heatmap-cell.prob-very-low .cell-prob { color: #ff5555; }.heatmap-cell.prob-low .cell-prob { color: #ff8800; }.heatmap-cell.prob-medium .cell-prob { color: var(--gold); }.heatmap-cell.prob-high .cell-prob { color: #88ff44; }.heatmap-cell.prob-very-high .cell-prob { color: var(--neon-green); }
.heatmap-legend { display: flex; justify-content: center; gap: 1rem; margin-top: 1rem; padding-top: 0.75rem; border-top: 1px solid var(--glass-border);}
.legend-item { display: flex; align-items: center; gap: 0.35rem; font-size: 0.65rem; color: var(--text-muted);}
.legend-swatch { width: 10px; height: 10px; border-radius: 3px;}
.heatmap-empty { grid-column: 1 / -1; text-align: center; color: var(--text-muted); font-size: 0.85rem; padding: 2rem;}
/* βββ Scorecard ββββββββββββββββββββββββββββββββββββββββββββββββββββββ */.scorecard-body { display: flex; align-items: center; justify-content: space-between;}
.score-main { text-align: left;}
.score-runs { font-family: var(--font-mono); font-size: 3rem; font-weight: 800; color: var(--text-primary); line-height: 1;}
.score-wickets { font-size: 1.8rem; color: var(--text-secondary);}
.score-overs { font-size: 0.85rem; color: var(--text-muted); margin-top: 0.15rem; font-family: var(--font-mono);}
.score-extras { display: grid; grid-template-columns: repeat(3, 1fr); gap: 0.75rem;}
.extra-stat { text-align: center; padding: 0.75rem 1.25rem; background: rgba(255,255,255,0.03); border-radius: var(--radius-sm); border: 1px solid rgba(255,255,255,0.05);}
.extra-stat span { display: block; font-size: 0.65rem; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.06em; margin-bottom: 0.15rem;}
.extra-stat strong { font-family: var(--font-mono); font-size: 1.05rem; color: var(--text-primary);}
/* βββ Footer βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */.app-footer { text-align: center; padding: 1rem 2rem; font-size: 0.7rem; color: var(--text-muted); border-top: 1px solid var(--glass-border); display: flex; align-items: center; justify-content: center; gap: 0.6rem;}
/* βββ Odds Flash Animations ββββββββββββββββββββββββββββββββββββββββββ */@keyframes oddsFlashGreen { 0% { color: var(--neon-green); text-shadow: 0 0 15px var(--neon-green); } 100% { color: var(--text-primary); text-shadow: none; }}
@keyframes oddsFlashGold { 0% { color: var(--gold); text-shadow: 0 0 15px var(--gold); } 100% { color: var(--text-primary); text-shadow: none; }}
.odds-flash-up { animation: oddsFlashGreen 1s ease-out;}
.odds-flash-down { animation: oddsFlashGold 1s ease-out;}
/* βββ Responsive βββββββββββββββββββββββββββββββββββββββββββββββββββββ */@media (max-width: 1024px) { .dashboard-grid { grid-template-columns: 1fr; padding: 1rem; gap: 1rem; }
.odds-panel, .heatmap-panel, .scorecard-panel, .volatility-panel, .ou-panel, .wicket-panel { grid-column: 1; }
.top-bar { flex-direction: column; gap: 0.75rem; padding: 0.75rem 1rem; }
.top-bar__controls { width: 100%; justify-content: space-between; }
.odds-value { font-size: 2rem; }
.score-runs { font-size: 2.2rem; }}
@media (max-width: 640px) { .odds-body { flex-direction: column; gap: 1rem; }
.odds-vs { display: none; }
.odds-meta { flex-wrap: wrap; gap: 0.75rem; }
.volatility-stats { grid-template-columns: 1fr; }
.scorecard-body { flex-direction: column; gap: 1rem; text-align: center; }
.score-main { text-align: center; }
.heatmap-grid { grid-template-columns: 1fr; }
.heatmap-legend { flex-wrap: wrap; gap: 0.5rem; }}
/* βββ Scrollbar ββββββββββββββββββββββββββββββββββββββββββββββββββββββ */::-webkit-scrollbar { width: 6px; height: 6px;}
::-webkit-scrollbar-track { background: transparent;}
::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.1); border-radius: 100px;}
::-webkit-scrollbar-thumb:hover { background: rgba(255,255,255,0.2);}.gitignore
PUSH_ALL.ps1Added+26
backend/api/stats_router.py+2-2
backend/api_server.py+26-10
backend/ml_engine/hybrid_model.py+7-2
sync_to_hf.pyAdded+56
zai/app.jsDeleted-595
zai/betting_metrics.pyDeleted-499
zai/index.htmlDeleted-206
zai/main.pyDeleted-359
zai/models.pyDeleted-145
zai/styles.cssDeleted-942