diff --git "a/app.py" "b/app.py" --- "a/app.py" +++ "b/app.py" @@ -19,6 +19,7 @@ import streamlit as st import streamlit_vertical_slider as svs from pydub import AudioSegment from scipy.signal import butter, sosfilt +from gradio_client import Client as GradioClient # Removed st.session_state alias - using st.session_state directly # WordPress API base URL @@ -84,6 +85,67 @@ except KeyError: st.error("BEARER_TOKEN environment variable is not set.") st.stop() +# ============================================================================= +# HUGGING FACE SPACE CONFIGURATION for MusicGen +# ============================================================================= +# Get HF Space token from environment variables or Streamlit secrets +try: + # Try Streamlit secrets first (for Streamlit Cloud deployment) + HF_SPACE_TOKEN = st.secrets.get("HF_SPACE_TOKEN", None) +except: + # Fall back to environment variable + HF_SPACE_TOKEN = os.environ.get("HF_SPACE_TOKEN", None) + +# Your MusicGen Space URL +MUSICGEN_SPACE = "Healthydater/musicgen" + +# MusicGen client will be initialized on-demand (lazy loading) +# This avoids timeout issues when the Space is sleeping at startup +musicgen_client = None +# ============================================================================= + +def get_musicgen_client_with_retry(max_retries=3, retry_delay=120): + """ + Initialize or get the MusicGen Space client with retry logic. + This handles cold starts by retrying with delays. + + Args: + max_retries: Number of connection attempts + retry_delay: Seconds to wait between retries (default: 120s = 2 minutes) + + Returns: + GradioClient instance or None if all retries failed + """ + global musicgen_client + + # If client already initialized, return it + if musicgen_client is not None: + return musicgen_client + + # Try to initialize with retries + for attempt in range(1, max_retries + 1): + try: + print(f"Connecting to model (attempt {attempt}/{max_retries})...") + + # Gradio Client automatically uses HF_TOKEN environment variable if set + client = GradioClient(MUSICGEN_SPACE) + + print(f"✅ Connected to model successfully") + musicgen_client = client + return client + + except Exception as e: + error_msg = str(e) + print(f"Connection attempt {attempt} failed: {error_msg}") + + if attempt < max_retries: + print(f"Waiting {retry_delay}s before retry...") + time.sleep(retry_delay) + else: + print(f"❌ All connection attempts failed") + return None + + return None page_bg_img = '''