big debug amélioration enregistrement

This commit is contained in:
Foufure13
2025-01-10 15:07:14 +01:00
parent 096c605213
commit af359e9c70
13 changed files with 842 additions and 128 deletions
+155 -71
View File
@@ -7,6 +7,7 @@ import time
import pprint
import random
import requests
import shutil
import datetime
import glob
import threading
@@ -30,6 +31,11 @@ def hprint(color, texte):
timestamp = datetime.datetime.now().strftime("%Hh %Mm %Ss")
console.print("[bold "+color+"] ["+timestamp+"] "+texte+" [/bold "+color+"]")
def sprint(script_name,color, texte):
timestamp = datetime.datetime.now().strftime("%Hh %Mm %Ss")
console.print("[bold "+color+"] ["+timestamp+"] ("+script_name+") "+texte+" [/bold "+color+"]")
def del_file(dossier, file):
motif = os.path.join(dossier, file)
for file in glob.glob(motif):
@@ -55,85 +61,162 @@ def get_current_time():
################### RecordTwitch ########################
class RecordTwitch:
def __init__(self, channel_name, recordtime):
def __init__(self, channel_name, record_time):
self.channel_name = channel_name
self.all_proxies = []
self.channel_url = "https://www.twitch.tv/" + self.channel_name
self.record_time = recordtime
self.dir_twitchrecord = "twitch-recordAudio"
self.process = None # Pour stocker le sous-processus en cours
self.record_time = record_time
self.max_timerecordfile = 60
self.running = True
self.script_name = "twitch_record"
if (self.record_time == -1):
self.record_time = 9999
def stop(self):
"""Arrête le processus d'enregistrement s'il est en cours."""
if self.process and self.process.poll() is None: # Vérifie si le processus est actif
hprint("yellow",f"Arrêt de l'enregistrement...")
self.process.terminate() # Envoie un signal de terminaison
try:
self.process.wait(timeout=5) # Attend la fin avec un délai de 5 secondes
except subprocess.TimeoutExpired:
hprint("RED",f"Le processus ne répond pas, forçage de l'arrêt.")
self.process.kill() # Forcer l'arrêt si le processus ne termine pas
hprint("yellow",f"Enregistrement arrêté.")
else:
hprint("green",f"Aucun enregistrement en cours.")
sprint(self.script_name,"magenta","STOPING RecordTwitch")
self.running = False
def del_mp3(self, dossier):
motif = os.path.join(dossier, '*.mp3')
for file in glob.glob(motif):
os.remove(file)
sprint(self.script_name,"yellow",f"file deleted : {file}")
def hprint(self,color, texte):
timestamp = datetime.datetime.now().strftime("%Hh %Mm %Ss")
console.print("[bold "+color+"] ["+timestamp+"] "+texte+" [/bold "+color+"]")
# Fonction pour convertir l'heure en secondes
def time_to_seconds(time_str):
h, m, s = map(int, time_str.split(':'))
return h * 3600 + m * 60 + s
def clear_diretory(self, dir_inrecord="in_record", dir_record="record"):
#sprint(self.script_name,'green', 'clear_diretory start')
if os.path.exists(dir_inrecord) and os.path.exists(dir_record):
sprint(self.script_name,'green', f"dir {dir_inrecord} and {dir_record} exist clearing")
self.del_mp3(dir_inrecord)
self.del_mp3(dir_record)
# Fonction pour rechercher dans le dictionnaire
def search_dict(d, key):
return d.get(key, "Key not found")
def create_session(self):
# Session creating for request
self.ua = UserAgent()
self.session = Streamlink()
self.session.set_option("http-headers", {
"Accept-Language": "en-US,en;q=0.5",
"Connection": "keep-alive",
"DNT": "1",
"Upgrade-Insecure-Requests": "1",
"User-Agent": self.ua.random,
"Client-ID": "your_client_id", # Replace with your actual Client-ID
"Referer": "https://www.google.com/"
})
def main_record_twitch(self):
# Utiliser Popen à la place de run pour pouvoir arrêter le processus
def get_url(self):
sprint(self.script_name,"green","start get_url")
url = ""
self.create_session()
try:
print(f"Lancement de l'enregistrement pour {self.channel_name} pendant {self.record_time} secondes.")
record_twitch = ['python', self.dir_twitchrecord+'/twitch_record_unlimited.py', '-twitchname', self.channel_name,'-recordtime',str(self.record_time)]
self.process = subprocess.Popen(record_twitch)
self.process.communicate() # Attend que le sous-processus termine
streams = self.session.streams(self.channel_url)
url = streams['audio_only'].url if 'audio_only' in streams else streams['worst'].url
sprint(self.script_name,"cyan","url generate : " + url)
except Exception as e:
print(f"Erreur pendant l'enregistrement: {e}")
def start_recording(self):
"""Lance main_record_twitch dans un thread pour ne pas bloquer le code principal."""
self.thread = threading.Thread(target=self.main_record_twitch)
self.thread.start() # Démarre l'enregistrement dans un thread séparé
sprint(self.script_name,"red","Error on get url : "+str(e))
# traceback.print_exc() # Affiche les détails de l'erreur
pass
return url
################### RecordTwitch FIN ########################
def loop_run(self, intervalle):#boucle pour déplacer les fichier fini enregistrement
time.sleep(30) # attente début du script complet et enregistrement
try:
while self.running:
self.verif_record_move()
sprint(self.script_name,"yellow", f"wait {intervalle}s for next scan file completed.")
time.sleep(intervalle)
except KeyboardInterrupt:
sprint(self.script_name,"red", "STOP LOOP.")
finally:
self.running = False # Assurez-vous que le drapeau est désactivé
def verif_record_move(self, dir_inrecord="in_record", dir_record="record"):
sprint(self.script_name,"green", "start verif_record_move")
if not os.path.exists(dir_record):
os.makedirs(dir_record)
sprint(self.script_name,"green", "création du dossier : "+dir_record)
fichiers = [f for f in os.listdir(dir_inrecord) if os.path.isfile(os.path.join(dir_inrecord, f))]
if len(fichiers) > 1:
# sort file
sort_file = sorted(fichiers, key=lambda x: int(x.split('_')[-1].split('.')[0]))
fileto_move = sort_file[0]
chemin_source = os.path.join(dir_inrecord, fileto_move)
chemin_destination = os.path.join(dir_record, fileto_move)
# move file
shutil.move(chemin_source, chemin_destination)
sprint(self.script_name,"green",f"File moved: {fileto_move}")
else:
sprint(self.script_name,"yellow","Not enough files to compare.")
def compteur(self ):
seconds = 0
loop = 0
while self.running:
time.sleep(1) # Attend une seconde
if (seconds < 10):
print(f"\033[94mRecording time: 0{seconds}s | file : {loop}\033[0m", end='\r', flush=True) # Réinitialise la ligne à chaque fois
else:
print(f"\033[94mRecording time: {seconds}s | file : {loop}\033[0m", end='\r', flush=True) # Réinitialise la ligne à chaque fois
seconds += 1
if seconds == self.max_timerecordfile:
loop +=1
seconds = 0 # Réinitialise le compteur après 60 seconds
def record_audio(self):
output_directory = "record"
in_record_directory = "in_record"
os.makedirs(output_directory, exist_ok=True)
os.makedirs(in_record_directory, exist_ok=True)
timestamp_complet = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
timestamp = datetime.datetime.now().strftime("%Y-%m-%d")
output_file_path = os.path.join(in_record_directory, f"{timestamp}_%03d.mp3")
sprint(self.script_name,"green", f"start record")
thread_compteur = Thread(target=self.compteur, daemon=True)
thread_compteur.start()
command = ['ffmpeg','-i', self.stream_url,'-vn','-acodec','libmp3lame','-ar','44100','-ac','2','-map','0:a','-f','segment','-segment_time',str(self.max_timerecordfile),'-segment_format','mp3',output_file_path,'-loglevel', 'error']
# sprint(self.script_name,'yellow',str(command))
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
output, error = process.communicate()
# thread_compteur.do_run = False
thread_compteur.join()
def main(self):
self.running = True
self.clear_diretory()
self.stream_url = self.get_url()
if not self.stream_url:
sprint(self.script_name,"red","Impossible de récupérer l'URL du flux")
return
record_thread = Thread(target=self.record_audio)
record_thread.start()
# record_thread.join() # Wait for the recording to finish
loop_run = Thread(target=self.loop_run, args=(20,), daemon=True)
loop_run.start()
#loop_run.join() # Wait for the recording to finish
sprint(self.script_name,"cyan","Enregistrement terminé, le programme va se terminer.")
################## RecordTwitch FIN ########################
@@ -355,10 +438,11 @@ class IA_generator:
def change_prompt(self):
if self.index_prompt == len(self.list_prompt):
self.index_prompt = 0
else :
self.index_prompt += 1
self.index_prompt = len(self.list_prompt) -1
# if self.index_prompt == len(self.list_prompt):
# self.index_prompt = 0
# else :
# self.index_prompt += 1
def reload_json(self):
@@ -506,8 +590,8 @@ class messageTwitch:
def change_user(self):
# commented for pausing
if (self.totaluser != 1): # si la liste ne fait que 1 de taille
if(self.totaluser+1 > self.indexuser): # si la taille de liste est plus grande que lindex
if (self.totaluser != 1): # si la liste ne fait pas que 1 de taille
if(self.totaluser > self.indexuser): # si la taille de liste est plus grande que lindex
self.indexuser = self.indexuser + 1
else :
self.indexuser = 0
@@ -543,7 +627,7 @@ class messageTwitch:
message_tosend = 'python send_message.py '+command
hprint("yellow",f"send message = "+str(message_tosend))
subprocess.run(message_tosend, shell=True)
hprint("yellow",f"Finnish send message")
hprint("yellow",f"Finnish send send_message_user index :" + str(index_user))
def send_message(self, Message_text):
@@ -553,7 +637,7 @@ class messageTwitch:
message_tosend = 'python send_message.py '+command
hprint("yellow",f"send message = "+str(message_tosend))
subprocess.run(message_tosend, shell=True)
hprint("yellow",f"Finnish send message")
hprint("yellow",f"Finnish send_message message")