added save videos

This commit is contained in:
juancarlos.cavero 2025-12-24 01:14:02 +01:00
parent 207f1aa8e3
commit 0b0ffccb69
3 changed files with 65 additions and 1 deletions

9
app.py
View file

@ -5,15 +5,18 @@ import threading
import json import json
import shutil import shutil
import glob import glob
import glob
import time import time
import asyncio import asyncio
from dotenv import load_dotenv
from typing import Dict, Optional, List from typing import Dict, Optional, List
from contextlib import asynccontextmanager from contextlib import asynccontextmanager
from fastapi import FastAPI, UploadFile, File, Form, HTTPException, Request, Header from fastapi import FastAPI, UploadFile, File, Form, HTTPException, Request, Header
from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel from pydantic import BaseModel
from s3_uploader import upload_job_artifacts
load_dotenv()
# Constants # Constants
UPLOAD_DIR = "uploads" UPLOAD_DIR = "uploads"
@ -247,6 +250,10 @@ async def run_job(job_id, job_data):
jobs[job_id]['status'] = 'completed' jobs[job_id]['status'] = 'completed'
jobs[job_id]['logs'].append("Process finished successfully.") jobs[job_id]['logs'].append("Process finished successfully.")
# Start S3 upload in background (silent, non-blocking)
loop = asyncio.get_event_loop()
loop.run_in_executor(None, upload_job_artifacts, output_dir, job_id)
# Find result JSON # Find result JSON
json_files = glob.glob(os.path.join(output_dir, "*_metadata.json")) json_files = glob.glob(os.path.join(output_dir, "*_metadata.json"))
if not json_files: if not json_files:

View file

@ -8,6 +8,7 @@ faster-whisper
google-genai google-genai
python-dotenv python-dotenv
mediapipe==0.10.14 mediapipe==0.10.14
boto3
fastapi fastapi
uvicorn uvicorn

56
s3_uploader.py Normal file
View file

@ -0,0 +1,56 @@
import os
import boto3
from botocore.exceptions import ClientError
import logging
# Configure silent logging for boto3 and botocore
logging.getLogger('boto3').setLevel(logging.CRITICAL)
logging.getLogger('botocore').setLevel(logging.CRITICAL)
logging.getLogger('s3transfer').setLevel(logging.CRITICAL)
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
def upload_file_to_s3(file_path, bucket_name, s3_key):
"""
Upload a file to an S3 bucket silently.
"""
access_key = os.environ.get('AWS_ACCESS_KEY_ID')
secret_key = os.environ.get('AWS_SECRET_ACCESS_KEY')
region = os.environ.get('AWS_REGION', 'us-east-1')
if not access_key or not secret_key:
return False
s3_client = boto3.client(
's3',
aws_access_key_id=access_key,
aws_secret_access_key=secret_key,
region_name=region
)
try:
# Extra arguments for public read if needed, but the user didn't specify.
# Given the bucket name, it might be for a web app.
s3_client.upload_file(file_path, bucket_name, s3_key)
return True
except ClientError:
return False
except Exception:
return False
def upload_job_artifacts(directory, job_id):
"""
Upload all generated clips and metadata for a job to S3.
"""
bucket_name = "openshorts.app-clips"
if not os.path.exists(directory):
return
for filename in os.listdir(directory):
# Upload .mp4 clips and the metadata JSON
if (filename.endswith(".mp4") or filename.endswith(".json")) and not filename.startswith("temp_"):
file_path = os.path.join(directory, filename)
s3_key = f"{job_id}/{filename}"
upload_file_to_s3(file_path, bucket_name, s3_key)