Spaces:
Sleeping
Sleeping
Chandima Prabhath commited on
Commit ·
0410763
1
Parent(s): 9792bdd
Add logging and threading support for video encoding worker
Browse filesFiles changed (4)
1234567import uvicornfrom video_encoder.api.main import appif __name__ == "__main__":uvicorn.run(app,host="0.0.0.0",1234567891011121314151617181920import uvicornfrom video_encoder.api.main import appfrom rq import Worker, Queue, Connectionfrom redis import Redisfrom video_encoder.config import RedisConfigif __name__ == "__main__":import threadingdef start_worker():with Connection(RedisConfig.get_connection()):worker = Worker(map(Queue, [RedisConfig.QUEUE_NAME]))worker.work()worker_thread = threading.Thread(target=start_worker)worker_thread.start()uvicorn.run(app,host="0.0.0.0",
9 unmodified lines10111213141516171819202122232425262728293031323 unmodified lines363738394041424344453 unmodified lines49505152535455565758596061627 unmodified lines70717273749 unmodified linesfrom redis import from_urlfrom ..config import EncodingConfig, RedisConfigfrom ..worker.tasks import encode_video_taskq = Queue(connection=RedisConfig.get_connection(), default_timeout=3600)app = FastAPI(title="Video Encoding Service")@app.post("/upload")async def upload_video(file: UploadFile):job_id = str(uuid.uuid4())temp_dir = os.path.join(EncodingConfig.TEMP_DIR, job_id)os.makedirs(temp_dir, exist_ok=True)input_path = os.path.join(temp_dir, file.filename)with open(input_path, "wb") as f:f.write(await file.read())q.enqueue(encode_video_task, job_id, input_path)return JSONResponse(content={"job_id": job_id},status_code=status.HTTP_202_ACCEPTED3 unmodified linesasync def get_status(job_id: str):redis = RedisConfig.get_connection()progress = redis.hget(f"job:{job_id}", "progress")if not progress:raise HTTPException(status_code=404, detail="Job not found")return {"job_id": job_id, "progress": float(progress)}@app.get("/play/{job_id}")3 unmodified linesjob_id.encode(),hashlib.sha256).hexdigest()if not hmac.compare_digest(token, expected_token):raise HTTPException(status_code=403, detail="Invalid token")master_playlist = os.path.join(EncodingConfig.TEMP_DIR, job_id, f"{job_id}_master.m3u8")if not os.path.exists(master_playlist):raise HTTPException(status_code=404, detail="Playlist not found")return FileResponse(master_playlist,media_type="application/vnd.apple.mpegurl"7 unmodified linesf"{job_id}{timestamp}".encode(),hashlib.sha256).hexdigest()return {"token": f"{timestamp}:{signature}"}9 unmodified lines101112131415161718192021222324252627282930313233343536373839403 unmodified lines44454647484950515253543 unmodified lines585960616263646566676869707172737 unmodified lines8182838485869 unmodified linesfrom redis import from_urlfrom ..config import EncodingConfig, RedisConfigfrom ..worker.tasks import encode_video_taskimport logginglogger = logging.getLogger(__name__)q = Queue(connection=RedisConfig.get_connection(), default_timeout=3600)app = FastAPI(title="Video Encoding Service")@app.on_event("startup")async def startup_event():logger.info("Application startup")@app.post("/upload")async def upload_video(file: UploadFile):job_id = str(uuid.uuid4())temp_dir = os.path.join(EncodingConfig.TEMP_DIR, job_id)os.makedirs(temp_dir, exist_ok=True)input_path = os.path.join(temp_dir, file.filename)with open(input_path, "wb") as f:f.write(await file.read())logger.info(f"Enqueuing job {job_id} for file {file.filename}")q.enqueue(encode_video_task, job_id, input_path)return JSONResponse(content={"job_id": job_id},status_code=status.HTTP_202_ACCEPTED3 unmodified linesasync def get_status(job_id: str):redis = RedisConfig.get_connection()progress = redis.hget(f"job:{job_id}", "progress")if not progress:logger.warning(f"Job {job_id} not found")raise HTTPException(status_code=404, detail="Job not found")return {"job_id": job_id, "progress": float(progress)}@app.get("/play/{job_id}")3 unmodified linesjob_id.encode(),hashlib.sha256).hexdigest()if not hmac.compare_digest(token, expected_token):logger.warning(f"Invalid token for job {job_id}")raise HTTPException(status_code=403, detail="Invalid token")master_playlist = os.path.join(EncodingConfig.TEMP_DIR, job_id, f"{job_id}_master.m3u8")if not os.path.exists(master_playlist):logger.warning(f"Playlist not found for job {job_id}")raise HTTPException(status_code=404, detail="Playlist not found")return FileResponse(master_playlist,media_type="application/vnd.apple.mpegurl"7 unmodified linesf"{job_id}{timestamp}".encode(),hashlib.sha256).hexdigest()logger.info(f"Generated token for job {job_id}")return {"token": f"{timestamp}:{signature}"}
6 unmodified lines78910111213143 unmodified lines181920212223246 unmodified linesload_dotenv()class EncodingConfig:TEMP_DIR = "./tmp"class RedisConfig:URL = os.getenv("REDIS_URL")3 unmodified lines@classmethoddef get_connection(cls):if not cls.CONN_POOL:cls.CONN_POOL = from_url(cls.URL, max_connections=20)return cls.CONN_POOLHMAC_SECRET = os.getenv("VIDEO_HMAC_SECRET", "default-secret-change-me")6 unmodified lines78910111213141516171819203 unmodified lines2425262728293031323334356 unmodified linesload_dotenv()import loggingclass EncodingConfig:DEBUG = os.getenv("DEBUG", "False") == "True"TEMP_DIR = "./tmp"LOG_LEVEL = logging.DEBUG if DEBUG else logging.INFOlogging.basicConfig(level=EncodingConfig.LOG_LEVEL)logger = logging.getLogger(__name__)class RedisConfig:URL = os.getenv("REDIS_URL")3 unmodified lines@classmethoddef get_connection(cls):if not cls.CONN_POOL:try:cls.CONN_POOL = from_url(cls.URL, max_connections=20)logger.info("Successfully connected to Redis")except Exception as e:logger.error(f"Failed to connect to Redis: {e}")raisereturn cls.CONN_POOLHMAC_SECRET = os.getenv("VIDEO_HMAC_SECRET", "default-secret-change-me")
8 unmodified lines9101112131415161718192021222324252627282930318 unmodified linesfrom .ffmpeg import FFmpegEncoderfrom ..config import EncodingConfiglogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)q = Queue(connection=RedisConfig.get_connection(), default_timeout=3600)def update_job_progress(job_id: str, progress: float):RedisConfig.get_connection().hset(f"job:{job_id}", "progress", progress)def encode_video_task(job_id: str, input_path: str) -> Optional[str]:try:output_dir = os.path.join(EncodingConfig.TEMP_DIR, job_id)encoder = FFmpegEncoder(input_path, output_dir)update_job_progress(job_id, 0.1)master_playlist = encoder.encode()update_job_progress(job_id, 1.0)return master_playlistexcept Exception as e:logger.error(f"Encoding failed for job {job_id}: {str(e)}")8 unmodified lines91011121314151617181920212223242526272829303132338 unmodified linesfrom .ffmpeg import FFmpegEncoderfrom ..config import EncodingConfiglogger = logging.getLogger(__name__)q = Queue(connection=RedisConfig.get_connection(), default_timeout=3600)def update_job_progress(job_id: str, progress: float):logger.info(f"Updating progress for job {job_id} to {progress}")RedisConfig.get_connection().hset(f"job:{job_id}", "progress", progress)def encode_video_task(job_id: str, input_path: str) -> Optional[str]:try:logger.info(f"Starting encoding for job {job_id}")output_dir = os.path.join(EncodingConfig.TEMP_DIR, job_id)encoder = FFmpegEncoder(input_path, output_dir)update_job_progress(job_id, 0.1)master_playlist = encoder.encode()update_job_progress(job_id, 1.0)logger.info(f"Encoding completed for job {job_id}")return master_playlistexcept Exception as e:logger.error(f"Encoding failed for job {job_id}: {str(e)}")
run.py+13
video_encoder/api/main.py+21-9
video_encoder/config.py+12-1
video_encoder/worker/tasks.py+5-3