Kung-Hsun commited on
Commit
1f3c5ee
·
verified ·
1 Parent(s): d6b3324

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -151
app.py CHANGED
@@ -1964,160 +1964,74 @@ def run_multi_y(before_file, after_file, linear, nonlinear, ylist, add_inter, ad
1964
 
1965
  # [自動function管理核心]
1966
  import re
 
1967
 
1968
- def summarize_tab_function_usage(pyfile):
1969
- """
1970
- 讀取 Python app 檔案,輸出各 Gradio 分頁(Tab)呼叫到的 function 對照表。
1971
- """
1972
- with open(pyfile, "r", encoding="utf-8") as f:
1973
- code = f.read()
1974
-
1975
- # 支援 gr.TabItem("名稱") 或 gr.Tab("名稱")
1976
- tab_blocks = []
1977
- tab_pattern = re.compile(
1978
- r'with gr\.Tab(Item)?\(\s*[\'"]([^\'"]+)[\'"]\s*\)\s*:\s*((?:\n[ \t]+.*?)+)(?=\nwith gr\.Tab|\n# |\Z)',
1979
- re.DOTALL
1980
- )
1981
- for match in tab_pattern.finditer(code):
1982
- tab_title = match.group(2).strip()
1983
- tab_code = match.group(3)
1984
- tab_blocks.append((tab_title, tab_code))
1985
-
1986
- # 抓每個 tab 內 click/change/callback 事件使用到的 function
1987
- event_pattern = re.compile(r'\.(click|change|submit)\(\s*([a-zA-Z0-9_]+)', re.MULTILINE)
1988
- tab_func_map = {}
1989
- for tab_title, tab_code in tab_blocks:
1990
  funcs = set()
1991
- for event_match in event_pattern.finditer(tab_code):
1992
- func = event_match.group(2)
1993
- if func:
1994
- funcs.add(func)
1995
- tab_func_map[tab_title] = sorted(funcs)
1996
-
1997
- # 組合成 markdown
1998
- summary = "# 📋 分頁(Function)呼叫對照表\n"
1999
- for tab, funcs in tab_func_map.items():
2000
- summary += f"\n## [{tab}]\n"
 
 
 
2001
  if funcs:
2002
- summary += "\n".join([f"- {func}" for func in funcs]) + "\n"
 
 
2003
  else:
2004
- summary += "- 本Tab未直接偵測到function事件\n"
2005
- return summary
 
2006
 
2007
- import re
2008
- import os
2009
-
2010
- def map_ui_to_function(pyfile=None):
2011
- """
2012
- 掃描本地 app.py,建立主UI元件到 function 的 mapping。
2013
- """
2014
- # 找當前目錄下的 app.py
2015
- if not pyfile:
2016
- pyfile = "app.py"
2017
- if not os.path.exists(pyfile):
2018
- # 嘗試在 /mnt/data/ 這類目錄(如Colab、雲部署路徑)
2019
- for d in ["/mnt/data/", "/home/user/app/"]:
2020
- try_path = os.path.join(d, "app.py")
2021
- if os.path.exists(try_path):
2022
- pyfile = try_path
2023
- break
2024
- if not os.path.exists(pyfile):
2025
- return "⚠️ 找不到 app.py,請確認本目錄存在 app.py!"
2026
-
2027
- with open(pyfile, "r", encoding="utf-8") as f:
2028
- code = f.read()
2029
-
2030
- # 1. 掃所有主UI元件(常見 gr.* 元件,並取得其「變數名」與型態、label)
2031
- ui_pattern = re.compile(
2032
- r'(\w+)\s*=\s*gr\.(\w+)\(([^#\n)]*)\)', re.MULTILINE
2033
- )
2034
- ui_map = {}
2035
- for m in ui_pattern.finditer(code):
2036
- var, ui_type, params = m.groups()
2037
- # 取 label 參數(有可能在多個位置/行)
2038
- label = ""
2039
- label_match = re.search(r'label\s*=\s*[\'"]([^\'"]+)[\'"]', params)
2040
- if label_match:
2041
- label = label_match.group(1)
2042
- ui_map[var] = {"type": ui_type, "label": label}
2043
-
2044
- # 2. 找所有互動事件,與function對應
2045
- # ex: btn.click(func, ...)
2046
- event_pattern = re.compile(
2047
- r'(\w+)\s*\.\s*(click|change|submit)\s*\(\s*([a-zA-Z0-9_]+)', re.MULTILINE
2048
- )
2049
- event_map = {} # {元件: [function...]}
2050
- for m in event_pattern.finditer(code):
2051
- var, evt, func = m.groups()
2052
- event_map.setdefault(var, []).append({"event": evt, "func": func})
2053
-
2054
- # 3. 整合 mapping 輸出
2055
- result = "# 🗂️ 主UI元件 ➔ function mapping\n"
2056
- for var, uiinfo in ui_map.items():
2057
- uitype = uiinfo["type"]
2058
- label = uiinfo["label"]
2059
- events = event_map.get(var, [])
2060
- result += f"\n## {var} ({uitype})\n"
2061
- if label:
2062
- result += f"- **Label**: `{label}`\n"
2063
- if events:
2064
- for ev in events:
2065
- result += f"- 觸發 `{ev['event']}` → **{ev['func']}**\n"
2066
- else:
2067
- result += "- 無發現綁定事件\n"
2068
- return result
2069
-
2070
-
2071
- import re
2072
-
2073
- def tab_function_mapping(pyfile="app.py"):
2074
- # 讀入代碼
2075
  try:
2076
  with open(pyfile, encoding="utf-8") as f:
2077
  code = f.read()
2078
  except Exception as e:
2079
- return f"❌ 無法讀取 {pyfile}:{e}"
2080
-
2081
- # 找所有Tab開頭
2082
- tab_blocks = []
2083
- for m in re.finditer(r'with\s+gr\.Tab\((?P<name>.+?)\)\s*:\s*\n(?P<block>(?:[ \t]+.+\n)+)', code):
2084
- tab_name = m.group("name").strip().strip('"').strip("'")
2085
- block = m.group("block")
2086
- tab_blocks.append((tab_name, block))
2087
-
2088
- # 補抓 gr.TabItem() 寫法
2089
- for m in re.finditer(r'with\s+gr\.TabItem\((?P<name>.+?)\)\s*:\s*\n(?P<block>(?:[ \t]+.+\n)+)', code):
2090
- tab_name = m.group("name").strip().strip('"').strip("'")
2091
- block = m.group("block")
2092
- tab_blocks.append((tab_name, block))
2093
-
2094
- # 抓各Tab區塊內定義的UI元件(變數名)
2095
- tab_to_vars = {}
2096
- var_regex = re.compile(r'^\s*([\w\d_]+)\s*=\s*gr\.\w+\(', re.MULTILINE)
2097
- for tab_name, block in tab_blocks:
2098
- varlist = var_regex.findall(block)
2099
- tab_to_vars[tab_name] = varlist
2100
-
2101
- # 抓全檔的 function 綁定(btn.click(func, ...)、xxx.change(func...))
2102
- event_calls = re.findall(r'([\w\d_]+)\s*\.\s*(click|change|submit)\s*\(\s*([a-zA-Z_][\w\d_]*)', code)
2103
- var_to_func = {}
2104
- for var, evt, func in event_calls:
2105
- var_to_func.setdefault(var, []).append((evt, func))
2106
-
2107
- # 組合結果:Tab ➔ (UI元件, function)
2108
- res = "# 📋 **分頁(Tab) ➔ function呼叫 mapping**\n\n"
2109
- for tab_name, varlist in tab_to_vars.items():
2110
- res += f"## 🏷️ {tab_name}\n"
2111
- found = False
2112
- for v in varlist:
2113
- if v in var_to_func:
2114
- found = True
2115
- for evt, func in var_to_func[v]:
2116
- res += f"- **{v}** (`{evt}`) ➔ `{func}`\n"
2117
- if not found:
2118
- res += "- 無綁定事件function\n"
2119
- res += "\n"
2120
- return res
2121
 
2122
  # ======================== Gradio 多分頁主UI ========================
2123
 
@@ -2603,13 +2517,14 @@ with gr.Blocks(css=custom_css) as demo:
2603
  """)
2604
 
2605
 
2606
- with gr.Tab("🧩 Function管理") as func_tab:
2607
- gr.Markdown("#### 各分頁(Tab)自動列出該頁有用到的function及觸發元件")
2608
- func_btn = gr.Button("立即分析")
 
2609
  func_out = gr.Markdown()
2610
- def analyze_func(_):
2611
- return tab_function_mapping()
2612
- func_btn.click(analyze_func, inputs=[func_btn], outputs=[func_out])
2613
 
2614
 
2615
  gr.Markdown("<div id='footer'> 本平台由T100團隊設計,歡迎交流建議 │ 2025_</div>")
 
1964
 
1965
  # [自動function管理核心]
1966
  import re
1967
+ import gradio as gr
1968
 
1969
+ # ===== (1) 自動解析:每個Tab呼叫哪些function =====
1970
+ def tab_function_mapping(pyfile="app.py"):
1971
+ try:
1972
+ with open(pyfile, encoding="utf-8") as f:
1973
+ code = f.read()
1974
+ except Exception as e:
1975
+ return f"❌ 讀取 {pyfile} 失敗:{e}"
1976
+
1977
+ # 抓出所有TabItem
1978
+ tab_pattern = re.compile(r'with gr\.TabItem\(["\'](.+?)["\']\):([\s\S]*?)(?=with gr\.TabItem|\Z)', re.MULTILINE)
1979
+ # 抓出 .click(fn=...) or .click(...)
1980
+ click_pattern = re.compile(r'\.click\(\s*(?:[a-zA-Z_][\w\d_]*)|\.click\(\s*fn\s*=\s*([a-zA-Z_][\w\d_]*)', re.MULTILINE)
1981
+ # 可再加 .change(fn=xxx)... 視你UI元件有無用
1982
+ change_pattern = re.compile(r'\.change\(\s*(?:[a-zA-Z_][\w\d_]*)|\.change\(\s*fn\s*=\s*([a-zA-Z_][\w\d_]*)', re.MULTILINE)
1983
+
1984
+ output = "## 🧩 分頁(Tab) ➔ function mapping\n\n"
1985
+ for m in tab_pattern.finditer(code):
1986
+ tab_name, tab_code = m.group(1), m.group(2)
 
 
 
 
1987
  funcs = set()
1988
+ # .click
1989
+ for c in click_pattern.findall(tab_code):
1990
+ if isinstance(c, tuple):
1991
+ c = [x for x in c if x][0] if any(c) else None
1992
+ if c and c != "lambda":
1993
+ funcs.add(c)
1994
+ # .change
1995
+ for c in change_pattern.findall(tab_code):
1996
+ if isinstance(c, tuple):
1997
+ c = [x for x in c if x][0] if any(c) else None
1998
+ if c and c != "lambda":
1999
+ funcs.add(c)
2000
+ output += f"### {tab_name}\n"
2001
  if funcs:
2002
+ output += "- 觸發 function:\n"
2003
+ for fn in sorted(funcs):
2004
+ output += f" - `{fn}`\n"
2005
  else:
2006
+ output += "- (本Tab未發現function直接綁定)\n"
2007
+ output += "\n"
2008
+ return output
2009
 
2010
+ # ===== (2) 自動擷取所有 function 定義 (含說明) =====
2011
+ def scan_functions(pyfile="app.py"):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2012
  try:
2013
  with open(pyfile, encoding="utf-8") as f:
2014
  code = f.read()
2015
  except Exception as e:
2016
+ return f"❌ 讀取 {pyfile} 失敗:{e}"
2017
+ func_pattern = re.compile(
2018
+ r"^(def [a-zA-Z_][\w\d_]*\(.*?\):(?:\n(?: |\t).*)*)",
2019
+ re.MULTILINE
2020
+ )
2021
+ output = "## 📃 所有 function 定義 (def...)\n\n"
2022
+ matches = func_pattern.findall(code)
2023
+ if not matches:
2024
+ return "❗ 沒有抓到任何 function (def)!"
2025
+ for func in matches:
2026
+ func_name = re.match(r"def ([a-zA-Z_][\w\d_]*)", func)
2027
+ output += f"---\n### `{func_name.group(1) if func_name else '?'}()`\n"
2028
+ # 顯示前3行(含def)與註解,長的顯示收折
2029
+ func_lines = func.split("\n")
2030
+ if len(func_lines) > 8:
2031
+ output += "```python\n" + "\n".join(func_lines[:8]) + "\n... (略)\n```\n"
2032
+ else:
2033
+ output += "```python\n" + func + "\n```\n"
2034
+ return output
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2035
 
2036
  # ======================== Gradio 多分頁主UI ========================
2037
 
 
2517
  """)
2518
 
2519
 
2520
+ with gr.Tab("🧩 Function管理"):
2521
+ gr.Markdown("#### 各分頁(Tab) ➔ function 對應 & 全 function 定義一覽(自動讀取 app.py,不需上傳)")
2522
+ analyze_btn = gr.Button("立即分析 (自動讀取app.py)")
2523
+ tab_out = gr.Markdown()
2524
  func_out = gr.Markdown()
2525
+ def do_full_analyze(_):
2526
+ return tab_function_mapping(), scan_functions()
2527
+ analyze_btn.click(do_full_analyze, None, [tab_out, func_out])
2528
 
2529
 
2530
  gr.Markdown("<div id='footer'> 本平台由T100團隊設計,歡迎交流建議 │ 2025_</div>")