Skip to content

Commit

Permalink
Merge pull request #22 from Zhou-Shilin/v2ui-config
Browse files Browse the repository at this point in the history
feat: Add config edit feature to v2-ui
  • Loading branch information
Zhou-Shilin authored Jun 15, 2024
2 parents d696189 + fd63259 commit 582ce6c
Show file tree
Hide file tree
Showing 4 changed files with 150 additions and 24 deletions.
62 changes: 47 additions & 15 deletions config.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,55 @@
import yaml
from log_writer import logger

with open("config.yaml", "r") as conf:
config_content = yaml.safe_load(conf)
for key, value in config_content.items():
if key == "CODING_MODEL" and value == "gpt-4":
globals()[key] = "gpt-4-turbo-preview" # Force using gpt-4-turbo-preview if the user set the CODING_MODEL to gpt-4. Because gpt-4 is not longer supports json modes.
globals()[key] = value
logger(f"config: {key} -> {value}")
def load_config():
"""
Loads the configuration from the 'config.yaml' file and sets the global variables accordingly.
If the 'GENERATE_MODEL' key in the configuration is set to 'gpt-4', it forces the use of 'gpt-4-turbo-preview'
as the value for the 'GENERATE_MODEL' key, since 'gpt-4' no longer supports json modes.
Returns:
None
"""
with open("config.yaml", "r") as conf:
config_content = yaml.safe_load(conf)
for key, value in config_content.items():
if key == "GENERATE_MODEL" and value == "gpt-4":
globals()[key] = "gpt-4-turbo-preview" # Force using gpt-4-turbo-preview if the user set the GENERATE_MODEL to gpt-4. Because gpt-4 is not longer supports json modes.
globals()[key] = value
logger(f"config: {key} -> {value}")

def edit_config(key, value):
with open("config.yaml", "r") as file:
lines = file.readlines()
"""
Edits the config file.
Args:
key (str): The key to edit.
value (str): The value to set.
Returns:
bool: True
"""

for i, line in enumerate(lines):
if f"{key}:" in line:
lines[i] = line.replace(line.split(":")[1].strip().strip('"'), f"{value}")
with open("config.yaml", "r") as conf:
config_content = conf.readlines()

with open("config.yaml", "w") as conf:
for line in config_content:
if line.startswith(key):
if value == True:
write_value = "True"
elif value == False:
write_value = "False"
else:
write_value = f"\"{value}\""
if "#" in line:
conf.write(f"{key}: {write_value} # {line.split('#')[1]}\n")
else:
conf.write(f"{key}: {write_value}\n")
else:
conf.write(line)

with open("config.yaml", "w") as file:
file.writelines(lines)
return True

logger(f"edit_config: {key} -> {value}")
load_config()
4 changes: 2 additions & 2 deletions config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ NAMING_MODEL: "gpt-3.5-turbo"
RENDERING_URL: "https://beta.cubical.xyz/" # Don't change this unless you know what you are doing.

# DEVELOPER SETTINGS #
DEBUG_MODE: True
VERSION_NUMBER: "2.0.0" #NEVER EDIT THIS IF YOU DON'T KNOW WHAT ARE YOU DOING
DEBUG_MODE: False
VERSION_NUMBER: "2.0.0" # NEVER EDIT THIS IF YOU DON'T KNOW WHAT ARE YOU DOING

# PROMPT SETTINGS #
# If you don't know what it is, please don't touch it. Be sure to backup before editing.
Expand Down
10 changes: 8 additions & 2 deletions cube_qgui/base_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,15 @@
# Please indicate the source for reprinting.
import threading
import traceback
import sys
from typing import Dict

import tkinter

from cube_qgui.manager import *

from log_writer import logger


def check_callable(bind_func):
if bind_func and not hasattr(bind_func, "__call__"):
Expand Down Expand Up @@ -168,9 +171,12 @@ def new_func(obj):
try:
func(obj)
except Exception as e:
print("-----以下为异常信息-----")
print("-----ERROR MSG START-----")
print(traceback.print_exc())
print("-----以上为异常信息-----")
print("-----ERROR MSG END-----")

# Record the error message to the log
logger(f"Error: {e}")
if end_func:
end_func()
# 清除Flag,此时按钮可以再次点击
Expand Down
98 changes: 93 additions & 5 deletions ui-v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import shutil
import uuid

