import streamlit as st import os import subprocess import sys import glob import streamlit_authenticator as stauth import yaml # -------------------------------------------------- # Streamlit Page Configuration # -------------------------------------------------- st.set_page_config( page_title="Demo Engine", page_icon="📊", layout="wide", ) # -------------------------------------------------- # Secrets: GitHub Credentials & Repository Name # -------------------------------------------------- # PRV_REPO: Name of the GitHub repository to clone (e.g. "internal_demo_signal_portfolio") REPO_NAME = st.secrets["PRV_REPO"] # APP_SUBDIR: The subdirectory inside the cloned repository where your app resides. APP_SUBDIR = "private_repo" git_user = st.secrets["GIT_USR"] git_token = st.secrets["GIT_TK"] def clone_repository(): """ Clone the GitHub repository if it hasn't been cloned already. The repository is cloned into a folder named REPO_NAME. """ repo_url = f"https://{git_user}:{git_token}@github.com/{git_user}/{REPO_NAME}.git" if not os.path.exists(REPO_NAME): print("Cloning repository...") subprocess.run(["git", "clone", repo_url], check=True) else: print("Repository already cloned.") def install_custom_packages(): """ Install custom Python packages from the 'packages' directory in a specific order defined by packages_order. This function installs packages either from a directory (editable install) or from a tar.gz file matching the pattern "{pkg}-*.tar.gz". Packages not listed in packages_order will be installed afterward in alphabetical order. """ packages_dir = os.path.join(os.getcwd(), "packages") if not os.path.exists(packages_dir): print("No 'packages' directory found. Skipping custom packages installation.") return print("Installing custom packages in specified order...") # Define the installation order. packages_order = ["lotus_data", "ta_indicators", "indicator_scoring", "portfolio_stats", "ta_inversion"] installed = set() # Install packages in the specified order. for pkg in packages_order: pkg_dir = os.path.join(packages_dir, pkg) if os.path.isdir(pkg_dir): print(f"Installing package (editable): {pkg}") subprocess.run( [sys.executable, "-m", "pip", "install", "-e", pkg_dir], check=True ) installed.add(pkg) else: # Look for a tar.gz file matching the package pattern. pattern = os.path.join(packages_dir, f"{pkg}-*.tar.gz") files = glob.glob(pattern) if files: tar_pkg_path = files[0] # take the first match print(f"Installing package from tar.gz: {tar_pkg_path}") subprocess.run( [sys.executable, "-m", "pip", "install", tar_pkg_path], check=True ) installed.add(pkg) else: print(f"Package '{pkg}' not found in the 'packages' directory.") # Install remaining packages (those not in packages_order) in alphabetical order. for item in sorted(os.listdir(packages_dir)): # For tar.gz files, extract the base name (before the first hyphen) base_item = item.split('-')[0] if item.endswith(".tar.gz") else item if base_item in installed: continue # Skip if already installed. item_path = os.path.join(packages_dir, item) if os.path.isdir(item_path): print(f"Installing package (editable): {item}") subprocess.run( [sys.executable, "-m", "pip", "install", "-e", item_path], check=True ) elif os.path.isfile(item_path) and item.endswith(".tar.gz"): print(f"Installing package from tar.gz: {item}") subprocess.run( [sys.executable, "-m", "pip", "install", item_path], check=True ) else: print(f"Skipping unknown package format: {item}") def install_requirements(): """ Install dependencies from the requirements.txt file in the current working directory. """ requirements_path = os.path.join(os.getcwd(), "requirements.txt") if os.path.exists(requirements_path): print("Installing requirements from requirements.txt...") subprocess.run( [sys.executable, "-m", "pip", "install", "-r", requirements_path], check=True ) else: print("requirements.txt not found.") def setup_environment(): """ Clone the repository and install dependencies if not already done. A marker file (.setup_complete) is stored in the app folder to avoid repeating setup. """ # Determine the absolute path to the app folder inside the cloned repository. repo_app_path = os.path.join(os.getcwd(), REPO_NAME, APP_SUBDIR) marker = os.path.join(repo_app_path, "setup_complete.txt") # Clone repository if needed. if not os.path.exists(REPO_NAME): clone_repository() # Verify the app folder exists. if not os.path.exists(repo_app_path): raise FileNotFoundError(f"App folder not found: {repo_app_path}") # Change directory into the repository's app folder. os.chdir(repo_app_path) # If the marker file does not exist, run the installation steps. if not os.path.exists(marker): print("Running environment setup in:", repo_app_path) install_custom_packages() install_requirements() # Create the marker file to signal that setup is complete. with open(marker, "w") as f: f.write("done") else: print("Setup already completed. Skipping installation steps.") # -------------------------------------------------- # Main Loading Process # -------------------------------------------------- try: setup_environment() # (Optional) List files in the current directory for debugging. subprocess.run(["ls", "-l"], shell=True) # Import and run the main app. # Since your repository contains 'st_app.py' in the app folder, # import main_app from st_app.py. from st_app import main_app # Load authentication configuration from the YAML file with open('.streamlit/auth_config.yaml') as file: config = yaml.safe_load(file) # Initialize the authenticator with config details authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'] ) # Display the login widget name, authentication_status, username = authenticator.login() if authentication_status: main_app() elif authentication_status is False: st.error("Username/password is incorrect") st.stop() # Stop further execution elif authentication_status is None: st.warning("Please enter your username and password") st.stop() # Stop further execution except Exception as e: # Log errors to the console (these messages will not display in the UI). print("Something went wrong! Error details:", e)