refactor: changes entire project structure

This commit is contained in:
2024-02-19 01:05:33 -05:00
parent 3e45c22b59
commit aae9ba4a27
13 changed files with 240 additions and 255 deletions

5
app/__init__.py Normal file
View File

@@ -0,0 +1,5 @@
from flask import Flask
app = Flask(__name__)
from app import routes

32
app/routes.py Normal file
View File

@@ -0,0 +1,32 @@
from app import app
from flask import render_template, jsonify
from app.scoreboard.process_data import extract_game_info
import json
SCOREBOARD_DATA_FILE = 'scoreboard_data.json'
@app.route('/')
def index():
return render_template('index.html')
@app.route('/scoreboard')
def get_scoreboard():
try:
with open(SCOREBOARD_DATA_FILE, 'r') as json_file:
scoreboard_data = json.load(json_file)
except FileNotFoundError:
return jsonify({"error": "Failed to retrieve scoreboard data. File not found."})
except json.JSONDecodeError:
return jsonify({"error": "Failed to retrieve scoreboard data. Invalid JSON format."})
if scoreboard_data:
live_games = [game for game in extract_game_info(scoreboard_data) if game["Game State"] == "LIVE"]
pre_games = [game for game in extract_game_info(scoreboard_data) if game["Game State"] == "PRE"]
final_games = [game for game in extract_game_info(scoreboard_data) if game["Game State"] == "FINAL"]
return jsonify({
"live_games": live_games,
"pre_games": pre_games,
"final_games": final_games
})
else:
return jsonify({"error": "Failed to retrieve scoreboard data"})

View File

View 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

View 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
View 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)

View 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()

166
app/static/script.js Normal file
View File

