Files
python_test/smartassist/src/startservices.py
T

72 lines
2.7 KiB
Python

# Start all services
import subprocess
import os
import yaml
from backend import run_flask
import socket
import urllib.parse
def configure():
# Load configuration file that defines parameters for services
with open('./smartassist/config/smartassist.yaml') as f:
config = yaml.safe_load(f)
# 1. Find the API Key environment variable name
api_key_env = None
for key, value in config['ollama'].items():
if isinstance(value, str) and value.startswith("${") and value.endswith("}"):
api_key_env = value[2:-1] # Extract name between ${}
# 2. Obtain API Key if an environment variable was found
api_key = None
if api_key_env:
api_key = os.getenv(api_key_env)
else:
print("Warning: Environment variable reference not found in YAML configuration.")
# Update the config dictionary with the actual API key (or None if not found)
config['ollama']['api_key'] = api_key
return config
def start_frontend(config):
parsed_url = urllib.parse.urlparse(config['frontend']['url'])
hostname = parsed_url.netloc.split(':')[0] # Split by ':' and take the first part, i.e., 'localhost', IP, or domain name
port = parsed_url.port # This is the server port
# Use the socket module in Python to check whether a port is in use,
# which would indicate that a server is already running on that port.
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
try:
s.bind((hostname, port))
print("No server is running on this host and port.")
# Start frontend (web server) as a separate process
subprocess.Popen(["python", "-m", "http.server", str(port)])
except socket.error as e:
if e.errno == 48:
print("Another server is already running on this host and port. Assumes it is a web server, will continue.")
else:
raise # Unexpected error, re-raise it so we can see the traceback
except Exception as e:
print(f"Failed to start frontend: {e}")
def start_backend(config):
parsed_url = urllib.parse.urlparse(config['backend']['url'])
# hostname = parsed_url.netloc.split(':')[0] # Split by ':' and take the first part, i.e., 'localhost', IP, or domain name
port = parsed_url.port # This is the server port
print(f"{port}")
try:
run_flask(port = port)
except Exception as e:
print(f"Failed to start backend: {e}")
if __name__ == '__main__':
conf = configure() # Read config from file and set up config dict
print(conf)
start_frontend(config=conf) # No need for this as the backend starts a web server on its own.
start_backend(config=conf)