import os import sqlite3 import datetime import flask import re def is_youtube_id(video_id): """Check if the video_id is a valid YouTube ID""" return re.match(r'^[a-zA-Z0-9_-]{11}$', str(video_id)) is not None def read_music_database(): conn = sqlite3.connect("assets/localwrapped/music.db") c = conn.cursor() c.execute('SELECT * FROM music') music_list = c.fetchall() conn.close() return music_list def read_count_database(year: int): db_path = f'assets/localwrapped/count-{year}.db' if year != datetime.datetime.now().year else 'assets/localwrapped/count.db' if not os.path.exists(db_path): return [] conn = sqlite3.connect(db_path) c = conn.cursor() c.execute('SELECT * FROM count') count_list = c.fetchall() conn.close() return count_list def get_available_years(): years = [] for file in os.listdir('assets/localwrapped'): if file.startswith('count') and file.endswith('.db'): year = file.split('-')[-1].split('.')[0] if year.isdigit(): years.append(int(year)) return sorted(years, reverse=True) def total_play_time(year: int): total_time = 0 music_data = {row[0]: row for row in read_music_database()} for count_entry in read_count_database(year): if count_entry[0] in music_data: total_time += float(music_data[count_entry[0]][7]) * count_entry[1] return total_time def generatehtmlcode(year: int = datetime.datetime.now().year): available_years = get_available_years() current_year = datetime.datetime.now().year selected_year = year if year in available_years else current_year html = ''' Halhadus' Local Wrapped

🎵 Halhadus' Local Wrapped

← Main Page
📁 Source Codes
{% for y in available_years %} {{ y }} {% endfor %}

📊 Statistics for {{ selected_year }}

⏳ Total Play Time: {{ total_time }} minutes

🕒 Last Updated: {{ last_updated }}

🎶 Most Played Tracks

{% for music in top_tracks %}
{% if is_youtube_id(music.video_id) %} {{ music.name }} cover {% else %}
No thumbnail available
{% endif %}

{{ music.name }}

▶ Played {{ music.count }} times

{% if is_youtube_id(music.video_id) %} YouTube YT Music {% else %} Play Source {% endif %}
{% endfor %}
''' # Prepare data music_data = {row[0]: row for row in read_music_database()} count_data = read_count_database(selected_year) top_tracks = [] for count_entry in count_data: if count_entry[0] in music_data: video_id = music_data[count_entry[0]][1] top_tracks.append({ 'name': count_entry[0], 'count': count_entry[1], 'video_id': video_id }) top_tracks.sort(key=lambda x: x['count'], reverse=True) total_time = int(total_play_time(selected_year) / 60) db_path = f'assets/localwrapped/count-{selected_year}.db' if selected_year != current_year else 'assets/localwrapped/count.db' last_updated = datetime.datetime.utcfromtimestamp(os.path.getmtime(db_path)).strftime('%Y-%m-%d %H:%M UTC') return flask.render_template_string( html, top_tracks=top_tracks, total_time=total_time, last_updated=last_updated, available_years=available_years, selected_year=selected_year, is_youtube_id=is_youtube_id )