Ajusta projeto para consumir uma fila

This commit is contained in:
LeoMortari
2025-08-02 12:27:26 -03:00
parent 5bb58c98e5
commit 95d287bafc
3 changed files with 53 additions and 63 deletions

106
main.py
View File

@@ -1,21 +1,30 @@
import os
import pika
import json
import requests
import threading
os.environ["IMAGEIO_FFMPEG_EXE"] = "/usr/bin/ffmpeg"
from flask import Flask, request, jsonify
from components.video import process_full_video
app = Flask(__name__)
RABBITMQ_HOST = os.environ.get('RABBITMQ_HOST', 'rabbitmq')
RABBITMQ_PORT = int(os.environ.get('RABBITMQ_PORT', 5672))
RABBITMQ_USER = os.environ.get('RABBITMQ_USER', 'admin')
RABBITMQ_PASS = os.environ.get('RABBITMQ_PASS')
RABBITMQ_QUEUE = os.environ.get('RABBITMQ_QUEUE', 'to-render')
def process_and_call_webhook(url, video_id, times, webhook_url, filename):
if not RABBITMQ_PASS:
raise RuntimeError("RABBITMQ_PASS não definido no ambiente")
def callback(ch, method, properties, body):
try:
os.makedirs("videos", exist_ok=True)
os.makedirs("temp", exist_ok=True)
data = json.loads(body)
filename = data.get("filename")
times = data.get("times", [])
webhook_url = data.get("webhookUrl")
url = data.get("url")
video_id = data.get("videoId")
print(f"Processando vídeo: {filename}")
print(f"Working on video {filename}")
processed_files = process_full_video(filename, times)
payload = {
@@ -26,63 +35,44 @@ def process_and_call_webhook(url, video_id, times, webhook_url, filename):
"videoId": video_id,
"error": False,
}
try:
resp = requests.post(webhook_url, json=payload, timeout=30)
print(f"Webhook status: {resp.status_code}, content: {resp.text}")
except Exception as webhook_error:
print(f"Erro ao chamar webhook: {webhook_error}")
except Exception as e:
payload = {
"videosProcessedQuantity": 0,
"filename": filename,
"processedFiles": processed_files,
"url": url,
"videoId": video_id,
"filename": filename if 'filename' in locals() else None,
"processedFiles": [],
"url": url if 'url' in locals() else None,
"videoId": video_id if 'video_id' in locals() else None,
"error": str(e),
}
try:
resp = requests.post(webhook_url, json=payload, timeout=30)
print(f"Webhook send error status: {resp.status_code}")
print(str(e))
except Exception as webhook_error:
print(f"Erro ao chamar webhook: {webhook_error}")
print(f"Erro no processamento: {e}")
@app.route('/process', methods=['POST'])
def process_video():
try:
if webhook_url:
resp = requests.post(webhook_url, json=payload, timeout=30)
print(f"Webhook status: {resp.status_code}")
except Exception as wh_err:
print(f"Erro ao chamar webhook: {wh_err}")
data = request.get_json()
if not data or not ("url" in data or "videoId" in data):
return jsonify({"error": "Informe 'url' ou 'videoId'"}), 400
ch.basic_ack(delivery_tag=method.delivery_tag)
url = data.get("url")
video_id = data.get("videoId")
times = data.get("times", [])
webhook_url = data.get("webhookUrl")
def main():
credentials = pika.PlainCredentials(RABBITMQ_USER, RABBITMQ_PASS)
parameters = pika.ConnectionParameters(
host=RABBITMQ_HOST,
port=RABBITMQ_PORT,
credentials=credentials,
heartbeat=600,
blocked_connection_timeout=300
)
connection = pika.BlockingConnection(parameters)
channel = connection.channel()
channel.queue_declare(queue=RABBITMQ_QUEUE, durable=True)
channel.basic_qos(prefetch_count=1)
channel.basic_consume(queue=RABBITMQ_QUEUE, on_message_callback=callback)
if not webhook_url:
return jsonify({"error": "Informe 'webhookUrl'"}), 400
print(' [*] Esperando mensagens. Para sair: CTRL+C')
filename = data.get("filename")
if not filename:
return jsonify({"error": "Informe 'filename'"}), 400
channel.start_consuming()
threading.Thread(
target=process_and_call_webhook,
args=(url, video_id, times, webhook_url, filename),
daemon=True
).start()
return jsonify({"message": f"{video_id if video_id else url}"}), 200
if __name__ == '__main__':
app.run(host="0.0.0.0", port=5000, debug=True)
if __name__ == "__main__":
main()