Fixing the bug in the conjurer_musician.py file.

Fx

Fix

fx

Fix ?

Revert "Fix"

This reverts commit 4e185f7b34dfede04ed36ab9813bd9d1f7fb8b35.

Adding deploy for music bot
This commit is contained in:
2024-04-17 12:32:54 +01:00
committed by migatu
parent 0375b0a892
commit ca6896ebcf
7 changed files with 229 additions and 100 deletions
+94 -39
View File
@@ -5,19 +5,18 @@ functions for rescanning the music folder, updating the music list, and serving
API endpoints.
"""
import json
import logging
import re
from pathlib import Path
from platform import uname
import threading
import time
from datetime import datetime
from sys import platform
import logging
from flask import Flask, Response, jsonify, request, send_file
from waitress import serve
from logging import handlers
from json.decoder import JSONDecodeError
from pathlib import Path
from platform import uname
from sys import platform
from flask import Flask, jsonify, redirect, request, send_from_directory
from waitress import serve
HOST_ADDRESS = "192.168.1.15"
PORT_ADDRESS = 5000
@@ -30,7 +29,6 @@ if platform in ("linux", "linux2"):
LOGSTORE = "/home/mtuszowski/conjurer/logs/"
ENCODING = "utf-8"
else:
LOGFILE = "/home/pi/Conjurer/discord_mus_service.log"
NETRC_FILE = "/home/pi/.netrc"
@@ -40,17 +38,32 @@ if platform in ("linux", "linux2"):
music_file_list = []
def create_playlist():
"""
Reads a JSON file containing a playlist and writes the playlist items to a text file.
The JSON file path is '/home/pi/Conjurer/playlist.json',
and the text file path is '/home/pi/Conjurer/all_playlist.txt'.
Raises:
JSONDecodeError: If the JSON file cannot be decoded.
"""
with open("/home/pi/Conjurer/playlist.json", "r+", encoding="utf-8") as r_file:
with open("/home/pi/Conjurer/all_playlist.txt", "w", encoding="utf-8") as w_file:
with open(
"/home/pi/Conjurer/all_playlist.txt", "w", encoding="utf-8"
) as w_file:
try:
playlist = json.load(r_file)
for item in playlist:
w_file.write(item)
w_file.write("\n")
except JSONDecodeError:
except json.JSONDecodeError:
pass
def rescan():
"""
The `rescan` function logs a message, scans for mp3 files in a specified folder,
@@ -64,13 +77,12 @@ def rescan():
music_file_list.append(temp_music_file)
with open("/home/pi/Conjurer/playlist.json", "r+", encoding="utf-8") as s_file:
database = music_file_list
#self.app.logger.info("DUMPING DATA")
# self.app.logger.info("DUMPING DATA")
s_file.truncate(0)
s_file.seek(0)
json.dump(database, s_file)
create_playlist()
#TODO: Zobaczyc czy losowo, itp. lepiej po stronie pythona czy po stronei liquidsoapa. Tak samo modyfikowanie playlisty itp. itd.
#TODO: Ale zaczac od odtwarzania playlisty z tego pliku json (moze np. sie format nie zgadzac albo cos)
def thread_rescan():
"""
@@ -79,15 +91,31 @@ def thread_rescan():
"""
logging.info("Starting filesystemupdater")
while True:
time.sleep(60*60*24)
time.sleep(60 * 60 * 24)
logging.info("Rescan triggered")
rescan()
app = Flask(__name__)
#TODO: Parametry ustalające czy dajemy zwrotkę do bota czy do streamera ? W każdej z funkcji?
#TODO: Odpalić wyszukiwarki w wątkach i dopiero po wszystkim zsumować wyszukiwanie.
def wyszukaj(word_list, how_many):
logger = logging.getLogger()
# TODO: Odpalić wyszukiwarki w wątkach i dopiero po wszystkim zsumować wyszukiwanie.
def wyszukaj(word_list, how_many, _logger=None, return_to_bot=True):
"""
Searches for music files based on a list of keywords and returns a list of matching files.
Args:
word_list (list): A list of keywords to search for.
how_many (int): The maximum number of matching files to return.
Returns:
list: A list of matching files, sorted by their search weight.
"""
if _logger is None:
fun_logger = logging.getLogger()
else:
fun_logger = _logger
return_list = []
search_weight = []
@@ -101,7 +129,7 @@ def wyszukaj(word_list, how_many):
skip_start = 1
for word in word_list[skip_start:]:
token_weight = len(word)
logger.info("Słowo kluczowe: %s", word)
fun_logger.info("Słowo kluczowe: %s", word)
itr = 0
for file in music_file_list:
file = file.split(SEPARATOR_FILE_PATH)
@@ -141,7 +169,7 @@ def wyszukaj(word_list, how_many):
else:
skip = 4
matched_times = 1
#TODO: To do wątków albo for asynchroniczny
# TODO: To do wątków albo for asynchroniczny
for itm in all_words[skip:]:
pingu += 1
pattern = ".*" + word + ".*"
@@ -157,26 +185,40 @@ def wyszukaj(word_list, how_many):
matched_times += 1
itr += 1
logger.info("Stworzylem tablice wag zajęło mi to %s", datetime.now() - time_start)
fun_logger.info(
"Stworzylem tablice wag zajęło mi to %s", datetime.now() - time_start
)
time_start = datetime.now()
item_to_search = max_weight(search_weight)
itr = 0
if item_to_search == 0:
return None
return []
not_found = True
return_list = []
if int(how_many) <= 0:
logger.info("Jeden plik do zagrania")
fun_logger.info("Jeden plik do zagrania")
while not_found:
if search_weight[itr][0] == item_to_search:
return_list.append(search_weight[itr])
return return_list
if not return_to_bot:
with open(
"/home/pi/Conjurer/priority_queue.playlist", "w", encoding="utf-8"
) as s_file:
s_file.write(search_weight[itr][1])
break
itr += 1
else:
logger.info("Wiele plików do zagrania")
fun_logger.info("Wiele plików do zagrania")
search_weight.sort(key=lambda x: x[0], reverse=True)
return_list.extend(search_weight[: int(how_many)])
return return_list
if not return_to_bot:
for item in return_list:
with open(
"/home/pi/Conjurer/priority_queue.playlist", "w", encoding="utf-8"
) as s_file:
s_file.write(item[1])
return return_list
def max_weight(lista):
"""
@@ -205,17 +247,25 @@ def remove_characters(string, character):
"""
return string.replace(character, "")
@app.route("/stream", methods=["GET"])
def stream_music():
def stream_music_hls():
"""
The function `get_music_list` returns a JSON object containing a list of music files.
:return: A JSON response containing a key "music_file_list" with the value of the variable
`music_file_list`.
"""
m3u8 = Path("/tmp/hls/stream.m3u8")
r = Response(m3u8)
r.headers["Content-Type"] = "application/mpegURL"
return r, 200
return send_from_directory("/tmp/hls", "stream.m3u8")
@app.route("/stream_mp3", methods=["GET"])
def stream_music_mp3():
"""
The function `get_music_list` returns a JSON object containing a list of music files.
:return: A JSON response containing a key "music_file_list" with the value of the variable
`music_file_list`.
"""
return redirect("http://www.example.com", code=302)
@app.route("/mp3", methods=["GET"])
@@ -248,6 +298,7 @@ def update_music_list():
)
return return_data
@app.route("/get_music", methods=["POST"])
def look_for_playlist():
"""
@@ -264,7 +315,7 @@ def look_for_playlist():
app.logger.info(record["lista_slow"])
app.logger.info(record["UUID"])
app.logger.info(record["dlugosc_plejlisty"])
return_data = wyszukaj(record["lista_slow"],record["dlugosc_plejlisty"])
return_data = wyszukaj(record["lista_slow"], record["dlugosc_plejlisty"], app.logger)
return_data = (
jsonify(isError=False, message="Success", statusCode=200, data=return_data),
@@ -281,6 +332,7 @@ def flask_debug():
# trunk-ignore(bandit/B201)
app.run(debug=True, use_reloader=False, host=HOST_ADDRESS, port=PORT_ADDRESS)
def waitress_run():
"""
The `waitress_run` function serves the `app` on host "0.0.0.0"
@@ -288,16 +340,19 @@ def waitress_run():
"""
serve(app, host=HOST_ADDRESS, port=PORT_ADDRESS)
if __name__ == "__main__":
logger = logging.getLogger('conjurer_musician')
logger = logging.getLogger("conjurer_musician")
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
formatter = logging.Formatter(
"%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
handler = handlers.RotatingFileHandler(
filename=LOGFILE,
encoding=ENCODING,
mode="a",
maxBytes=6 * 1024 * 1024,
backupCount=6,
filename=LOGFILE,
encoding=ENCODING,
mode="a",
maxBytes=6 * 1024 * 1024,
backupCount=6,
)
handler.setFormatter(formatter)
logger.addHandler(handler)