Spaces:
Runtime error
Runtime error
import os | |
import streamlit as st | |
import googleapiclient.discovery | |
from google.oauth2 import service_account | |
def auth(): | |
with open("/tmp/token.json", "w") as token_f: | |
google_key = os.getenv("GOOGLE_KEY") | |
token_f.write(google_key) | |
credentials = service_account.Credentials.from_service_account_file('/tmp/token.json') | |
return credentials | |
def get_status(credentials, instance_name): | |
status = False | |
client = googleapiclient.discovery.build('compute', 'v1', credentials=credentials) | |
response = client.instances().list(project='nus-cisco-corp-lab-wp1', zone='asia-southeast1-c').execute() | |
for item in response['items']: | |
if item["name"] == instance_name: | |
try: | |
ip_address = item['networkInterfaces'][0]['accessConfigs'][0]['natIP'] | |
except Exception as e: | |
ip_address = None | |
status = True if item["status"] == "RUNNING" else False | |
return status, ip_address | |
def activate_server(credentials, instance_name): | |
service = googleapiclient.discovery.build('compute', 'v1', credentials=credentials) | |
request = service.instances().start(project='nus-cisco-corp-lab-wp1', zone='asia-southeast1-c', instance=instance_name) | |
response = request.execute() | |
return response | |
st.title("Lucky Reactor") | |
instance_name = "lucky-reactor" | |
credentials = auth() | |
status, ip_address = get_status(credentials, instance_name) | |
st.image("cover.jpg", caption="Lucky Reactor is currently " + ("running π" if status else "sleeping π΄") + ".") | |
if not status: | |
with st.form("my_form"): | |
token = st.text_input("Token (FYI: The reactor costs USD $10 per hour to operate)") | |
submitted = st.form_submit_button("Ignite π") | |
if submitted and token == os.getenv("EASY_TOKEN"): | |
st.write("Lucky Reactor has been ignited. Please wait a few minutes (3~5) to preceed...") | |
response = activate_server(credentials, instance_name) | |
else: | |
st.write(f"You can access Lucky Reactor via http://{ip_address}:7860") |