File size: 7,306 Bytes
88aa271
 
 
 
a649493
2614b6d
c78998f
88aa271
8b1e4f7
88aa271
8b1e4f7
88aa271
65c9c3e
88aa271
 
 
 
8b1e4f7
d6dd170
8b1e4f7
a649493
 
1a005d3
d6dd170
 
 
855b960
d6dd170
88aa271
8b1e4f7
d6dd170
88aa271
d6dd170
 
8b1e4f7
88aa271
 
8b1e4f7
88aa271
 
 
c5d284c
 
a649493
5d5fdaa
 
 
88aa271
 
c5d284c
8b1e4f7
c5d284c
 
 
 
 
 
 
 
 
 
 
5d5fdaa
 
c5d284c
 
5d5fdaa
c5d284c
 
 
 
a649493
5d5fdaa
 
 
 
 
 
 
 
 
 
 
 
c5d284c
 
 
a649493
5d5fdaa
 
a649493
c5d284c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88aa271
 
d6dd170
88aa271
 
 
8b1e4f7
88aa271
a649493
88aa271
 
 
8b1e4f7
88aa271
d6dd170
 
 
1a005d3
d6dd170
a649493
1a005d3
2df0d76
1a005d3
 
 
d6dd170
1a005d3
a649493
1a005d3
 
a649493
 
1a005d3
 
a649493
1a005d3
 
d6dd170
 
a649493
d6dd170
 
 
1a005d3
d6dd170
8b1e4f7
88aa271
8b1e4f7
88aa271
d6dd170
88aa271
a649493
88aa271
8b1e4f7
d6dd170
1a005d3
d95f981
 
2614b6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88aa271
 
a649493
1a005d3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
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)