from flask import Flask, request, redirect, url_for, render_template_string
import subprocess
import threading

app = Flask(__name__)

# Replace these with your desired username and password
USERNAME = 'your_username'
PASSWORD = 'your_password'

html_login = '''
<!doctype html>
<title>Login</title>
<h1>Login</h1>
<form method=post>
  <input type=text name=username placeholder='Username'>
  <input type=password name=password placeholder='Password'>
  <input type=submit value=Login>
</form>
'''

@app.route('/', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        if request.form['username'] == USERNAME and request.form['password'] == PASSWORD:
            return redirect(url_for('gradio_app'))
        else:
            return 'Incorrect credentials', 401
    return render_template_string(html_login)

@app.route('/gradio')
def gradio_app():
    # This will ensure the app runs only once and not on every request
    if not gradio_app.started:
        threading.Thread(target=run_gradio).start()
        gradio_app.started = True
    return redirect("http://localhost:7860")

def run_gradio():
    subprocess.run(["python", "app_w_lora.py"])

# Initialize the flag to indicate if the Gradio app has started
gradio_app.started = False

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5000)