from log_writer import logger
import config
import core
import browser
Expand Down Expand Up @@ -149,14 +150,86 @@ def open_config(args: dict):
Returns:
bool: Always True.
"""
os.system("notepad config.py")
os.system("notepad config.yaml")

return True

def save_apply_config(args: dict):
"""
Saves and applies the configuration.
Args:
args (dict): A dictionary containing the necessary arguments.
Returns:
bool: Always True.
"""
keys = ["API_KEY", "BASE_URL"]

for key in keys:
value = args[key].get()

if key == "ADVANCED_MODE":
value = True if value == 1 else False
else:
pass

config.edit_config(key, value)

config.load_config()

args["DevTool_CONFIG_API_KEY_DISPLAY"].set(f"CONFIG.API_KEY = {config.API_KEY}")
args["DevTools_CONFIG_BASE_URL_DISPLAY"].set(f"CONFIG.BASE_URL = {config.BASE_URL}")

return True

def load_config(args: dict):
"""
Loads the configuration.
Args:
args (dict): A dictionary containing the necessary arguments.
Returns:
bool: Always True.
"""
config.load_config()

args["API_KEY"].set(config.API_KEY)
args["BASE_URL"].set(config.BASE_URL)

return True

def print_args(args: dict):
"""
Prints the arguments.
Args:
args (dict): A dictionary containing the arguments.
Returns:
bool: Always True.
"""
for arg, v_fun in args.items():
print(f"Name: {arg}, Value: {v_fun.get()}")

return True

def raise_error(args: dict):
"""
Raises an error.
Args:
args (dict): A dictionary containing the arguments.
"""
raise Exception("This is a test error.")

root = CreateQGUI(title="BuilderGPT",
tab_names=["Generate", "Render", "Settings"]
tab_names=["Generate", "Render", "Settings", "DevTools"]
)

logger("Starting program.")

# Initialize Core
core.initialize()

Expand All @@ -168,15 +241,30 @@ def open_config(args: dict):
root.add_notebook_tool(InputBox(name="Description", default="A simple house", label_info="Description", tab_index=0))

root.add_notebook_tool(Progressbar(name="Generation Progress", title="Progress", tab_index=0))
root.add_notebook_tool(RunButton(generate, "Generate", tab_index=0))
root.add_notebook_tool(RunButton(bind_func=generate, name="Generate", text="Generate", tab_index=0))

# Render Page
root.add_notebook_tool(ChooseFileTextButton(name="Schematic File Path", label_info="Schematic File", tab_index=1))
root.add_notebook_tool(Progressbar(name="Rendering Progress", title="Progress", tab_index=1))
root.add_notebook_tool(RunButton(render, "Render", tab_index=1))
root.add_notebook_tool(RunButton(bind_func=render, name="Render", text="Render", tab_index=1))

# Settings Page
root.add_notebook_tool(RunButton(open_config, "Open Config", "Open Config", tab_index=2))
root.add_notebook_tool(InputBox(name="API_KEY", default=config.API_KEY, label_info="API Key", tab_index=2))
root.add_notebook_tool(InputBox(name="BASE_URL", default=config.BASE_URL, label_info="BASE URL", tab_index=2))

config_buttons = HorizontalToolsCombine([
BaseButton(bind_func=save_apply_config, name="Save & Apply Config", text="Save & Apply", tab_index=2),
BaseButton(bind_func=load_config, name="Load Config", text="Load Config", tab_index=2),
BaseButton(bind_func=open_config, name="Open Config", text="Open Full Config", tab_index=2)
])
root.add_notebook_tool(config_buttons)

# DevTools Page
root.add_notebook_tool(Label(name="DevTool_DESCRIPTION", text="This is a testing page for developers. Ignore it if you are a normal user.", tab_index=3))
root.add_notebook_tool(Label(name="DevTool_CONFIG_API_KEY_DISPLAY", text=f"CONFIG.API_KEY = {config.API_KEY}", tab_index=3))
root.add_notebook_tool(Label(name="DevTools_CONFIG_BASE_URL_DISPLAY", text=f"CONFIG.BASE_URL = {config.BASE_URL}", tab_index=3))
root.add_notebook_tool(RunButton(bind_func=print_args, name="Print Args", text="Print Args", tab_index=3))
root.add_notebook_tool(RunButton(bind_func=raise_error, name="Raise Error", text="Raise Error", tab_index=3))

# Sidebar
root.set_navigation_about(author="CubeGPT Team",
Expand Down

0 comments on commit 582ce6c

Please sign in to comment.