iraisul

wdyd new work cgpt

Nov 1st, 2025
279
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.23 KB | None | 0 0
  1. # Retry: create the GUI script file attr_form_gui.py in /mnt/data and report result.
  2. import os, textwrap, sys
  3. OUTFILE = "/mnt/data/attr_form_gui.py"
  4. code = r'''"""
  5. attr_form_gui.py
  6. Phase 3: Dynamic GUI form that builds widgets based on attribute_properties JSON and YAML config.
  7. Saves completed work entries into work_properties table as JSON.
  8. Requires: ttkbootstrap, pyyaml
  9. Run: python attr_form_gui.py
  10. """
  11.  
  12. import os, sqlite3, json, yaml, datetime, random, string, sys
  13. import tkinter as tk
  14. from tkinter import ttk, messagebox, simpledialog
  15. import ttkbootstrap as tb
  16.  
  17. DB_PATH = "wdyd4.db"
  18. YAML_PATH = "attributes_config.yaml"
  19.  
  20. # ---------- Phase1 utilities (embedded) ----------
  21. def load_config(config_path=YAML_PATH):
  22.    if not os.path.exists(config_path):
  23.        return {"attributes": [], "attribute_properties": [], "maximum_binded_attribute_support": 1}
  24.    with open(config_path, "r", encoding="utf-8") as f:
  25.        cfg = yaml.safe_load(f) or {}
  26.    cfg.setdefault("attributes", [])
  27.    cfg.setdefault("attribute_properties", [])
  28.    cfg.setdefault("maximum_binded_attribute_support", 1)
  29.    return cfg
  30.  
  31. def formWorkID(prefix="WDY"):
  32.    now = datetime.datetime.utcnow()
  33.    core = now.strftime("%y%m%d%H%M%S%f")[:-3]
  34.    suffix = ''.join(random.choices(string.ascii_uppercase + string.digits, k=2))
  35.    return f"{prefix}{core}{suffix}"
  36.  
  37. def _get_db_conn(db_path=DB_PATH):
  38.    if not os.path.exists(db_path):
  39.        raise FileNotFoundError(f"DB not found at {db_path}")
  40.    return sqlite3.connect(db_path)
  41.  
  42. def get_attribute_properties(attr_name, db_path=DB_PATH):
  43.    conn = _get_db_conn(db_path)
  44.    cur = conn.cursor()
  45.    cur.execute("SELECT properties_json FROM attribute_properties WHERE attribute_name = ?", (attr_name,))
  46.    row = cur.fetchone()
  47.    conn.close()
  48.    if not row: return None
  49.    try:
  50.        return json.loads(row[0])
  51.    except Exception:
  52.        return row[0]
  53.  
  54. def get_dropdown_items(attr_name, db_path=DB_PATH):
  55.    props = get_attribute_properties(attr_name, db_path=db_path)
  56.    if not props or not isinstance(props, dict): return []
  57.    for key in ("DropdownItems","dropdownitems","dropdown_items","dropdown"):
  58.        if key in props:
  59.            val = props[key]
  60.            if isinstance(val, list): return val
  61.            try:
  62.                parsed = json.loads(val)
  63.                if isinstance(parsed, list): return parsed
  64.            except Exception:
  65.                pass
  66.    return []
  67.  
  68. def get_default_value(attr_name, db_path=DB_PATH):
  69.    props = get_attribute_properties(attr_name, db_path=db_path)
  70.    if not props or not isinstance(props, dict): return None
  71.    for key in ("DefaultValue","Default","defaultvalue","default"):
  72.        if key in props: return props[key]
  73.    return None
  74.  
  75. def is_flag_true(attr_name, flag, db_path=DB_PATH):
  76.    props = get_attribute_properties(attr_name, db_path=db_path)
  77.    if not props or not isinstance(props, dict): return False
  78.    if flag in props: return bool(props[flag])
  79.    alt = flag.replace(" ", "").replace("_","").lower()
  80.    for k,v in props.items():
  81.        if k.replace(" ","").replace("_","").lower() == alt:
  82.            return bool(v)
  83.    return False
  84.  
  85. # ---------- Phase2 DB helpers (embedded) ----------
  86. def ensure_work_tables(db_path=DB_PATH):
  87.    conn = _get_db_conn(db_path); cur = conn.cursor()
  88.    cur.execute("""CREATE TABLE IF NOT EXISTS work_properties (
  89.        work_id TEXT PRIMARY KEY, user_name TEXT, properties_json TEXT, created_at TEXT)""")
  90.    conn.commit(); conn.close()
  91.  
  92. def list_attributes(db_path=DB_PATH):
  93.    conn = _get_db_conn(db_path); cur = conn.cursor()
  94.    cur.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='Attributes'")
  95.    if not cur.fetchone():
  96.        conn.close(); return []
  97.    cur.execute("SELECT attributeName FROM Attributes ORDER BY attributeID")
  98.    rows = [r[0] for r in cur.fetchall()]; conn.close(); return rows
  99.  
  100. def insert_final_work(work_id, user_name, properties_dict, db_path=DB_PATH):
  101.    conn = _get_db_conn(db_path); cur = conn.cursor()
  102.    cur.execute("INSERT OR REPLACE INTO work_properties (work_id, user_name, properties_json, created_at) VALUES (?, ?, ?, ?)",
  103.                (work_id, user_name, json.dumps(properties_dict, ensure_ascii=False), datetime.datetime.utcnow().isoformat()))
  104.    conn.commit(); conn.close()
  105.  
  106. # ---------- GUI widget constructors ----------
  107. def DrawTheDateEntry(frame, attr_name, default=None):
  108.    lbl = ttk.Label(frame, text=attr_name + " (Date):")
  109.    ent = ttk.Entry(frame)
  110.    if default:
  111.        ent.insert(0, default)
  112.    lbl.pack(fill="x", padx=4, pady=(4,0))
  113.    ent.pack(fill="x", padx=4, pady=(0,6))
  114.    return ent
  115.  
  116. def DrawEntryWidget(frame, attr_name, default=None):
  117.    lbl = ttk.Label(frame, text=attr_name + ":")
  118.    ent = ttk.Entry(frame)
  119.    if default:
  120.        ent.insert(0, default)
  121.    lbl.pack(fill="x", padx=4, pady=(4,0))
  122.    ent.pack(fill="x", padx=4, pady=(0,6))
  123.    return ent
  124.  
  125. def DrawTheCombobox(frame, attr_name, items, default=None):
  126.    lbl = ttk.Label(frame, text=attr_name + " (Select):")
  127.    combo = ttk.Combobox(frame, values=items)
  128.    if default:
  129.        combo.set(default)
  130.    lbl.pack(fill="x", padx=4, pady=(4,0))
  131.    combo.pack(fill="x", padx=4, pady=(0,6))
  132.    btn = ttk.Button(frame, text="Add item", command=lambda: handleAddDropdownItem(attr_name, combo))
  133.    btn.pack(anchor="e", padx=4, pady=(0,6))
  134.    return combo
  135.  
  136. def handleAddDropdownItem(attr_name, combobox_widget):
  137.    new_item = simpledialog.askstring("Add dropdown item", f"New item for {attr_name}:")
  138.    if not new_item: return
  139.    props = get_attribute_properties(attr_name) or {}
  140.    items = props.get("DropdownItems", [])
  141.    if not isinstance(items, list): items = []
  142.    items.append(new_item)
  143.    props["DropdownItems"] = items
  144.    conn = _get_db_conn()
  145.    cur = conn.cursor()
  146.    cur.execute("UPDATE attribute_properties SET properties_json = ? WHERE attribute_name = ?", (json.dumps(props, ensure_ascii=False), attr_name))
  147.    conn.commit(); conn.close()
  148.    combobox_widget['values'] = items
  149.    combobox_widget.set(new_item)
  150.    messagebox.showinfo("Added", f"Added '{new_item}' to {attr_name} dropdown items.")
  151.  
  152. # ---------- Main form builder ----------
  153. class DynamicFormApp:
  154.    def __init__(self, master, user_name="default"):
  155.        self.master = master
  156.        self.user_name = user_name
  157.        master.title("WDYD Dynamic Form")
  158.        ensure_work_tables()
  159.        self.cfg = load_config()
  160.        self.universal = self._build_universal_dict()
  161.        self.mandatory_attrs = self.universal.get("Mandatory", [])
  162.        if not self.mandatory_attrs:
  163.            self.mandatory_attrs = list_attributes()
  164.        self.widgets = {}
  165.        self._build_ui()
  166.  
  167.    def _build_universal_dict(self):
  168.        keys = ["Mandatory","HasDropdown","IsDate","HasDefault","HasBinded","CanHaveMultipleValueInLifetime"]
  169.        d = {k: [] for k in keys}
  170.        conn = _get_db_conn(); cur = conn.cursor()
  171.        cur.execute("SELECT attribute_name, properties_json FROM attribute_properties")
  172.        for name, pjson in cur.fetchall():
  173.            try:
  174.                props = json.loads(pjson)
  175.            except Exception:
  176.                continue
  177.            for k in keys:
  178.                for pk, pv in props.items():
  179.                    if pk.replace(" ", "").lower() == k.replace(" ",").lower():
  180.                        if pv:
  181.                            d[k].append(name)
  182.                        break
  183.        conn.close()
  184.        return d
  185.  
  186.    def _build_ui(self):
  187.        style = tb.Style(theme="litera")
  188.        frame = ttk.Frame(self.master, padding=12)
  189.        frame.pack(fill="both", expand=True)
  190.        form_area = ttk.Frame(frame)
  191.        form_area.pack(fill="both", expand=True)
  192.        for attr in self.mandatory_attrs:
  193.            if is_flag_true(attr, "IsDate"):
  194.                default = get_default_value(attr)
  195.                wid = DrawTheDateEntry(form_area, attr, default=default)
  196.            elif is_flag_true(attr, "HasDropdown"):
  197.                items = get_dropdown_items(attr)
  198.                default = get_default_value(attr)
  199.                wid = DrawTheCombobox(form_area, attr, items, default=default)
  200.            else:
  201.                default = get_default_value(attr)
  202.                wid = DrawEntryWidget(form_area, attr, default=default)
  203.            self.widgets[attr] = wid
  204.        btn = ttk.Button(frame, text="Submit", bootstyle="success", command=self.submit)
  205.        btn.pack(pady=8)
  206.  
  207.    def submit(self):
  208.        data = {}
  209.        for attr, widget in self.widgets.items():
  210.            try:
  211.                val = widget.get()
  212.            except Exception:
  213.                val = ""
  214.            data[attr] = val
  215.        wid = formWorkID()
  216.        insert_final_work(wid, self.user_name, data)
  217.        messagebox.showinfo("Saved", f"Work saved with ID: {wid}")
  218.  
  219. def main():
  220.    root = tb.Window(themename="litera")
  221.    app = DynamicFormApp(root)
  222.    root.mainloop()
  223.  
  224. if __name__ == "__main__":
  225.    main()
  226. '''
  227.  
  228. try:
  229.     with open(OUTFILE, "w", encoding="utf-8") as f:
  230.         f.write(code)
  231.     created = True
  232. except Exception as e:
  233.     created = False
  234.     err = str(e)
  235.  
  236. {"created_file": OUTFILE, "created": created, "error": err if not created else None}
Advertisement
Add Comment
Please, Sign In to add comment