Add song_kissFM.py
This commit is contained in:
parent
e58359e939
commit
c4013c7095
102
song_kissFM.py
Normal file
102
song_kissFM.py
Normal file
@ -0,0 +1,102 @@
|
||||
import requests
|
||||
from bs4 import BeautifulSoup
|
||||
from datetime import datetime, timedelta
|
||||
import base64
|
||||
import argparse
|
||||
import random
|
||||
|
||||
# URL de l'emissora amb entropia per evitar la memòria cau
|
||||
BASE_URL = "https://emisora.org.es/kiss-fm/"
|
||||
URL_WITH_ENTROPY = f"{BASE_URL}?rand={random.randint(0, 100000)}"
|
||||
|
||||
# Fitxers de sortida
|
||||
CURRENT_FILE = "/home/max/current_playlist.md"
|
||||
SUMMARY_FILE_TEMPLATE = "/home/max/DIA_analitzat_{date}.md"
|
||||
|
||||
# Inicialitza un fitxer Markdown amb capçalera
|
||||
def init_markdown(file, headers):
|
||||
with open(file, "w") as f:
|
||||
f.write(headers)
|
||||
|
||||
# Afegeix una fila a un fitxer Markdown
|
||||
def append_to_markdown(file, data):
|
||||
with open(file, "a") as f:
|
||||
f.write(data)
|
||||
|
||||
# Llegeix l'última línia d'un fitxer
|
||||
def get_last_line(file):
|
||||
try:
|
||||
with open(file, "r") as f:
|
||||
lines = f.readlines()
|
||||
return lines[-1] if lines else None
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
|
||||
# Procésa el darrer element `li` de `data-playlist-previous-songs`
|
||||
def fetch_last_playlist_song():
|
||||
headers = {
|
||||
'Cache-Control': 'no-cache',
|
||||
'Pragma': 'no-cache',
|
||||
'User-Agent': 'Mozilla/5.0 (Windows NT 5.1; rv:40.0) Gecko/20100101 Firefox/40.0'
|
||||
}
|
||||
|
||||
response = requests.get(URL_WITH_ENTROPY, headers=headers)
|
||||
if response.status_code == 200:
|
||||
soup = BeautifulSoup(response.content, 'html.parser')
|
||||
last_li = soup.select_one('ul[data-playlist-previous-songs] li:last-child')
|
||||
if last_li:
|
||||
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
title = last_li.get('title', 'N/A')
|
||||
artist = last_li.find('span', class_='playlist__artist-name').text
|
||||
song = last_li.find('span', class_='playlist__song-name').text
|
||||
img_tag = last_li.find('img')
|
||||
img_src = img_tag['src'] if img_tag else ''
|
||||
|
||||
# Obtenim les dades de la imatge i les convertim en base64
|
||||
if img_src:
|
||||
img_response = requests.get(img_src)
|
||||
if img_response.status_code == 200:
|
||||
img_data = base64.b64encode(img_response.content).decode('utf-8')
|
||||
img_md = f""
|
||||
else:
|
||||
img_md = "No disponible"
|
||||
else:
|
||||
img_md = "No disponible"
|
||||
|
||||
# Prepara les dades en format Markdown
|
||||
new_entry = f"| {timestamp} | {title} | {artist} | {song} | {img_md} |\n"
|
||||
|
||||
# Compara amb l'última línia no temporal
|
||||
last_entry = get_last_line(CURRENT_FILE)
|
||||
if not last_entry or last_entry.split('|')[2:] != new_entry.split('|')[2:]:
|
||||
append_to_markdown(CURRENT_FILE, new_entry)
|
||||
|
||||
# Genera un resum diari de la música detectada
|
||||
def generate_daily_summary():
|
||||
yesterday = (datetime.now() - timedelta(days=1)).strftime("%Y-%m-%d")
|
||||
summary_file = SUMMARY_FILE_TEMPLATE.format(date=yesterday)
|
||||
init_markdown(summary_file, f"# Resum del dia {yesterday}\n\n| Temps | Títol | Artista | Nom Cançó | Imatge |\n|-------|-------|---------|-----------|--------|\n")
|
||||
|
||||
# Agrupa informació de `current_playlist.md`
|
||||
try:
|
||||
with open(CURRENT_FILE, "r") as current:
|
||||
lines = current.readlines()
|
||||
for line in lines:
|
||||
if yesterday in line:
|
||||
append_to_markdown(summary_file, line)
|
||||
except FileNotFoundError:
|
||||
print(f"No s'ha trobat el fitxer {CURRENT_FILE}.")
|
||||
|
||||
# Analitza els arguments de la línia de comandes
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--resum', action='store_true', help="Generar el resum diari")
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.resum:
|
||||
generate_daily_summary()
|
||||
else:
|
||||
fetch_last_playlist_song()
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
Loading…
Reference in New Issue
Block a user