DKethan commited on
Commit
329c48a
Β·
verified Β·
1 Parent(s): 97e2a3c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +116 -88
app.py CHANGED
@@ -3,28 +3,47 @@ from streamlit_autorefresh import st_autorefresh
3
  import requests
4
  from bs4 import BeautifulSoup
5
  from datetime import datetime
6
- import pandas as pd
7
 
8
- # πŸ”§ Page config must be first
9
- st.set_page_config(page_title="IPL Score Stream", layout="centered")
10
 
11
- # πŸ”„ Auto-refresh every 5 seconds
12
- st_autorefresh(interval=5000, limit=None, key="ipl_autorefresh")
 
 
 
 
 
13
 
 
14
  BASE_URL = "https://www.cricbuzz.com"
15
- current_year = datetime.now().year
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
- # -------------------- LIVE IPL FUNCTION --------------------
18
  def fetch_live_ipl_matches():
19
  url = f"{BASE_URL}/cricket-match/live-scores"
20
  headers = {"User-Agent": "Mozilla/5.0"}
21
- response = requests.get(url, headers=headers)
22
- soup = BeautifulSoup(response.text, "html.parser")
23
 
24
  live_matches = []
25
- match_sections = soup.find_all("div", class_="cb-col cb-col-100 cb-plyr-tbody cb-rank-hdr cb-lv-main")
26
-
27
- for section in match_sections:
28
  header = section.find("h2", class_="cb-lv-grn-strip")
29
  if not header or not header.find("span", class_="cb-plus-ico cb-ico-live-stream"):
30
  continue
@@ -34,85 +53,94 @@ def fetch_live_ipl_matches():
34
  title_tag = block.find("h3", class_="cb-lv-scr-mtch-hdr")
35
  match_title = title_tag.get_text(strip=True).rstrip(',') if title_tag else "N/A"
36
 
37
- team1_block = block.find("div", class_="cb-hmscg-bwl-txt")
38
- team1_score = team1_block.find_all("div", class_="cb-ovr-flo")[1].text.strip() if team1_block else "N/A"
39
 
40
- team2_block = block.find("div", class_="cb-hmscg-bat-txt")
41
- team2_score = team2_block.find_all("div", class_="cb-ovr-flo")[1].text.strip() if team2_block else "N/A"
42
 
43
  status_tag = block.find("div", class_="cb-text-live")
44
- match_status = status_tag.text.strip() if status_tag else "Live match ongoing"
45
-
46
- live_matches.append({
47
- "Match Title": match_title,
48
- "Batting Score": team2_score,
49
- "Bowling Score": team1_score,
50
- "Status": match_status
51
- })
52
-
53
  return live_matches
54
 
