Skip to content

Commit

Permalink
rework themes system
Browse files Browse the repository at this point in the history
  • Loading branch information
blaisewf committed Oct 31, 2024
1 parent 93891af commit f9c084e
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 75 deletions.
2 changes: 1 addition & 1 deletion app.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@
# Load theme
import assets.themes.loadThemes as loadThemes

my_applio = loadThemes.load_json() or "ParityError/Interstellar"
my_applio = loadThemes.load_theme() or "ParityError/Interstellar"

# Define Gradio interface
with gr.Blocks(
Expand Down
137 changes: 65 additions & 72 deletions assets/themes/loadThemes.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,121 +2,114 @@
import os
import importlib
import gradio as gr
import sys

now_dir = os.getcwd()

folder = os.path.dirname(os.path.abspath(__file__))
folder = os.path.dirname(folder)
folder = os.path.dirname(folder)
folder = os.path.join(folder, "assets", "themes")
folder = os.path.join(
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
"assets",
"themes",
)
config_file = os.path.join(now_dir, "assets", "config.json")

import sys

sys.path.append(folder)


def read_json_file(filename):
"""Helper function to read a JSON file and return its contents."""
with open(filename, "r", encoding="utf8") as json_file:
return json.load(json_file)


def get_class(filename):
"""Retrieve the name of the first class found in the specified Python file."""
with open(filename, "r", encoding="utf8") as file:
for line_number, line in enumerate(file, start=1):
for line in file:
if "class " in line:
found = line.split("class ")[1].split(":")[0].split("(")[0].strip()
return found
break
class_name = line.split("class ")[1].split(":")[0].split("(")[0].strip()
return class_name
return None


def get_list():

def get_theme_list():
"""Compile a list of available themes from Python files and a JSON file."""
themes_from_files = [
os.path.splitext(name)[0]
for root, _, files in os.walk(folder, topdown=False)
for root, _, files in os.walk(folder)
for name in files
if name.endswith(".py") and root == folder
]

json_file_path = os.path.join(folder, "theme_list.json")
themes_from_url = []

try:
with open(json_file_path, "r", encoding="utf8") as json_file:
themes_from_url = [item["id"] for item in json.load(json_file)]
themes_from_url = [item["id"] for item in read_json_file(json_file_path)]
except FileNotFoundError:
themes_from_url = []
print("theme_list.json not found, proceeding with available files only.")

combined_themes = set(themes_from_files + themes_from_url)

return list(combined_themes)
return list(set(themes_from_files + themes_from_url))


def select_theme(name):
selected_file = name + ".py"
"""Select a theme by its name, updating the configuration file accordingly."""
selected_file = f"{name}.py"
full_path = os.path.join(folder, selected_file)

if not os.path.exists(full_path):
with open(config_file, "r", encoding="utf8") as json_file:
config_data = json.load(json_file)
config_data = read_json_file(config_file)

if not os.path.exists(full_path):
config_data["theme"]["file"] = None
config_data["theme"]["class"] = name
else:
class_found = get_class(full_path)
if class_found:
config_data["theme"]["file"] = selected_file
config_data["theme"]["class"] = class_found
else:
print(f"Theme class not found in {selected_file}.")
return

with open(config_file, "w", encoding="utf8") as json_file:
json.dump(config_data, json_file, indent=2)
print(f"Theme {name} successfully selected, restart applio.")
gr.Info(f"Theme {name} successfully selected, restart applio.")
return

class_found = get_class(full_path)
if class_found:
with open(config_file, "r", encoding="utf8") as json_file:
config_data = json.load(json_file)

config_data["theme"]["file"] = selected_file
config_data["theme"]["class"] = class_found
with open(config_file, "w", encoding="utf8") as json_file:
json.dump(config_data, json_file, indent=2)

with open(config_file, "w", encoding="utf8") as json_file:
json.dump(config_data, json_file, indent=2)
print(f"Theme {name} successfully selected, restart applio.")
gr.Info(f"Theme {name} successfully selected, restart applio.")
else:
print(f"Theme {name} was not found.")
message = f"Theme {name} successfully selected. Restart the application."
print(message)
gr.Info(message)


def read_json():
def load_theme():
"""Load the selected theme based on the configuration file."""
try:
with open(config_file, "r", encoding="utf8") as json_file:
data = json.load(json_file)
selected_file = data["theme"]["file"]
class_name = data["theme"]["class"]
config_data = read_json_file(config_file)
selected_file = config_data["theme"]["file"]
class_name = config_data["theme"]["class"]

if selected_file is not None and class_name:
return class_name
elif selected_file == None and class_name:
return class_name
if class_name:
if selected_file:
module = importlib.import_module(selected_file[:-3])
obtained_class = getattr(module, class_name)
return obtained_class()
else:
return "ParityError/Interstellar"
return class_name
else:
print("No valid theme class found.")
return None

except Exception as error:
print(f"An error occurred loading the theme: {error}")
return "ParityError/Interstellar"
print(f"An error occurred while loading the theme: {error}")
return None


def load_json():
def read_current_theme():
"""Read the current theme class from the configuration file."""
try:
with open(config_file, "r", encoding="utf8") as json_file:
data = json.load(json_file)
selected_file = data["theme"]["file"]
class_name = data["theme"]["class"]
config_data = read_json_file(config_file)
selected_file = config_data["theme"]["file"]
class_name = config_data["theme"]["class"]

return class_name if class_name else "ParityError/Interstellar"

if selected_file is not None and class_name:
module = importlib.import_module(selected_file[:-3])
obtained_class = getattr(module, class_name)
instance = obtained_class()
print(f"Theme {class_name} successfully loaded.")
return instance
elif selected_file == None and class_name:
return class_name
else:
print("The theme is incorrect.")
return None
except Exception as error:
print(f"An error occurred loading the theme: {error}")
return None
return "ParityError/Interstellar"
4 changes: 2 additions & 2 deletions tabs/settings/sections/themes.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ def theme_tab():
with gr.Row():
with gr.Column():
themes_select = gr.Dropdown(
loadThemes.get_list(),
value=loadThemes.read_json(),
loadThemes.get_theme_list(),
value=loadThemes.load_theme(),
label=i18n("Theme"),
info=i18n(
"Select the theme you want to use. (Requires restarting Applio)"
Expand Down

0 comments on commit f9c084e

Please sign in to comment.