@@ -0,0 +1,166 @@
// Function to fetch scoreboard data using AJAX
function fetchScoreboardData() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "/scoreboard", true);
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
updateScoreboard(JSON.parse(xhr.responseText));
} else {
console.error("Failed to fetch scoreboard data.");
}
}
};
xhr.send();
}
// Function to update scoreboard with fetched data
function updateScoreboard(data) {
var liveGamesSection = document.getElementById("live-games-section");
var preGamesSection = document.getElementById('pre-games-section');
var finalGamesSection = document.getElementById('final-games-section');
if (liveGamesSection) {
var liveGamesExist = data && data.live_games && data.live_games.length > 0;
if (liveGamesExist) {
document.getElementById('live-games').innerText = "Live Games"
liveGamesSection.innerHTML = generateGameBoxes(data.live_games, 'LIVE');
}
}
if (preGamesSection) {
var preGamesExist = data && data.pre_games && data.pre_games.length > 0;
if (preGamesExist) {
document.getElementById('on-later').innerText = "On Later"
preGamesSection.innerHTML = generateGameBoxes(data.pre_games, 'PRE');
}
}
if (finalGamesSection) {
var finalGamesExist = data && data.final_games && data.final_games.length > 0;
if (finalGamesExist) {
document.getElementById('game-over').innerText = "Game Over"
finalGamesSection.innerHTML = generateGameBoxes(data.final_games, 'FINAL');
}
}
}
// Function to generate HTML for game boxes
function generateGameBoxes(games, state) {
var html = '';
games.forEach(function(game) {
if (game['Game State'] === state) {
html += '<div class="game-box">';
if (state === 'LIVE') {
if (game['Time Running']) {
html += '<div class="live-dot"></div>'; // Display the red dot if the game is live
}
html += '<div class="team-info">';
html += '<img src="' + game['Away Logo'] + '" alt="' + game['Away Team'] + ' Logo" class="team-logo">';
html += '<div class="team-info-column">';
html += '<span class="team-name">' + game['Away Team'] + '</span>';
html += '<span class="team-sog">SOG: ' + game['Away Shots'] + '</span>';
html += '<span class="team-power-play">' + game['Away Power Play'] + '</span>';
html += '</div>';
html += '<span class="team-score">' + game['Away Score'] + '</span>';
html += '</div>';
html += '<div class="team-info">';
html += '<img src="' + game['Home Logo'] + '" alt="' + game['Home Team'] + ' Logo" class="team-logo">';
html += '<div class="team-info-column">';
html += '<span class="team-name">' + game['Home Team'] + '</span>';
html += '<span class="team-sog">SOG: ' + game['Home Shots'] + '</span>';
html += '<span class="team-power-play">' + game['Home Power Play'] + '</span>';
html += '</div>';
html += '<span class="team-score">' + game['Home Score'] + '</span>';
html += '</div>';
html += '<div class="game-info">';
if (game['Intermission']) {
html += '<div class="live-state-intermission">'
if (game['Period'] == 1 ) {
html += '1st Int';
}
if (game['Period'] == 2 ) {
html += '2nd Int';
}
if (game['Period'] == 3 ) {
html += '3rd Int';
}
html += '</div>';
html += '<div class="live-time-intermission">' + game['Time Remaining'] + '</div>';
} else {
html += '<div class="live-state">';
if (game['Period'] == 1 ) {
html += '1st';
}
else if (game['Period'] == 2 ) {
html += '2nd';
}
else if (game['Period'] == 3 ) {
html += '3rd';
}
else {
html += 'OT';
}
html += '</div>';
html += '<div class="live-time">' + game['Time Remaining'] + '</div>';
}
html += '</div>';
html += '<div class="game-info">';
html += '<strong>Game Score: </strong>' + game['Priority'];
html += '</div>';
html += '</div>';
} else if (state === 'PRE') {
html += '<div class="pre-state">' + game['Start Time'] + '</div>';
html += '<div class="team-info">';
html += '<img src="' + game['Away Logo'] + '" alt="' + game['Away Team'] + ' Logo" class="team-logo">';
html += '<span class="team-name">' + game['Away Team'] + '</span>';
html += '<span class="team-record">' + game['Away Record'] + '</span>';
html += '</div>';
html += '<div class="team-info">';
html += '<img src="' + game['Home Logo'] + '" alt="' + game['Home Team'] + ' Logo" class="team-logo">';
html += '<span class="team-name">' + game['Home Team'] + '</span>';
html += '<span class="team-record">' + game['Home Record'] + '</span>';
html += '</div>';
} else if (state === 'FINAL') {
html += '<div class="final-state">';
if (game['Last Period Type'] === 'REG') {
html += 'FINAL';
} else if (game['Last Period Type'] === 'OT') {
html += 'FINAL/OT';
} else {
html += 'FINAL/SO';
}
html += '</div>';
html += '<div class="team-info">';
html += '<img src="' + game['Away Logo'] + '" alt="' + game['Away Team'] + ' Logo" class="team-logo">';
html += '<div class="team-info-column">';
html += '<span class="team-name">' + game['Away Team'] + '</span>';
html += '<span class="team-sog">SOG: ' + game['Away Shots'] + '</span>';
html += '</div>';
html += '<span class="team-score">' + game['Away Score'] + '</span>';
html += '</div>';
html += '<div class="team-info">';
html += '<img src="' + game['Home Logo'] + '" alt="' + game['Home Team'] + ' Logo" class="team-logo">';
html += '<div class="team-info-column">';
html += '<span class="team-name">' + game['Home Team'] + '</span>';
html += '<span class="team-sog">SOG: ' + game['Home Shots'] + '</span>';
html += '</div>';
html += '<span class="team-score">' + game['Home Score'] + '</span>';
html += '</div>';
}
html += '</div>';
}
});
return html;
}
// Function to reload the scoreboard every 20 seconds
function autoRefresh() {
fetchScoreboardData();
setTimeout(autoRefresh, 5000); // 20 seconds
}
// Call the autoRefresh function when the page loads
window.onload = function() {
autoRefresh();
};

244
app/static/styles.css Normal file
View File