55
- # -------------------- RECENT RESULTS --------------------
56
- def get_recent_results():
57
- try:
58
- url = f"{BASE_URL}/cricket-series/9237/Indian-Premier-League-{current_year}/matches"
59
- headers = {"User-Agent": "Mozilla/5.0"}
60
- response = requests.get(url, headers=headers)
61
- soup = BeautifulSoup(response.text, "html.parser")
62
- all_tags = soup.find_all("a", href=True)
63
-
64
- results, seen = [], set()
65
- for i in range(len(all_tags) - 1):
66
- tag, next_tag = all_tags[i], all_tags[i + 1]
67
- href, title, result = tag['href'], tag.get_text().strip(), next_tag.get_text().strip()
68
-
69
- if "cricket-scores" in href:
70
- match_id = f"{title}-{result}"
71
- if match_id in seen:
72
- continue
73
- seen.add(match_id)
74
- results.append(f"{title} – {result}")
75
-
76
- return results[:10]
77
- except:
78
- return ["Error loading past matches."]
79
-
80
- # -------------------- UI --------------------
81
- st.title("🏏 IPL Score Stream")
82
- st.markdown("---")
83
-
84
- # πŸ”΄ LIVE MATCHES
85
- live_scores = fetch_live_ipl_matches()
86
- st.subheader("🟒 Live Matches")
87
- if live_scores:
88
- for match in live_scores:
89
- st.markdown(f"#### πŸ”₯ {match['Match Title']}")
90
- st.markdown(f"🏏 **Batting Side**: {match['Batting Score']}")
91
- st.markdown(f"🎯 **Bowling Side**: {match['Bowling Score']}")
92
- st.markdown(f"πŸ“£ **Status**: {match['Status']}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
  st.markdown("---")
94
- else:
95
- st.warning("❌ No live IPL matches currently.")
96
-
97
- # πŸ“Š LAST 2 MATCHES TABLE
98
- if live_scores:
99
- st.subheader("🧾 Match Summary")
100
- df = pd.DataFrame(live_scores[:2])
101
- df.index += 1
102
- st.table(df)
103
- st.markdown("---")
104
-
105
- # πŸ“‹ RECENT RESULTS
106
- recent_results = get_recent_results()
107
- if recent_results:
108
- won_matches = [r for r in recent_results if "won" in r.lower()]
109
- st.subheader("βœ… Won Matches")
110
- for result in won_matches:
111
- st.markdown(f"- {result}")
112
- st.markdown("---")
113
-
114
- st.subheader("πŸ“‹ All Recent Results")
115
- for result in recent_results:
116
- st.markdown(f"- {result}")
117
- else:
118
- st.warning("❌ No recent results found.")
 
3
  import requests
4
  from bs4 import BeautifulSoup
5
  from datetime import datetime
 
6
 
7
+ # Dynamically get the current year
8
+ CURRENT_YEAR = datetime.now().year
9
 
10
+ # Define the unique code for the year (e.g., 2025 -> 9237)
11
+ YEAR_CODE_MAPPING = {
12
+ 2025: "9237",
13
+ }
14
+
15
+ # Get the unique code for the current year
16
+ YEAR_CODE = YEAR_CODE_MAPPING.get(CURRENT_YEAR, "default_code")
17
 
18
+ # Construct URLs
19
  BASE_URL = "https://www.cricbuzz.com"
20
+ IPL_SERIES_URL = f"{BASE_URL}/cricket-series/{YEAR_CODE}/indian-premier-league-{CURRENT_YEAR}"
21
+ IPL_MATCHES_URL = f"{IPL_SERIES_URL}/matches"
22
+ LIVE_KEYWORDS = ["won the toss", "opt", "elect", "need", "needs", "chose to"]
23
+
24
+ st.markdown("""
25
+ <style>
26
+ .main > div { max-width: 100%; padding-left: 1rem; padding-right: 1rem; }
27
+ </style>
28
+ """, unsafe_allow_html=True)
29
+
30
+ st.markdown(f"""
31
+ <h1 style='text-align: center;'>🏏 IPL Score Stream</h1>
32
+ <p style='text-align: center; font-size: 16px; color: gray;'>
33
+ ⏱️ Last updated: {datetime.now().strftime('%H:%M:%S')}
34
+ </p>
35
+ """, unsafe_allow_html=True)
36
+
37
+ st_autorefresh(interval=5000, limit=None, key="ipl_autorefresh")
38
 
 
39
  def fetch_live_ipl_matches():
40
  url = f"{BASE_URL}/cricket-match/live-scores"
41
  headers = {"User-Agent": "Mozilla/5.0"}
42
+ soup = BeautifulSoup(requests.get(url, headers=headers).text, "html.parser")
 
43
 
44
  live_matches = []
45
+ sections = soup.find_all("div", class_="cb-col cb-col-100 cb-plyr-tbody cb-rank-hdr cb-lv-main")
46
+ for section in sections:
 
47
  header = section.find("h2", class_="cb-lv-grn-strip")
48
  if not header or not header.find("span", class_="cb-plus-ico cb-ico-live-stream"):
49
  continue
 
53
  title_tag = block.find("h3", class_="cb-lv-scr-mtch-hdr")
54
  match_title = title_tag.get_text(strip=True).rstrip(',') if title_tag else "N/A"
55
 
56
+ team1 = block.find("div", class_="cb-hmscg-bwl-txt")
57
+ score1 = team1.find_all("div", class_="cb-ovr-flo")[1].text.strip() if team1 else "N/A"
58
 
59
+ team2 = block.find("div", class_="cb-hmscg-bat-txt")
60
+ score2 = team2.find_all("div", class_="cb-ovr-flo")[1].text.strip() if team2 else "N/A"
61
 
62
  status_tag = block.find("div", class_="cb-text-live")
63
+ status = status_tag.text.strip() if status_tag else ""
64
+
65
+ if any(k in status.lower() for k in LIVE_KEYWORDS):
66
+ live_matches.append({
67
+ "Match Title": match_title,
68
+ "Batting Score": score2,
69
+ "Bowling Score": score1,
70
+ "Status": status
71
+ })
72
  return live_matches
73
 
74
+ def get_recent_news():
75
+ headers = {"User-Agent": "Mozilla/5.0"}
76
+ soup = BeautifulSoup(requests.get(IPL_SERIES_URL, headers=headers).text, "html.parser")
77
+ tags = soup.find_all("a", class_="cb-nws-hdln-ancr")
78
+ return [(tag.text.strip(), BASE_URL + tag["href"]) for tag in tags[:10]]
79
+
80
+ def get_recent_match_results():
81
+ headers = {"User-Agent": "Mozilla/5.0"}
82
+ soup = BeautifulSoup(requests.get(IPL_MATCHES_URL, headers=headers).text, "html.parser")
83
+ result_blocks = soup.find_all("a", href=True)
84
+
85
+ results = []
86
+ for tag in result_blocks:
87
+ if "won by" in tag.text.lower():
88
+ desc = tag.text.strip()
89
+ link = BASE_URL + tag["href"]
90
+ parent = tag.find_parent("div", class_="cb-col-100 cb-col")
91
+ date_tag = parent.find("div", class_="schedule-date") if parent else None
92
+ date = date_tag.text.strip() if date_tag else "β€”"
93
+ results.append((date, desc, link))
94
+
95
+ return results[-5:][::-1] if results else []
96
+
97
+ def get_upcoming_matches():
98
+ headers = {"User-Agent": "Mozilla/5.0"}
99
+ soup = BeautifulSoup(requests.get(IPL_MATCHES_URL, headers=headers).text, "html.parser")
100
+ matches = []
101
+
102
+ for block in soup.select("div.cb-series-matches"):
103
+ title_tag = block.select_one("a.text-hvr-underline")
104
+ venue_tag = block.select_one("div.text-gray")
105
+ time_tag = block.select_one("a.cb-text-upcoming")
106
+
107
+ if title_tag and venue_tag and time_tag:
108
+ title = title_tag.text.strip()
109
+ venue = venue_tag.text.strip()
110
+ start = time_tag.text.strip()
111
+ link = BASE_URL + title_tag["href"]
112
+ matches.append(f"- [{title} at {venue}]({link})")
113
+
114
+ return matches[:5]
115
+
116
+ def left_panel():
117
+ st.subheader("🟒 Live Matches")
118
+ matches = fetch_live_ipl_matches()
119
+ if matches:
120
+ for match in matches:
121
+ st.markdown(f"#### πŸ”₯ {match['Match Title']}")
122
+ st.markdown(f"🏏 **Batting Side**: {match['Batting Score']}")
123
+ st.markdown(f"🎯 **Bowling Side**: {match['Bowling Score']}")
124
+ st.markdown(f"πŸ“£ **Status**: {match['Status']}")
125
+ st.markdown("---")
126
+ else:
127
+ st.warning("❌ No live IPL matches currently.")
128
  st.markdown("---")
129
+
130
+ st.subheader("πŸ“° Latest IPL News")
131
+ for title, link in get_recent_news():
132
+ st.markdown(f"- [{title}]({link})")
133
+
134
+ def right_panel():
135
+ st.subheader("πŸ“… Recent Match Results")
136
+ for _, desc, link in get_recent_match_results():
137
+ st.markdown(f"- [{desc}]({link})")
138
+
139
+ st.divider()
140
+ st.subheader("πŸ—“οΈ Upcoming Matches")
141
+ for line in get_upcoming_matches():
142
+ st.markdown(line)
143
+
144
+ left_col, right_col = st.columns([5, 5])
145
+ with left_col: left_panel()
146
+ with right_col: right_panel()