refactor: changes entire project structure
This commit is contained in:
0
app/scoreboard/__init__.py
Normal file
0
app/scoreboard/__init__.py
Normal file
34
app/scoreboard/get_data.py
Normal file
34
app/scoreboard/get_data.py
Normal file
@@ -0,0 +1,34 @@
|
||||
import requests
|
||||
from datetime import datetime
|
||||
import json
|
||||
|
||||
SCOREBOARD_DATA_FILE = 'scoreboard_data.json'
|
||||
|
||||
def get_scoreboard_data():
|
||||
now = datetime.now()
|
||||
start_time_evening = now.replace(hour=23, minute=0, second=0, microsecond=0) # 7:00 PM EST
|
||||
end_time_evening = now.replace(hour=8, minute=0, second=0, microsecond=0) # 3:00 AM EST
|
||||
|
||||
if now >= start_time_evening or now < end_time_evening:
|
||||
# Use now URL
|
||||
nhle_api_url = "https://api-web.nhle.com/v1/score/now"
|
||||
|
||||
else:
|
||||
# Use current data URL
|
||||
nhle_api_url = f"https://api-web.nhle.com/v1/score/{now.strftime('%Y-%m-%d')}"
|
||||
|
||||
response = requests.get(nhle_api_url)
|
||||
if response.status_code == 200:
|
||||
return response.json()
|
||||
else:
|
||||
print("Error:", response.status_code)
|
||||
|
||||
# Store scoreboard data locally
|
||||
def store_scoreboard_data():
|
||||
scoreboard_data = get_scoreboard_data()
|
||||
if scoreboard_data:
|
||||
with open(SCOREBOARD_DATA_FILE, 'w') as json_file:
|
||||
json.dump(scoreboard_data, json_file)
|
||||
return scoreboard_data
|
||||
else:
|
||||
return None
|
||||
139
app/scoreboard/process_data.py
Normal file
139
app/scoreboard/process_data.py
Normal file
@@ -0,0 +1,139 @@
|
||||
import sqlite3
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
def extract_game_info(scoreboard_data):
|
||||
if not scoreboard_data:
|
||||
return []
|
||||
|
||||
extracted_info = []
|
||||
for game in scoreboard_data.get("games", []):
|
||||
extracted_info.append({
|
||||
"Home Team": game["homeTeam"]["name"]["default"],
|
||||
"Home Score": game["homeTeam"]["score"],
|
||||
"Away Team": game["awayTeam"]["name"]["default"],
|
||||
"Away Score": game["awayTeam"]["score"],
|
||||
"Home Logo": game["homeTeam"]["logo"],
|
||||
"Away Logo": game["awayTeam"]["logo"],
|
||||
"Game State": convert_game_state(game["gameState"]),
|
||||
"Period": process_period(game),
|
||||
"Time Remaining": process_time_remaining(game),
|
||||
"Time Running": game["clock"]["running"],
|
||||
"Intermission": game["clock"]["inIntermission"],
|
||||
"Priority": calculate_game_priority(game),
|
||||
"Start Time": process_start_time(game),
|
||||
"Home Record": game["homeTeam"]["record"] if game["gameState"] in ["PRE", "FUT"] else "N/A",
|
||||
"Away Record": game["awayTeam"]["record"] if game["gameState"] in ["PRE", "FUT"] else "N/A",
|
||||
"Home Shots": game["homeTeam"]["sog"] if game["gameState"] not in ["PRE", "FUT"] else 0,
|
||||
"Away Shots": game["awayTeam"]["sog"] if game["gameState"] not in ["PRE", "FUT"] else 0,
|
||||
"Home Power Play": get_power_play_info(game, game["homeTeam"]["name"]["default"]),
|
||||
"Away Power Play": get_power_play_info(game, game["awayTeam"]["name"]["default"]),
|
||||
"Last Period Type": get_game_outcome(game)
|
||||
})
|
||||
|
||||
# Sort games based on priority
|
||||
return sorted(extracted_info, key=lambda x: x["Priority"], reverse=True)
|
||||
|
||||
def convert_game_state(game_state):
|
||||
state_mapping = {"OFF": "FINAL", "CRIT": "LIVE", "FUT": "PRE"}
|
||||
return state_mapping.get(game_state, game_state)
|
||||
|
||||
def process_period(game):
|
||||
if game["gameState"] in ["PRE", "FUT"]:
|
||||
return 0
|
||||
elif game["gameState"] in ["FINAL", "OFF"]:
|
||||
return "N/A"
|
||||
else:
|
||||
return game["periodDescriptor"]["number"]
|
||||
|
||||
def process_time_remaining(game):
|
||||
if game["gameState"] in ["PRE", "FUT"]:
|
||||
return "20:00"
|
||||
elif game["gameState"] in ["FINAL", "OFF"]:
|
||||
return "00:00"
|
||||
else:
|
||||
time_remaining = game["clock"]["timeRemaining"]
|
||||
return "END" if time_remaining == "00:00" else time_remaining
|
||||
|
||||
def process_start_time(game):
|
||||
if game["gameState"] in ["PRE", "FUT"]:
|
||||
utc_time = game["startTimeUTC"]
|
||||
return utc_to_est_time(utc_time)
|
||||
else:
|
||||
return "N/A"
|
||||
|
||||
def get_power_play_info(game, team_name):
|
||||
if "situation" in game and "situationDescriptions" in game["situation"]:
|
||||
for situation in game["situation"]["situationDescriptions"]:
|
||||
if situation == "PP" and game["awayTeam"]["name"]["default"] == team_name:
|
||||
return f"PP {game['situation']['timeRemaining']}"
|
||||
elif situation == "PP" and game["homeTeam"]["name"]["default"] == team_name:
|
||||
return f"PP {game['situation']['timeRemaining']}"
|
||||
return ""
|
||||
|
||||
def get_game_outcome(game):
|
||||
return game["gameOutcome"]["lastPeriodType"] if game["gameState"] == "FINAL" else "N/A"
|
||||
|
||||
def calculate_game_priority(game):
|
||||
# Return 0 if game is in certain states
|
||||
if game["gameState"] in ["FINAL", "OFF", "PRE", "FUT"] or game["clock"]["inIntermission"]:
|
||||
return 0
|
||||
|
||||
# Get standings for home and away teams
|
||||
home_team_standings = get_team_standings(game["homeTeam"]["name"]["default"])
|
||||
away_team_standings = get_team_standings(game["awayTeam"]["name"]["default"])
|
||||
|
||||
# Calculate total values of leagueSequence + leagueL10Sequence for each team
|
||||
home_total = home_team_standings["league_sequence"] + home_team_standings["league_l10_sequence"]
|
||||
away_total = away_team_standings["league_sequence"] + away_team_standings["league_l10_sequence"]
|
||||
|
||||
# Calculate the matchup adjustment factor
|
||||
matchup_adjustment = home_total + away_total
|
||||
|
||||
# Get period, time remaining, scores, and other relevant data
|
||||
period = game.get("periodDescriptor", {}).get("number", 0)
|
||||
time_remaining = game.get("clock", {}).get("secondsRemaining", 0)
|
||||
home_score = game["homeTeam"]["score"]
|
||||
away_score = game["awayTeam"]["score"]
|
||||
score_difference = abs(home_score - away_score)
|
||||
score_total = (home_score + away_score) * 20
|
||||
|
||||
# Calculate the base priority based on period
|
||||
base_priority = {4: 400, 3: 300, 2: 200}.get(period, 100)
|
||||
|
||||
# Adjust base priority based on score difference
|
||||
if score_difference > 3:
|
||||
base_priority -= 500
|
||||
elif score_difference > 2:
|
||||
base_priority -= 350
|
||||
elif score_difference > 1:
|
||||
base_priority -= 100
|
||||
|
||||
# Adjust base priority based on certain conditions
|
||||
if score_difference == 0 and period == 3 and time_remaining <= 600:
|
||||
base_priority += 100
|
||||
|
||||
# Calculate time priority
|
||||
time_priority = (1200 - time_remaining) / 20
|
||||
|
||||
# Calculate the final priority
|
||||
final_priority = int(base_priority + time_priority - matchup_adjustment + score_total)
|
||||
|
||||
return final_priority
|
||||
|
||||
def get_team_standings(team_name):
|
||||
conn = sqlite3.connect("nhl_standings.db")
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("""
|
||||
SELECT league_sequence, league_l10_sequence
|
||||
FROM standings
|
||||
WHERE team_common_name = ?
|
||||
""", (team_name,))
|
||||
result = cursor.fetchone()
|
||||
conn.close()
|
||||
return {"league_sequence": result[0] if result else 0, "league_l10_sequence": result[1] if result else 0}
|
||||
|
||||
def utc_to_est_time(utc_time):
|
||||
utc_datetime = datetime.strptime(utc_time, "%Y-%m-%dT%H:%M:%SZ")
|
||||
est_offset = timedelta(hours=-5)
|
||||
est_datetime = utc_datetime + est_offset
|
||||
return est_datetime.strftime("%I:%M %p")
|
||||
13
app/scoreboard/tasks.py
Normal file
13
app/scoreboard/tasks.py
Normal file
@@ -0,0 +1,13 @@
|
||||
import schedule
|
||||
import time
|
||||
from app.scoreboard.update_nhl_standings_db import update_nhl_standings
|
||||
from app.scoreboard.get_data import store_scoreboard_data
|
||||
|
||||
def schedule_tasks():
|
||||
schedule.every(600).seconds.do(update_nhl_standings)
|
||||
schedule.every(10).seconds.do(store_scoreboard_data)
|
||||
while True:
|
||||
schedule.run_pending()
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
65
app/scoreboard/update_nhl_standings_db.py
Normal file
65
app/scoreboard/update_nhl_standings_db.py
Normal file
@@ -0,0 +1,65 @@
|
||||
import sqlite3
|
||||
import requests
|
||||
|
||||
def create_standings_table(conn):
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("""
|
||||
CREATE TABLE IF NOT EXISTS standings (
|
||||
team_common_name TEXT,
|
||||
league_sequence INTEGER,
|
||||
league_l10_sequence INTEGER
|
||||
)
|
||||
""")
|
||||
conn.commit()
|
||||
|
||||
def truncate_standings_table(conn):
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("DELETE FROM standings")
|
||||
conn.commit()
|
||||
|
||||
def insert_standings_info(conn, standings_info):
|
||||
cursor = conn.cursor()
|
||||
for team in standings_info:
|
||||
cursor.execute("""
|
||||
INSERT INTO standings (team_common_name, league_sequence, league_l10_sequence)
|
||||
VALUES (?, ?, ?)
|
||||
""", (team["team_common_name"], team["league_sequence"], team["league_l10_sequence"]))
|
||||
conn.commit()
|
||||
|
||||
def extract_standings_info():
|
||||
url = "https://api-web.nhle.com/v1/standings/now"
|
||||
response = requests.get(url)
|
||||
if response.status_code == 200:
|
||||
standings_data = response.json()
|
||||
standings_info = []
|
||||
for team in standings_data.get("standings", []):
|
||||
team_info = {
|
||||
"team_common_name": team["teamCommonName"]["default"],
|
||||
"league_sequence": team["leagueSequence"],
|
||||
"league_l10_sequence": team["leagueL10Sequence"]
|
||||
}
|
||||
standings_info.append(team_info)
|
||||
return standings_info
|
||||
else:
|
||||
print("Error:", response.status_code)
|
||||
return None
|
||||
|
||||
def update_nhl_standings():
|
||||
# Connect to SQLite database
|
||||
conn = sqlite3.connect("nhl_standings.db")
|
||||
|
||||
# Create standings table if it doesn't exist
|
||||
create_standings_table(conn)
|
||||
|
||||
# Truncate standings table before inserting new data
|
||||
truncate_standings_table(conn)
|
||||
|
||||
# Extract standings info
|
||||
standings_info = extract_standings_info()
|
||||
|
||||
# Insert standings info into the database
|
||||
if standings_info:
|
||||
insert_standings_info(conn, standings_info)
|
||||
|
||||
# Close database connection
|
||||
conn.close()
|
||||
Reference in New Issue
Block a user