3 Commits

Author SHA1 Message Date
Joakim Persson 03c08d4024 Introducerade loggning för att ersätta vanliga utskrifter 2024-07-19 17:20:02 +02:00
Joakim Persson 38c78934a5 Ändrade tillbaks till debug=true för Flask 2024-07-19 17:18:40 +02:00
Joakim Persson 66620cc6ca Fler test samt flyttade bort logging-sektionenfrån de oanvända. 2024-07-19 17:17:14 +02:00
3 changed files with 69 additions and 21 deletions
+9 -1
View File
@@ -15,12 +15,20 @@ ollama:
# model: "llama3:70b" # Select a model supported by the Ollama server
# model: "llama3:latest" # Select a model supported by the Ollama server
# Additional Configuration Options (Optional ignored for now)
# Logging comment out the whole section for default level which is INFO
logging:
level: DEBUG # Set log level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
# Additional Configuration Options (Optional ignored for now)
# Cache Settings (Optional)
cache:
enabled: true
timeout: 60 # Seconds
test:
test_key_1: "ett"
test_key_2: "ett"
test_key_3: "${THIS_IS_A_DUMMY_VAR}"
another_test: "Syns detta?"
+2 -1
View File
@@ -83,7 +83,8 @@ def get_response(user_query):
def run_flask(fport=5005):
# Flask endpoint for user interaction
print(f"Entering run_flask()")
app.run(port = str(str(fport)), debug=False)
# app.run(port = str(str(fport)), debug=False)
app.run(port = str(str(fport)), debug=True)
# app.run(port=5000, debug=True, use_reloader=False)
print(f"Exiting run_flask()")
+58 -19
View File
@@ -6,29 +6,66 @@ import json
from backend import run_flask
import socket
import urllib.parse
import logging
global log_level
logger = logging.getLogger(__name__)
def set_local_logger(log_instance):
"""
Configure logging based on the global variable log_level
Logging is controlled by integer values, where DEBUG < INFO < WARNING < ERROR < CRITICAL.
To turn off logging completely, set numeric_log_level to at least CRITICAL + 1.
"""
global log_level
numeric_log_level = getattr(logging, log_level, None)
if not isinstance(numeric_log_level, int):
raise ValueError('Invalid log level: %s' % log_level)
logging.basicConfig(level=numeric_log_level) # Set the root logger level to the configured level
log_instance.info('Log level set to {}'.format(log_level)) # Example usage of the logger
def configure():
##################
# Read YAML config
##################
# 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():
def resolve_env_var(value):
if isinstance(value, str) and value.startswith("${") and value.endswith("}"):
api_key_env = value[2:-1] # Extract name between ${}
env_var_name = value[2:-1] # Extract name between ${}
return os.getenv(env_var_name, None)
return value
# 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.")
def update_dict_with_env_vars(d):
for key in d:
if isinstance(d[key], dict):
update_dict_with_env_vars(d[key]) # Recursively check nested dictionaries
elif isinstance(d[key], str):
d[key] = resolve_env_var(d[key])
return d
# Update the config dictionary with the actual API key (or None if not found)
config['ollama']['api_key'] = api_key
return config
# Update the config dictionary with resolved environment variables
updated_config = update_dict_with_env_vars(config)
##################
# Extract global logging level
##################
# The log_level variable will be used by the logger module to set the log level
global log_level
log_level = 'INFO' # Default value if not specified in the config file
if isinstance(updated_config.get('logging'), dict): # Look for 'logging' key in config file
logging_config = updated_config['logging']
if isinstance(logging_config.get('level'), str): # Set to value of the yaml file if specified
log_level = logging_config['level']
set_local_logger(logger) # Set log level for logger based on log_level
return updated_config
def start_frontend(config):
@@ -41,32 +78,34 @@ def start_frontend(config):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
try:
s.bind((hostname, port))
print(f"No server is running on {parsed_url.netloc}- starting up one.")
logger.info("No server is running on %s -— starting one.", parsed_url.netloc)
# 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(f"A server is already running on {parsed_url.netloc} -— will use this.")
logger.error("A server is already running on %s -— will use this.", parsed_url.netloc)
else:
raise # Unexpected error, re-raise it so we can see the traceback
except Exception as e:
print(f"Failed to start frontend: {e}")
logger.error("Failed to start frontend: %s", str(e)) # Corresponds to 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}")
logger.debug('Backend parsed url set to {}'.format(parsed_url))
logger.debug('Backend port set to {}'.format(port))
try:
run_flask(fport = port)
except Exception as e:
print(f"Failed to start backend: {e}")
logger.error("Failed to start backend: %s", str(e)) # Corresponds to print(f"Failed to start backend: {e}")
if __name__ == '__main__':
conf = configure() # Read config from file and set up config dict
print(json.dumps(conf, indent=4))
logger.debug('conf dictionary set to {}'.format(json.dumps(conf, indent=4)))
start_frontend(config=conf)
start_backend(config=conf)