@@ -0,0 +1,244 @@
body {
background-color: #121212; /* Dark background color */
font-family: Arial, sans-serif; /* Use a common sans-serif font */
color: #fff; /* White text color */
}
h1 {
text-align: center;
margin-top: 20px;
color: #f2f2f2; /* Lighten the text color */
}
.scoreboard {
display: flex;
flex-wrap: wrap;
justify-content: space-around;
margin-top: 20px;
}
.game-box {
background-color: #333; /* Dark background color for game boxes */
border-radius: 12px; /* Rounded corners */
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* Add a subtle shadow */
padding: 20px;
margin-bottom: 20px;
margin-left: 20px;
margin-right: 20px;
width: 300px;
position: relative; /* Position relative for absolute positioning */
}
.team-info {
display: flex;
align-items: center;
margin-bottom: 7px;
margin-top: 25px; /* Added margin-top */
}
.team-info-column {
display: flex;
flex-direction: column;
}
.team-logo {
width: 50px;
height: auto;
margin-right: 10px;
}
.team-name {
font-size: 18px;
font-weight: bold;
}
.team-score {
font-size: 25px;
font-weight: bold;
margin-left: auto;
}
.team-record {
font-size: 12px;
margin-left: auto;
font-weight: bold;
}
.team-sog {
font-size: 12px; /* Adjust font size as needed */
color: #ddd; /* Lighter text color */
}
.team-power-play {
font-size: 12px; /* Adjust font size as needed */
color: red; /* Set color to red */
margin-left: 10px; /* Add some margin for spacing */
}
.game-info {
margin-top: 12px;
color: #aaa; /* Lighten the text color */
text-align: center;
font-size: 14px;
}
.game-info strong {
margin-right: 5px;
}
.live-dot {
position: absolute;
top: 5px;
right: 5px;
width: 10px;
height: 10px;
background-color: red;
border-radius: 50%;
}
.pre-state {
position: absolute;
top: 10px;
left: 10px; /* Adjusted left position */
background-color: #444; /* Darker background color for pre state */
padding: 5px;
border-radius: 5px;
font-size: 12px;
color: #fff; /* White text color for live state */
font-weight: bolder; /* Bold text for live state */
z-index: 1; /* Ensure the live state box is above other content */
}
.final-state {
position: absolute;
top: 10px;
left: 10px; /* Adjusted left position */
background-color: #444; /* Darker background color for final state */
padding: 5px;
border-radius: 5px;
font-size: 12px;
color: #ddd; /* Lighter text color for final state */
z-index: 1; /* Ensure the final state box is above other content */
font-weight: bold;
}
.live-state {
position: absolute;
top: 10px;
left: 10px; /* Adjusted left position */
background-color: #0b6e31; /* Darker green background color for live state */
padding: 5px;
border-radius: 5px;
font-size: 12px;
color: #fff; /* White text color for live state */
font-weight: bolder; /* Bold text for live state */
z-index: 1; /* Ensure the live state box is above other content */
}
.live-state-intermission {
position: absolute;
top: 10px;
left: 10px; /* Adjusted left position */
background-color: #444; /* Darker green background color for live state */
padding: 5px;
border-radius: 5px;
font-size: 12px;
color: #fff; /* White text color for live state */
font-weight: bolder; /* Bold text for live state */
z-index: 1; /* Ensure the live state box is above other content */
}
.live-time {
position: absolute;
top: 10px;
left: 45px; /* Adjusted left position */
background-color: #444; /* Darker background color for time box */
padding: 5px;
border-radius: 5px;
font-size: 12px;
color: #ddd; /* Lighter text color for time box */
z-index: 1; /* Ensure the time box is above other content */
}
.live-time-intermission {
position: absolute;
top: 10px;
left: 60px; /* Adjusted left position */
background-color: #444; /* Darker background color for time box */
padding: 5px;
border-radius: 5px;
font-size: 12px;
color: #ddd; /* Lighter text color for time box */
z-index: 1; /* Ensure the time box is above other content */
}
#live-games-section {
display: flex;
align-items: start;
flex-wrap: wrap;
justify-content: flex-start;
margin-top: 20px;
}
#pre-games-section {
display: flex;
align-items: start;
flex-wrap: wrap;
justify-content: flex-start;
margin-top: 20px;
}
#final-games-section {
display: flex;
align-items: start;
flex-wrap: wrap;
justify-content: flex-start;
margin-top: 20px;
}
/* Existing CSS styles */
/* Add media query for smaller screens */
@media only screen and (max-width: 768px) {
.scoreboard {
flex-direction: column; /* Change direction to column for smaller screens */
align-items: center; /* Center align items */
}
.game-box {
width: 90%; /* Adjust width for better fit on smaller screens */
margin: 10px; /* Adjust margins */
}
.team-info {
align-items: center; /* Center align items */
margin-top: 26px; /* Adjust top margin */
margin-bottom: 5px; /* Adjust bottom margin */
}
.team-logo {
width: 36px; /* Adjust logo size */
height: 36px;
}
.team-name {
font-size: 16px; /* Decrease font size for better readability */
font-weight: bold;
}
.team-score {
font-size: 24px; /* Decrease font size for better readability */
font-weight: bold;
}
.game-info {
font-size: 12px; /* Decrease font size for better readability */
}
.live-state,
.live-time,
.pre-state,
.final-state {
font-size: 12px; /* Decrease font size for better readability */
}
}

20
app/templates/index.html Normal file
View File

@@ -0,0 +1,20 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>NHL Scoreboard</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="static\styles.css">
</head>
<body>
<h1 id="live-games"></h1>
<div id="live-games-section"></div>
<h1 id="on-later"></h1>
<div id="pre-games-section"></div>
<h1 id="game-over"></h1>
<div id="final-games-section"></div>
<script src="/static/script.js"></script>
</body>
</html>