Subida de código
This commit is contained in:
108
whisper-distributed/receiver/app.py
Normal file
108
whisper-distributed/receiver/app.py
Normal file
@@ -0,0 +1,108 @@
|
||||
#!/usr/bin/env python
|
||||
import os
|
||||
import time
|
||||
import pika
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from datetime import datetime
|
||||
|
||||
# Configuración de logging
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
||||
)
|
||||
logger = logging.getLogger('receiver')
|
||||
|
||||
# Configuración de RabbitMQ
|
||||
RABBITMQ_HOST = 'rabbitmq'
|
||||
RABBITMQ_USER = 'user'
|
||||
RABBITMQ_PASS = 'password'
|
||||
SPLIT_QUEUE = 'audio_split_queue'
|
||||
|
||||
# Directorios
|
||||
INPUT_DIR = '/app/input'
|
||||
SHARED_DIR = '/app/shared'
|
||||
|
||||
def connect_to_rabbitmq():
|
||||
"""Establece conexión con RabbitMQ"""
|
||||
tries = 0
|
||||
while True:
|
||||
try:
|
||||
credentials = pika.PlainCredentials(RABBITMQ_USER, RABBITMQ_PASS)
|
||||
connection = pika.BlockingConnection(
|
||||
pika.ConnectionParameters(
|
||||
host=RABBITMQ_HOST,
|
||||
credentials=credentials
|
||||
)
|
||||
)
|
||||
return connection
|
||||
except pika.exceptions.AMQPConnectionError:
|
||||
tries += 1
|
||||
logger.warning(f"Intento {tries}: No se pudo conectar a RabbitMQ. Reintentando en 5 segundos...")
|
||||
time.sleep(5)
|
||||
|
||||
def process_audio_file(filepath):
|
||||
"""Procesa un archivo de audio y lo envía a la cola de RabbitMQ"""
|
||||
filename = os.path.basename(filepath)
|
||||
file_id = f"{int(datetime.now().timestamp())}_{filename}"
|
||||
|
||||
# Guardar una copia en el directorio compartido
|
||||
shared_path = os.path.join(SHARED_DIR, file_id)
|
||||
os.system(f"cp {filepath} {shared_path}")
|
||||
|
||||
# Enviar mensaje a RabbitMQ para procesamiento
|
||||
connection = connect_to_rabbitmq()
|
||||
channel = connection.channel()
|
||||
|
||||
# Declarar la cola
|
||||
channel.queue_declare(queue=SPLIT_QUEUE, durable=True)
|
||||
|
||||
# Preparar mensaje
|
||||
message = {
|
||||
'file_id': file_id,
|
||||
'filename': filename,
|
||||
'filepath': shared_path,
|
||||
'timestamp': datetime.now().isoformat()
|
||||
}
|
||||
|
||||
# Publicar mensaje
|
||||
channel.basic_publish(
|
||||
exchange='',
|
||||
routing_key=SPLIT_QUEUE,
|
||||
body=json.dumps(message),
|
||||
properties=pika.BasicProperties(
|
||||
delivery_mode=2 # mensaje persistente
|
||||
)
|
||||
)
|
||||
|
||||
logger.info(f"Archivo {filename} enviado a la cola {SPLIT_QUEUE} con ID {file_id}")
|
||||
connection.close()
|
||||
|
||||
def monitor_input_directory():
|
||||
"""Monitorea el directorio de entrada para nuevos archivos de audio"""
|
||||
# Asegurar que el directorio compartido existe
|
||||
os.makedirs(SHARED_DIR, exist_ok=True)
|
||||
|
||||
# Crear conjunto de archivos ya procesados
|
||||
processed_files = set()
|
||||
|
||||
logger.info(f"Iniciando monitoreo del directorio {INPUT_DIR}")
|
||||
|
||||
while True:
|
||||
# Buscar archivos de audio en el directorio de entrada
|
||||
audio_extensions = ['.mp3', '.wav', '.flac', '.m4a', '.ogg']
|
||||
for ext in audio_extensions:
|
||||
for audio_file in Path(INPUT_DIR).glob(f'*{ext}'):
|
||||
filepath = str(audio_file)
|
||||
if filepath not in processed_files:
|
||||
logger.info(f"Nuevo archivo detectado: {filepath}")
|
||||
process_audio_file(filepath)
|
||||
processed_files.add(filepath)
|
||||
|
||||
# Esperar antes de volver a comprobar
|
||||
time.sleep(10)
|
||||
|
||||
if __name__ == "__main__":
|
||||
logger.info("Servicio receptor iniciado")
|
||||
monitor_input_directory()
|
||||
Reference in New Issue
Block a user