durgexh commited on
Commit
39cc212
·
verified ·
1 Parent(s): c09218e

Upload 9 files

Browse files
Files changed (5) hide show
  1. app.js +113 -133
  2. history.js +37 -5
  3. index.html +1 -0
  4. main.py +83 -19
  5. style.css +17 -0
app.js CHANGED
@@ -1,133 +1,113 @@
1
- // Real-time Mock Engine Outcomes
2
- const liveOutcomes = [
3
- { delivery: "Inswinger, Good Length", outcome: "Defends - No Run", probD: 82, probO: 76 },
4
- { delivery: "Yorker, Middle & Leg", outcome: "Squeezes to Point - 1 Run", probD: 65, probO: 58 },
5
- { delivery: "Bouncer, At the Body", outcome: "Hook Shot - SIX over Fine Leg!!!", probD: 45, probO: 32 },
6
- { delivery: "Slower Ball, Outside Off", outcome: "Swings and Misses - Dot Ball", probD: 78, probO: 81 },
7
- { delivery: "Outswinger, Full Length", outcome: "Cover Drive - FOUR Runs!", probD: 60, probO: 55 },
8
- { delivery: "Wide Yorker", outcome: "Slashes to Third Man - FOUR Runs", probD: 53, probO: 44 }
9
- ];
10
-
11
- document.addEventListener('DOMContentLoaded', () => {
12
- // Top Bar Elements
13
- const statusBadge = document.getElementById('matchStatusBadge');
14
- const team1El = document.getElementById('team1Text');
15
- const team2El = document.getElementById('team2Text');
16
- const scoreEl = document.getElementById('liveScoreText');
17
- const overEl = document.getElementById('liveOverText');
18
- const apiIndicator = document.getElementById('apiStatus');
19
-
20
- // Context Panels
21
- const venueEl = document.getElementById('venueText');
22
- const subEl = document.getElementById('matchSubtitle');
23
-
24
- // UI Panes
25
- const liveBox = document.getElementById('livePredictorBox');
26
- const upcBox = document.getElementById('upcomingPredictorBox');
27
- const titleEl = document.getElementById('predictionTitle');
28
-
29
- // Instantly bypass external API and load reliable presentation data
30
- apiIndicator.innerText = "LOCAL ENGINE: ACTIVE";
31
- apiIndicator.style.color = "var(--accent-green)";
32
-
33
- // Set Presentation Match Data directly
34
- const t1 = "LSG";
35
- const t2 = "KKR";
36
-
37
- // Choose mode: true for Live Dashboard, false for Upcoming Dashboard
38
- const IS_LIVE = true;
39
-
40
- if (IS_LIVE) {
41
- statusBadge.innerText = "🔥 MATCH IN PROGRESS";
42
- statusBadge.style.color = "#ef4444";
43
- statusBadge.style.borderColor = "#ef4444";
44
- statusBadge.style.backgroundColor = "rgba(239, 68, 68, 0.1)";
45
-
46
- team1El.innerText = t1;
47
- team2El.innerText = t2;
48
- venueEl.innerText = "Ekana Sports City";
49
- subEl.innerText = "IPL Presentation Match";
50
-
51
- scoreEl.innerText = "142 / 4";
52
- overEl.innerText = "15.2 Overs";
53
- scoreEl.classList.remove('hidden');
54
- overEl.classList.remove('hidden');
55
-
56
- document.getElementById('contextLabel1').innerText = "Striker";
57
- document.getElementById('contextValue1').innerText = "KL Rahul (58* off 42)";
58
- document.getElementById('contextLabel2').innerText = "Bowler";
59
- document.getElementById('contextValue2').innerText = "Sunil Narine (1/24 in 3 ov)";
60
- document.getElementById('pitchText').innerText = "Slow, Turning Track";
61
-
62
- titleEl.innerText = "LIVE BALL PREDICTIONS ACTIVE";
63
- liveBox.classList.remove('hidden');
64
- upcBox.classList.add('hidden');
65
-
66
- cycleLivePredictions();
67
- } else {
68
- statusBadge.innerText = "⏳ UPCOMING FIXTURE";
69
- statusBadge.style.color = "var(--accent-cyan)";
70
-
71
- team1El.innerText = t1;
72
- team2El.innerText = t2;
73
- venueEl.innerText = "Ekana Sports City";
74
- subEl.innerText = "Upcoming Schedule";
75
-
76
- document.getElementById('pitchText').innerText = "AI awaiting toss data...";
77
-
78
- liveBox.classList.add('hidden');
79
- upcBox.classList.remove('hidden');
80
- titleEl.innerText = "UPCOMING MATCH AI OVERVIEW";
81
-
82
- const p1 = document.getElementById('winProbBar');
83
- const fT = document.getElementById('favoredTeamText');
84
- const pT = document.getElementById('winProbText');
85
-
86
- const winProb = 64;
87
- fT.innerText = t1;
88
- pT.innerText = `${winProb}% Probability to Win`;
89
-
90
- setTimeout(() => { p1.style.width = `${winProb}%`; }, 300);
91
-
92
- document.getElementById('factor1').innerText = `AI historical data shows ${t1} has a +15% dominance matrix on home turf.`;
93
- document.getElementById('factor2').innerText = `Weather and ground toss dynamics inherently favor the chasing team by 14%.`;
94
- }
95
-
96
- function cycleLivePredictions() {
97
- const dOut = document.getElementById('deliveryOut');
98
- const oOut = document.getElementById('outcomeOut');
99
- const dProbBar = document.getElementById('delProbBar');
100
- const oProbBar = document.getElementById('outProbBar');
101
- const dProbText = document.getElementById('delProbText');
102
- const oProbText = document.getElementById('outProbText');
103
-
104
- // Let's increment balls visually
105
- let curScore = 142;
106
- let balls = 2; // starting 15.2
107
-
108
- setInterval(() => {
109
- dProbBar.style.width = '0%';
110
- oProbBar.style.width = '0%';
111
- dOut.innerHTML = "<span style='color: var(--text-muted); font-size: 1.2rem'>AI Re-calculating Next Ball...</span>";
112
- oOut.innerHTML = "...";
113
-
114
- setTimeout(() => {
115
- const p = liveOutcomes[Math.floor(Math.random() * liveOutcomes.length)];
116
-
117
- // update fake score
118
- balls++;
119
- if (balls > 6) { balls = 1; }
120
- overEl.innerText = `15.${balls} Overs`;
121
-
122
- dOut.innerText = p.delivery;
123
- oOut.innerText = p.outcome;
124
-
125
- dProbBar.style.width = `${p.probD}%`;
126
- oProbBar.style.width = `${p.probO}%`;
127
-
128
- dProbText.innerText = `${p.probD}% Probability`;
129
- oProbText.innerText = `${p.probO}% Probability`;
130
- }, 1000);
131
- }, 5000); // Cycles continuously every 5 seconds
132
- }
133
- });
 
