File size: 1,846 Bytes
c20196f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from flask import Flask, render_template
import subprocess
import os
import signal
import atexit
import platform
from pathlib import Path

app = Flask(__name__, template_folder="templates")
streamlit_process = None

@app.route("/")
def home():
    return render_template("index.html")

@app.route("/model")
def model():
    # simple client redirect to Streamlit
    return """
    <script>window.location.href = 'http://localhost:8501';</script>
    <p>Redirecting to AutVid AI...</p>
    """

def start_streamlit():
    """Launch Streamlit as subprocess (works on Windows/macOS/Linux)."""
    global streamlit_process
    if streamlit_process is not None:
        return
    # ensure model.py exists
    if not Path("model.py").exists():
        raise FileNotFoundError("model.py not found next to app.py")
    cmd = ["streamlit", "run", "model.py", "--server.port", "8501", "--server.headless", "true"]
    if platform.system() == "Windows":
        streamlit_process = subprocess.Popen(cmd, creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
    else:
        # setsid to create a new process group so we can kill gracefully
        streamlit_process = subprocess.Popen(cmd, preexec_fn=os.setsid)

def stop_streamlit():
    """Kill Streamlit process when Flask exits."""
    global streamlit_process
    if streamlit_process:
        try:
            if platform.system() == "Windows":
                streamlit_process.send_signal(signal.CTRL_BREAK_EVENT)
            else:
                os.killpg(os.getpgid(streamlit_process.pid), signal.SIGTERM)
        except Exception:
            try:
                streamlit_process.terminate()
            except Exception:
                pass
        streamlit_process = None

atexit.register(stop_streamlit)

if __name__ == "__main__":
    start_streamlit()
    app.run(debug=True, port=5000)