aboutsummaryrefslogtreecommitdiff
path: root/modules/scripts.py
blob: 20f489ce9237f36eb80430aa64ab058d506fa3f1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import os
import sys
import traceback

import gradio as gr

class Script:
    filename = None

    def title(self):
        raise NotImplementedError()


scripts = []


def load_scripts(basedir, globs):
    for filename in os.listdir(basedir):
        path = os.path.join(basedir, filename)

        if not os.path.isfile(path):
            continue

        with open(path, "r", encoding="utf8") as file:
            text = file.read()

        from types import ModuleType
        compiled = compile(text, path, 'exec')
        module = ModuleType(filename)
        module.__dict__.update(globs)
        exec(compiled, module.__dict__)

        for key, item in module.__dict__.items():
            if type(item) == type and issubclass(item, Script):
                item.filename = path

                scripts.append(item)


def wrap_call(func, filename, funcname, *args, default=None, **kwargs):
    try:
        res = func()
        return res
    except Exception:
        print(f"Error calling: {filename/funcname}", file=sys.stderr)
        print(traceback.format_exc(), file=sys.stderr)

    return default

def setup_ui():
    titles = [wrap_call(script.title, script.filename, "title") for script in scripts]

    gr.Dropdown(options=[""] + titles, value="", type="index")