1
+ // Handle dynamic fetches from the Python Backend
2
+ document.addEventListener('DOMContentLoaded', () => {
3
+ // Top Bar Elements
4
+ const statusBadge = document.getElementById('matchStatusBadge');
5
+ const team1El = document.getElementById('team1Text');
6
+ const team2El = document.getElementById('team2Text');
7
+ const scoreEl = document.getElementById('liveScoreText');
8
+ const overEl = document.getElementById('liveOverText');
9
+ const rrEl = document.getElementById('matchRunRateText');
10
+ const apiIndicator = document.getElementById('apiStatus');
11
+ const venueEl = document.getElementById('venueText');
12
+ const subEl = document.getElementById('matchSubtitle');
13
+
14
+ // UI Panes
15
+ const liveBox = document.getElementById('livePredictorBox');
16
+ const upcBox = document.getElementById('upcomingPredictorBox');
17
+ const titleEl = document.getElementById('predictionTitle');
18
+ const refreshBtn = document.getElementById('refreshBtn');
19
+
20
+ async function syncBackendData() {
21
+ try {
22
+ apiIndicator.innerText = "SERVER: SYNCING...";
23
+ apiIndicator.style.color = "yellow";
24
+
25
+ // Fetch exactly from Python Server memory state!
26
+ const res = await fetch('/api/state');
27
+ const state = await res.json();
28
+
29
+ apiIndicator.innerText = "SERVER: CONNECTED";
30
+ apiIndicator.style.color = "var(--accent-green)";
31
+
32
+ team1El.innerText = state.teams[0] || "Team 1";
33
+ team2El.innerText = state.teams[1] || "Team 2";
34
+ venueEl.innerText = state.venue;
35
+
36
+ if (state.live) {
37
+ statusBadge.innerText = "🔥 MATCH IN PROGRESS";
38
+ statusBadge.style.color = "#ef4444";
39
+ statusBadge.style.background = "rgba(239, 68, 68, 0.1)";
40
+
41
+ scoreEl.innerText = state.score;
42
+ overEl.innerText = state.overs + " Overs";
43
+
44
+ scoreEl.classList.remove('hidden');
45
+ overEl.classList.remove('hidden');
46
+
47
+ subEl.innerText = "Live AI Tracking";
48
+
49
+ titleEl.innerText = "LIVE BALL PREDICTIONS ACTIVE";
50
+ liveBox.classList.remove('hidden');
51
+ upcBox.classList.add('hidden');
52
+
53
+ reCalculateAI(); // trigger the visual bars
54
+ } else {
55
+ statusBadge.innerText = "⏳ UPCOMING FIXTURE";
56
+ statusBadge.style.color = "var(--accent-cyan)";
57
+ statusBadge.style.background = "rgba(6, 182, 212, 0.1)";
58
+
59
+ scoreEl.classList.add('hidden');
60
+ overEl.classList.add('hidden');
61
+ subEl.innerText = "Processing Upcoming Schedule";
62
+
63
+ liveBox.classList.add('hidden');
64
+ upcBox.classList.remove('hidden');
65
+ titleEl.innerText = "UPCOMING MATCH WIN PROBABILITY";
66
+
67
+ document.getElementById('favoredTeamText').innerText = state.teams[0];
68
+ document.getElementById('winProbBar').style.width = "72%";
69
+ document.getElementById('winProbText').innerText = "72% Probability";
70
+ }
71
+ } catch(e) {
72
+ console.error("Backend Disconnected:", e);
73
+ apiIndicator.innerText = "SERVER: OFFLINE";
74
+ apiIndicator.style.color = "red";
75
+ }
76
+ }
77
+
78
+ function reCalculateAI() {
79
+ const dOut = document.getElementById('deliveryOut');
80
+ const oOut = document.getElementById('outcomeOut');
81
+ const dProbBar = document.getElementById('delProbBar');
82
+ const oProbBar = document.getElementById('outProbBar');
83
+
84
+ dProbBar.style.width = '0%';
85
+ oProbBar.style.width = '0%';
86
+ dOut.innerHTML = "<span class='text-muted'>Re-calculating Data...</span>";
87
+
88
+ // Random permutations representing dynamic engine
89
+ const outcomes = ["Defends - No Run", "Squeezes to Point - 1 Run", "Hook Shot - SIX!!!", "Bowled", "Cover Drive - FOUR"];
90
+ const dels = ["Inswinger", "Yorker", "Slower Bouncer", "Wide Yorker", "Good Length"];
91
+
92
+ setTimeout(() => {
93
+ dOut.innerText = dels[Math.floor(Math.random() * dels.length)];
94
+ oOut.innerText = outcomes[Math.floor(Math.random() * outcomes.length)];
95
+
96
+ dProbBar.style.width = `${Math.floor(Math.random() * 40 + 50)}%`;
97
+ oProbBar.style.width = `${Math.floor(Math.random() * 40 + 50)}%`;
98
+ }, 800);
99
+ }
100
+
101
+ if (refreshBtn) {
102
+ refreshBtn.addEventListener('click', () => {
103
+ refreshBtn.innerHTML = "🔄 Syncing...";
104
+ syncBackendData().then(() => {
105
+ setTimeout(() => { refreshBtn.innerHTML = "🔄 Refresh Live State"; }, 500);
106
+ });
107
+ });
108
+ }
109
+
110
+ // Auto update every 12 seconds
111
+ setInterval(syncBackendData, 12000);
112
+ syncBackendData(); // Init
113
+ });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
history.js CHANGED
@@ -1,5 +1,37 @@
1
- // Emptied because the model was initialized today
2
- // Real history will be generated after today's logic.
3
- document.addEventListener('DOMContentLoaded', () => {
4
- // Memory wiped
5
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ document.addEventListener('DOMContentLoaded', async () => {
2
+ const tbody = document.getElementById('historyTableBody');
3
+ if(!tbody) return;
4
+
5
+ async function fetchHistory() {
6
+ try {
7
+ const res = await fetch('/api/history');
8
+ const historyData = await res.json();
9
+
10
+ tbody.innerHTML = '';
11
+
12
+ if (historyData.length === 0) {
13
+ tbody.innerHTML = '<tr><td colspan="6" style="text-align:center; padding:3rem; color:var(--text-muted)">The AI Engine has booted up.<br>Waiting for live match data to process before generating history records...</td></tr>';
14
+ return;
15
+ }
16
+
17
+ historyData.forEach(item => {
18
+ const tr = document.createElement('tr');
19
+ tr.innerHTML = `
20
+ <td>${item.time}</td>
21
+ <td style="font-weight:bold; color:var(--text-main)">${item.match}</td>
22
+ <td>${item.over} Overs</td>
23
+ <td>${item.score}</td>
24
+ <td class="match-yes">${item.prediction}</td>
25
+ <td style="color:var(--accent-green)">✓ Logged</td>
26
+ `;
27
+ tbody.appendChild(tr);
28
+ });
29
+ } catch(e) {
30
+ console.error("History fetch error", e);
31
+ }
32
+ }
33
+
34
+ fetchHistory();
35
+ // Refresh history grid every 15 seconds automatically
36
+ setInterval(fetchHistory, 15000);
37
+ });
index.html CHANGED
@@ -15,6 +15,7 @@
15
  <span class="ai-glow">Predict</span>IPL
16
  </div>
17
  <ul class="nav-links">
 
18
  <li><a href="index.html" class="active">Live Prediction</a></li>
19
  <li><a href="history.html">Match History</a></li>
20
  </ul>
 
15
  <span class="ai-glow">Predict</span>IPL
16
  </div>
17
  <ul class="nav-links">
18
+ <li><button id="refreshBtn" class="refresh-btn">🔄 Refresh Live State</button></li>
19
  <li><a href="index.html" class="active">Live Prediction</a></li>
20
  <li><a href="history.html">Match History</a></li>
21
  </ul>
main.py CHANGED
@@ -1,36 +1,100 @@
1
  from fastapi import FastAPI
2
  from fastapi.staticfiles import StaticFiles
 
3
  import uvicorn
4
  import threading
5
  import time
6
-
7
- # You can import the bypass function from your scraper.py when you're ready
8
- # from scraper import bypass_firewall
9
 
10
  app = FastAPI()
11
 
12
- # This tells the server to statically serve your HTML, CSS, and JS exactly as they are without breaking the design.
13
- app.mount("/", StaticFiles(directory=".", html=True), name="static")
 
 
 
 
 
 
 
 
 
14
 
15
- # ==============================================================================
16
- # HUGGING FACE BACKGROUND TASK ARCHITECTURE
17
- # When you activate this, the cloud computer will automatically run your hacker script
18
- # in the background 24/7 independently of the website viewers.
19
- # ==============================================================================
20
- def autonomous_data_heist():
21
  while True:
22
  try:
23
- print("Background Cloud Server: Attempting ESPNcricinfo Bypass Check...")
24
- # bypass_firewall() # Trigger the scraper
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  except Exception as e:
26
- print("Routine network reset.")
27
 
28
- time.sleep(30) # Rips the database every 30 seconds to prevent bans
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
- # Start the background task as a ghost thread
31
- threading.Thread(target=autonomous_data_heist, daemon=True).start()
32
 
33
  if __name__ == "__main__":
34
- # Hugging Face Spaces strictly requires servers to broadcast on port 7860
35
- print("Initializing Hugging Face Server on Port 7860...")
36
  uvicorn.run(app, host="0.0.0.0", port=7860)
 
1
  from fastapi import FastAPI
2
  from fastapi.staticfiles import StaticFiles
3
+ from pydantic import BaseModel
4
  import uvicorn
5
  import threading
6
  import time
7
+ import requests
8
+ from datetime import datetime
9
+ import os
10
 
11
  app = FastAPI()
12
 
13
+ # Your API Key from earlier
14
+ API_KEY = "c14e1300-c6d6-4165-8424-8a00c80c1b94"
15
+ URL = f"https://api.cricapi.com/v1/currentMatches?apikey={API_KEY}&offset=0"
16
+
17
+ # Central Python Brain State Memory
18
+ system_state = {
19
+ "live": False, "status": "UPCOMING", "teams": ["Initializing", "Data"],
20
+ "score": "0/0", "overs": "0.0", "venue": "Loading Stadium..."
21
+ }
22
+ prediction_history = []
23
+ last_over = ""
24
 
25
+ def autonomous_backend_scraper():
26
+ global system_state, prediction_history, last_over
27
+ print("AI Backend Brain Engaged. Autonomous Fetching Started...")
28
+
 
 
29
  while True:
30
  try:
31
+ # Backend fetches data. Bypasses all browser CORS limitations!
32
+ res = requests.get(URL, timeout=15)
33
+ data = res.json()
34
+
35
+ if data.get('status') == 'success':
36
+ t20 = [m for m in data.get('data', []) if m.get('matchType') != 'test']
37
+
38
+ live_match = next((m for m in t20 if m.get('matchStarted') and not m.get('matchEnded')), None)
39
+
40
+ if live_match:
41
+ system_state["live"] = True
42
+ system_state["status"] = "LIVE"
43
+ system_state["teams"] = live_match.get('teams', ["Team A", "Team B"])
44
+ system_state["venue"] = live_match.get('venue', "Live Stadium")
45
+
46
+ if live_match.get('score'):
47
+ sc = live_match['score'][-1]
48
+ new_over = str(sc.get('o', '0.0'))
49
+ new_score = f"{sc.get('r', '0')}/{sc.get('w', '0')}"
50
+
51
+ system_state["score"] = new_score
52
+ system_state["overs"] = new_over
53
+
54
+ # History Logic: Save records when balls progress!
55
+ if new_over != last_over and last_over != "":
56
+ prediction_history.append({
57
+ "time": datetime.now().strftime("%H:%M:%S"),
58
+ "match": f"{system_state['teams'][0]} vs {system_state['teams'][1]}",
59
+ "over": new_over,
60
+ "score": new_score,
61
+ "prediction": "Processed successfully"
62
+ })
63
+ # Cap history at 50 to save RAM
64
+ if len(prediction_history) > 50:
65
+ prediction_history.pop(0)
66
+
67
+ last_over = new_over
68
+
69
+ else:
70
+ # No live matches. Find the immediate upcoming one.
71
+ upc = next((m for m in t20 if not m.get('matchStarted')), None)
72
+ if upc:
73
+ system_state["live"] = False
74
+ system_state["status"] = "UPCOMING"
75
+ system_state["teams"] = upc.get('teams', ["Team A", "Team B"])
76
+ system_state["venue"] = upc.get('venue', "Upcoming Venue")
77
+
78
  except Exception as e:
79
+ print("Python Server Network Error:", e)
80
 
81
+ # Cooldown timer to not abuse the API limits
82
+ time.sleep(15)
83
+
84
+ # Start the Ghost Thread
85
+ threading.Thread(target=autonomous_backend_scraper, daemon=True).start()
86
+
87
+ # API Endpoints mapped directly to the UI
88
+ @app.get("/api/state")
89
+ def get_state():
90
+ return system_state
91
+
92
+ @app.get("/api/history")
93
+ def get_history():
94
+ return prediction_history
95
 
96
+ # Serve the beautiful frontend Website lastly
97
+ app.mount("/", StaticFiles(directory=".", html=True), name="frontend")
98
 
99
  if __name__ == "__main__":
 
 
100
  uvicorn.run(app, host="0.0.0.0", port=7860)
style.css CHANGED
@@ -65,6 +65,23 @@ body {
65
  color: var(--accent-cyan);
66
  }
67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  /* Dashboard Layout */
69
  .dashboard {
70
  padding: 2rem 3rem;
 
65
  color: var(--accent-cyan);
66
  }
67
 
68
+ .refresh-btn {
69
+ background: transparent;
70
+ color: var(--accent-green);
71
+ border: 1px solid var(--accent-green);
72
+ border-radius: 20px;
73
+ padding: 0.4rem 1rem;
74
+ cursor: pointer;
75
+ font-weight: 600;
76
+ font-family: 'Outfit', sans-serif;
77
+ transition: all 0.3s;
78
+ }
79
+
80
+ .refresh-btn:hover {
81
+ background: var(--accent-green);
82
+ color: var(--bg-dark);
83
+ }
84
+
85
  /* Dashboard Layout */
86
  .dashboard {
87
  padding: 2rem 3rem;