Pathl.Stona/app.py

183 lines
5.3 KiB
Python
Raw Normal View History

2026-01-30 17:08:36 +00:00
from flask import Flask, request, render_template, jsonify, send_file
import os, json, importlib, importlib.util, sys, re
from markdown import markdown
2026-01-30 12:33:51 +00:00
app = Flask(__name__)
2026-01-30 17:08:36 +00:00
# FOLDERS
UPLOAD_FOLDER = "scripts"
MODELS_FOLDER = "models"
APKS_FOLDER = "apks"
2026-01-30 12:33:51 +00:00
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
2026-01-30 17:08:36 +00:00
os.makedirs(MODELS_FOLDER, exist_ok=True)
sys.path.insert(0, os.path.join(os.getcwd(), APKS_FOLDER))
2026-01-30 12:33:51 +00:00
2026-01-30 17:08:36 +00:00
# GLOBAL MODELS
2026-01-30 12:33:51 +00:00
MODELS = {}
2026-01-30 17:08:36 +00:00
# ---- Load models at startup ----
2026-01-30 12:33:51 +00:00
def load_models():
2026-01-30 17:08:36 +00:00
global MODELS
MODELS = {}
for folder in os.listdir(MODELS_FOLDER):
path = os.path.join(MODELS_FOLDER, folder)
2026-01-30 12:33:51 +00:00
if not os.path.isdir(path):
continue
meta_path = os.path.join(path, "meta.json")
if not os.path.exists(meta_path):
continue
with open(meta_path) as f:
meta = json.load(f)
func_name = meta.get("function_name")
if not func_name:
continue
py_file = os.path.join(path, "model.py")
spec = importlib.util.spec_from_file_location("model_module", py_file)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
func = getattr(module, func_name)
MODELS[folder] = {
"func": func,
"inputs": meta.get("inputs", []),
"meta": meta,
"path": path
}
load_models()
2026-01-30 17:08:36 +00:00
# ---------------- DASHBOARD ----------------
2026-01-30 12:33:51 +00:00
@app.route("/")
def dashboard():
models_with_md = {}
for name, model in MODELS.items():
md_content = ""
try:
md_path = os.path.join(model["path"], model["meta"]["description_file"])
with open(md_path, "r", encoding="utf-8") as f:
2026-01-30 17:08:36 +00:00
md_content = markdown(f.read())
except:
2026-01-30 12:33:51 +00:00
md_content = "<p>Brak opisu.</p>"
models_with_md[name] = {**model, "md_content": md_content}
return render_template("user.html", models=models_with_md)
2026-01-30 17:08:36 +00:00
# ---------------- EDITOR ----------------
@app.route("/editor/<model_name>")
def editor(model_name):
return render_template("editor.html", model_name=model_name)
# ---------------- RUN SCRIPT (MKScript) ----------------
@app.route("/run_script", methods=["POST"])
def run_script():
code = request.json.get("code", "")
output = []
variables = {}
modules = {}
try:
lines = code.split(";")
for line in lines:
line = line.strip()
if not line:
continue
# use mk
if line.startswith("use "):
name = line.split()[1]
mod = importlib.import_module(name)
modules[name] = mod
variables[name] = mod
continue
# print(...)
if line.startswith("print"):
inside = line[line.find("(")+1:line.rfind(")")]
output.append(str(eval_expr(inside, variables)))
continue
# typy int/float/bool
if any(line.startswith(t) for t in ["int ", "float ", "bool "]):
_, rest = line.split(" ", 1)
var, expr = rest.split("=")
variables[var.strip()] = eval_expr(expr.strip(), variables)
continue
# wywołanie funkcji np mk.add(1,2)
if "." in line and "(" in line:
obj, rest = line.split(".", 1)
fname = rest[:rest.find("(")]
args = rest[rest.find("(")+1:rest.find(")")]
args = [eval_expr(a.strip(), variables) for a in args.split(",")]
result = getattr(modules[obj], fname)(*args)
variables["_"] = result
continue
except Exception as e:
return jsonify({"error": str(e)})
return jsonify({
"output": output,
"variables": {k: str(v) for k, v in variables.items()}
})
def eval_expr(expr, variables):
expr = expr.replace("true", "True").replace("false", "False")
return eval(expr, {}, variables)
# ---------------- PREDICT ----------------
2026-01-30 12:33:51 +00:00
@app.route("/predict/<model_name>", methods=["POST"])
def predict(model_name):
model_entry = MODELS.get(model_name)
if not model_entry:
return jsonify({"output": "Model nie istnieje"}), 404
func = model_entry["func"]
inputs = model_entry["inputs"]
2026-01-30 17:08:36 +00:00
kwargs = {inp: request.form.get(inp) for inp in inputs}
2026-01-30 12:33:51 +00:00
try:
for k in kwargs:
try:
kwargs[k] = float(kwargs[k])
except:
pass
output = func(**kwargs)
except Exception as e:
output = str(e)
return jsonify({"output": str(output)})
2026-01-30 17:08:36 +00:00
# ---------------- DOWNLOAD SCRIPT ----------------
@app.route("/download_script/<filename>")
def download_script(filename):
path = os.path.join(UPLOAD_FOLDER, filename)
if os.path.exists(path):
return send_file(path, as_attachment=True)
return "Plik nie istnieje", 404
# ---------------- UPLOAD SCRIPT ----------------
@app.route("/upload_script", methods=["POST"])
def upload_script():
file = request.files.get("file")
if not file:
return "Nie przesłano pliku", 400
filename = file.filename
path = os.path.join(UPLOAD_FOLDER, filename)
file.save(path)
return "OK"
# ---------------- MAIN ----------------
2026-01-30 12:33:51 +00:00
if __name__ == "__main__":
2026-01-30 17:08:36 +00:00
app.run(port=4500)