Update streamlit_app.py
Browse files- streamlit_app.py +3 -32
streamlit_app.py
CHANGED
|
@@ -21,59 +21,46 @@
|
|
| 21 |
import numpy as np
|
| 22 |
from PIL import Image
|
| 23 |
import torch
|
| 24 |
-
|
| 25 |
# Import UI components
|
| 26 |
from ui import render_ui
|
| 27 |
-
|
| 28 |
# Import pipeline functions
|
| 29 |
-
from pipeline.video_pipeline import (
|
| 30 |
stage1_create_transparent_video,
|
| 31 |
stage2_composite_background,
|
| 32 |
setup_t4_environment,
|
| 33 |
-
check_gpu
|
| 34 |
-
dump_env
|
| 35 |
)
|
| 36 |
-
|
| 37 |
# --- Constants ---
|
| 38 |
APP_NAME = "Advanced Video Background Replacer"
|
| 39 |
LOG_FILE = "/tmp/app.log"
|
| 40 |
LOG_MAX_BYTES = 5 * 1024 * 1024
|
| 41 |
LOG_BACKUPS = 5
|
| 42 |
-
|
| 43 |
# --- Logging Setup ---
|
| 44 |
def setup_logging(level: int = logging.INFO) -> logging.Logger:
|
| 45 |
logger = logging.getLogger(APP_NAME)
|
| 46 |
logger.setLevel(level)
|
| 47 |
logger.propagate = False
|
| 48 |
-
|
| 49 |
# Clear previous handlers on rerun
|
| 50 |
for h in list(logger.handlers):
|
| 51 |
logger.removeHandler(h)
|
| 52 |
-
|
| 53 |
# Console handler
|
| 54 |
ch = logging.StreamHandler(sys.stdout)
|
| 55 |
ch.setLevel(level)
|
| 56 |
ch.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
|
| 57 |
-
|
| 58 |
# Rotating file handler
|
| 59 |
fh = logging.handlers.RotatingFileHandler(
|
| 60 |
LOG_FILE, maxBytes=LOG_MAX_BYTES, backupCount=LOG_BACKUPS, encoding="utf-8"
|
| 61 |
)
|
| 62 |
fh.setLevel(level)
|
| 63 |
fh.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
|
| 64 |
-
|
| 65 |
logger.addHandler(ch)
|
| 66 |
logger.addHandler(fh)
|
| 67 |
return logger
|
| 68 |
-
|
| 69 |
logger = setup_logging()
|
| 70 |
-
|
| 71 |
# --- Global Exception Hook ---
|
| 72 |
def custom_excepthook(type, value, tb):
|
| 73 |
logger.error(f"Unhandled: {type.__name__}: {value}\n{''.join(traceback.format_tb(tb))}", exc_info=True)
|
| 74 |
-
|
| 75 |
sys.excepthook = custom_excepthook
|
| 76 |
-
|
| 77 |
# --- Session State Initialization ---
|
| 78 |
def initialize_session_state():
|
| 79 |
defaults = {
|
|
@@ -98,11 +85,8 @@ def initialize_session_state():
|
|
| 98 |
for k, v in defaults.items():
|
| 99 |
if k not in st.session_state:
|
| 100 |
st.session_state[k] = v
|
| 101 |
-
|
| 102 |
if st.session_state.gpu_available is None:
|
| 103 |
-
dump_env(logger)
|
| 104 |
st.session_state.gpu_available = check_gpu(logger)
|
| 105 |
-
|
| 106 |
# --- Set Log Level ---
|
| 107 |
def set_log_level(name: str):
|
| 108 |
name = (name or "INFO").upper()
|
|
@@ -113,19 +97,16 @@ def set_log_level(name: str):
|
|
| 113 |
logger.setLevel(lvl)
|
| 114 |
st.session_state.log_level_name = name
|
| 115 |
logger.info(f"Log level set to {name}")
|
| 116 |
-
|
| 117 |
# --- Main Processing Function ---
|
| 118 |
def process_video(uploaded_video, bg_image, bg_color, bg_type):
|
| 119 |
run_id = uuid.uuid4().hex[:8]
|
| 120 |
logger.info("=" * 80)
|
| 121 |
logger.info(f"[RUN {run_id}] VIDEO PROCESSING STARTED at {datetime.utcnow().isoformat()}Z")
|
| 122 |
logger.info("=" * 80)
|
| 123 |
-
|
| 124 |
st.session_state.processing = True
|
| 125 |
st.session_state.processed_video_bytes = None
|
| 126 |
st.session_state.last_error = None
|
| 127 |
t0 = time.time()
|
| 128 |
-
|
| 129 |
try:
|
| 130 |
# Materialize uploaded video to temp file
|
| 131 |
suffix = Path(uploaded_video.name).suffix or ".mp4"
|
|
@@ -133,27 +114,21 @@ def process_video(uploaded_video, bg_image, bg_color, bg_type):
|
|
| 133 |
uploaded_video.seek(0)
|
| 134 |
tmp_vid.write(uploaded_video.read())
|
| 135 |
tmp_vid_path = tmp_vid.name
|
| 136 |
-
|
| 137 |
# Stage 1: Create transparent video and extract audio
|
| 138 |
transparent_path, audio_path = stage1_create_transparent_video(tmp_vid_path)
|
| 139 |
if not transparent_path or not os.path.exists(transparent_path):
|
| 140 |
raise RuntimeError("Stage 1 failed: Transparent video not created")
|
| 141 |
-
|
| 142 |
# Stage 2: Composite with background and restore audio
|
| 143 |
background = bg_image.convert("RGB") if bg_type == "Image" else bg_color
|
| 144 |
final_path = stage2_composite_background(transparent_path, audio_path, background, bg_type.lower())
|
| 145 |
-
|
| 146 |
if not final_path or not os.path.exists(final_path):
|
| 147 |
raise RuntimeError("Stage 2 failed: Final video not created")
|
| 148 |
-
|
| 149 |
# Load final video into memory for download
|
| 150 |
with open(final_path, 'rb') as f:
|
| 151 |
st.session_state.processed_video_bytes = f.read()
|
| 152 |
-
|
| 153 |
total = time.time() - t0
|
| 154 |
logger.info(f"[RUN {run_id}] SUCCESS size={len(st.session_state.processed_video_bytes)/1e6:.2f}MB, total Δ={total:.2f}s")
|
| 155 |
return True
|
| 156 |
-
|
| 157 |
except Exception as e:
|
| 158 |
total = time.time() - t0
|
| 159 |
error_msg = f"[RUN {run_id}] Processing Error: {str(e)} (Δ {total:.2f}s)\n\nCheck logs for details."
|
|
@@ -161,11 +136,9 @@ def process_video(uploaded_video, bg_image, bg_color, bg_type):
|
|
| 161 |
logger.error(traceback.format_exc())
|
| 162 |
st.session_state.last_error = error_msg
|
| 163 |
return False
|
| 164 |
-
|
| 165 |
finally:
|
| 166 |
st.session_state.processing = False
|
| 167 |
logger.info(f"[RUN {run_id}] Processing finished")
|
| 168 |
-
|
| 169 |
# --- Main App Entry Point ---
|
| 170 |
def main():
|
| 171 |
st.set_page_config(
|
|
@@ -174,10 +147,8 @@ def main():
|
|
| 174 |
layout="wide",
|
| 175 |
initial_sidebar_state="expanded"
|
| 176 |
)
|
| 177 |
-
|
| 178 |
initialize_session_state()
|
| 179 |
render_ui(process_video)
|
| 180 |
-
|
| 181 |
if __name__ == "__main__":
|
| 182 |
setup_t4_environment()
|
| 183 |
-
main()
|
|
|
|
| 21 |
import numpy as np
|
| 22 |
from PIL import Image
|
| 23 |
import torch
|
|
|
|
| 24 |
# Import UI components
|
| 25 |
from ui import render_ui
|
|
|
|
| 26 |
# Import pipeline functions
|
| 27 |
+
from pipeline.video_pipeline import (
|
| 28 |
stage1_create_transparent_video,
|
| 29 |
stage2_composite_background,
|
| 30 |
setup_t4_environment,
|
| 31 |
+
check_gpu
|
|
|
|
| 32 |
)
|
|
|
|
| 33 |
# --- Constants ---
|
| 34 |
APP_NAME = "Advanced Video Background Replacer"
|
| 35 |
LOG_FILE = "/tmp/app.log"
|
| 36 |
LOG_MAX_BYTES = 5 * 1024 * 1024
|
| 37 |
LOG_BACKUPS = 5
|
|
|
|
| 38 |
# --- Logging Setup ---
|
| 39 |
def setup_logging(level: int = logging.INFO) -> logging.Logger:
|
| 40 |
logger = logging.getLogger(APP_NAME)
|
| 41 |
logger.setLevel(level)
|
| 42 |
logger.propagate = False
|
|
|
|
| 43 |
# Clear previous handlers on rerun
|
| 44 |
for h in list(logger.handlers):
|
| 45 |
logger.removeHandler(h)
|
|
|
|
| 46 |
# Console handler
|
| 47 |
ch = logging.StreamHandler(sys.stdout)
|
| 48 |
ch.setLevel(level)
|
| 49 |
ch.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
|
|
|
|
| 50 |
# Rotating file handler
|
| 51 |
fh = logging.handlers.RotatingFileHandler(
|
| 52 |
LOG_FILE, maxBytes=LOG_MAX_BYTES, backupCount=LOG_BACKUPS, encoding="utf-8"
|
| 53 |
)
|
| 54 |
fh.setLevel(level)
|
| 55 |
fh.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
|
|
|
|
| 56 |
logger.addHandler(ch)
|
| 57 |
logger.addHandler(fh)
|
| 58 |
return logger
|
|
|
|
| 59 |
logger = setup_logging()
|
|
|
|
| 60 |
# --- Global Exception Hook ---
|
| 61 |
def custom_excepthook(type, value, tb):
|
| 62 |
logger.error(f"Unhandled: {type.__name__}: {value}\n{''.join(traceback.format_tb(tb))}", exc_info=True)
|
|
|
|
| 63 |
sys.excepthook = custom_excepthook
|
|
|
|
| 64 |
# --- Session State Initialization ---
|
| 65 |
def initialize_session_state():
|
| 66 |
defaults = {
|
|
|
|
| 85 |
for k, v in defaults.items():
|
| 86 |
if k not in st.session_state:
|
| 87 |
st.session_state[k] = v
|
|
|
|
| 88 |
if st.session_state.gpu_available is None:
|
|
|
|
| 89 |
st.session_state.gpu_available = check_gpu(logger)
|
|
|
|
| 90 |
# --- Set Log Level ---
|
| 91 |
def set_log_level(name: str):
|
| 92 |
name = (name or "INFO").upper()
|
|
|
|
| 97 |
logger.setLevel(lvl)
|
| 98 |
st.session_state.log_level_name = name
|
| 99 |
logger.info(f"Log level set to {name}")
|
|
|
|
| 100 |
# --- Main Processing Function ---
|
| 101 |
def process_video(uploaded_video, bg_image, bg_color, bg_type):
|
| 102 |
run_id = uuid.uuid4().hex[:8]
|
| 103 |
logger.info("=" * 80)
|
| 104 |
logger.info(f"[RUN {run_id}] VIDEO PROCESSING STARTED at {datetime.utcnow().isoformat()}Z")
|
| 105 |
logger.info("=" * 80)
|
|
|
|
| 106 |
st.session_state.processing = True
|
| 107 |
st.session_state.processed_video_bytes = None
|
| 108 |
st.session_state.last_error = None
|
| 109 |
t0 = time.time()
|
|
|
|
| 110 |
try:
|
| 111 |
# Materialize uploaded video to temp file
|
| 112 |
suffix = Path(uploaded_video.name).suffix or ".mp4"
|
|
|
|
| 114 |
uploaded_video.seek(0)
|
| 115 |
tmp_vid.write(uploaded_video.read())
|
| 116 |
tmp_vid_path = tmp_vid.name
|
|
|
|
| 117 |
# Stage 1: Create transparent video and extract audio
|
| 118 |
transparent_path, audio_path = stage1_create_transparent_video(tmp_vid_path)
|
| 119 |
if not transparent_path or not os.path.exists(transparent_path):
|
| 120 |
raise RuntimeError("Stage 1 failed: Transparent video not created")
|
|
|
|
| 121 |
# Stage 2: Composite with background and restore audio
|
| 122 |
background = bg_image.convert("RGB") if bg_type == "Image" else bg_color
|
| 123 |
final_path = stage2_composite_background(transparent_path, audio_path, background, bg_type.lower())
|
|
|
|
| 124 |
if not final_path or not os.path.exists(final_path):
|
| 125 |
raise RuntimeError("Stage 2 failed: Final video not created")
|
|
|
|
| 126 |
# Load final video into memory for download
|
| 127 |
with open(final_path, 'rb') as f:
|
| 128 |
st.session_state.processed_video_bytes = f.read()
|
|
|
|
| 129 |
total = time.time() - t0
|
| 130 |
logger.info(f"[RUN {run_id}] SUCCESS size={len(st.session_state.processed_video_bytes)/1e6:.2f}MB, total Δ={total:.2f}s")
|
| 131 |
return True
|
|
|
|
| 132 |
except Exception as e:
|
| 133 |
total = time.time() - t0
|
| 134 |
error_msg = f"[RUN {run_id}] Processing Error: {str(e)} (Δ {total:.2f}s)\n\nCheck logs for details."
|
|
|
|
| 136 |
logger.error(traceback.format_exc())
|
| 137 |
st.session_state.last_error = error_msg
|
| 138 |
return False
|
|
|
|
| 139 |
finally:
|
| 140 |
st.session_state.processing = False
|
| 141 |
logger.info(f"[RUN {run_id}] Processing finished")
|
|
|
|
| 142 |
# --- Main App Entry Point ---
|
| 143 |
def main():
|
| 144 |
st.set_page_config(
|
|
|
|
| 147 |
layout="wide",
|
| 148 |
initial_sidebar_state="expanded"
|
| 149 |
)
|
|
|
|
| 150 |
initialize_session_state()
|
| 151 |
render_ui(process_video)
|
|
|
|
| 152 |
if __name__ == "__main__":
|
| 153 |
setup_t4_environment()
|
| 154 |
+
main()
|