From abc48604a1bd70570bf1980753d5c3a933ca65de Mon Sep 17 00:00:00 2001 From: Scott Register Date: Sun, 27 Jul 2025 08:55:42 -0700 Subject: [PATCH] timeout init --- vr180_streaming/sam2_streaming.py | 1 - vr180_streaming/timeout_init.py | 45 +++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 vr180_streaming/timeout_init.py diff --git a/vr180_streaming/sam2_streaming.py b/vr180_streaming/sam2_streaming.py index e49d8e7..ccb16a4 100644 --- a/vr180_streaming/sam2_streaming.py +++ b/vr180_streaming/sam2_streaming.py @@ -18,7 +18,6 @@ from pathlib import Path from typing import Dict, Any, List, Optional, Tuple, Generator import warnings import gc -from .timeout_init import safe_init_state, TimeoutError # Import SAM2 components - these will be available after SAM2 installation try: diff --git a/vr180_streaming/timeout_init.py b/vr180_streaming/timeout_init.py new file mode 100644 index 0000000..5ec701c --- /dev/null +++ b/vr180_streaming/timeout_init.py @@ -0,0 +1,45 @@ +""" +Timeout wrapper for SAM2 initialization to prevent hanging +""" + +import signal +import functools +from typing import Any, Callable + + +class TimeoutError(Exception): + pass + + +def timeout(seconds: int = 120): + """Decorator to add timeout to function calls""" + def decorator(func: Callable) -> Callable: + @functools.wraps(func) + def wrapper(*args, **kwargs) -> Any: + # Define signal handler + def timeout_handler(signum, frame): + raise TimeoutError(f"Function {func.__name__} timed out after {seconds} seconds") + + # Set signal handler + old_handler = signal.signal(signal.SIGALRM, timeout_handler) + signal.alarm(seconds) + + try: + result = func(*args, **kwargs) + finally: + # Restore old handler + signal.alarm(0) + signal.signal(signal.SIGALRM, old_handler) + + return result + return wrapper + return decorator + + +@timeout(120) # 2 minute timeout +def safe_init_state(predictor, video_path: str, **kwargs) -> Any: + """Safely initialize SAM2 state with timeout""" + return predictor.init_state( + video_path=video_path, + **kwargs + ) \ No newline at end of file