File size: 1,626 Bytes
1321ce6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import pathlib
import modal

# Define container dependencies
image = (
    modal.Image.debian_slim()
    .apt_install("git")
    .pip_install("streamlit", "numpy", "pandas", "tensorflow", "transformers", "spotipy", "sentence_transformers")
)

stub = modal.Stub(name="streamlit_app.py", image=image)

# Define the run_streamlit function
@stub.function(
    mounts=[
        modal.Mount.from_local_directory(
            local_path=pathlib.Path(__file__).parent,
            remote_path=pathlib.Path("/app"),
            exclude=["*.pyc", "__pycache__"]
        )
    ],
    timeout=15 * 60  # Set the session timeout as needed
)
def run_streamlit(publish_url: bool = False):
    import streamlit.web.bootstrap

    streamlit_script_remote_path = pathlib.Path("streamlit_app.py")
    
    # Run the server. This function will not return until the server is shut down.
    with modal.forward(8501) as tunnel:
        # Reload Streamlit config with information about Modal tunnel address.
        if publish_url:
            stub.q.put(tunnel.url)
        streamlit.web.bootstrap.run(
            main_script_path=str(streamlit_script_remote_path),
            command_line=None,
            args=["--timeout", str(15 * 60)],  # Adjust as needed
            flag_options={},
        )

# Additional function for creating a web endpoint
@stub.function()
@modal.web_endpoint(method="GET")
def share():
    from fastapi.responses import RedirectResponse

    run_streamlit.spawn(publish_url=True)
    url = stub.q.get()
    return RedirectResponse(url, status_code=303)

# Deploy the app
if __name__ == "__main__":
    stub.deploy()