import gradio as gr import os import pandas as pd from markdown import markdown from bs4 import BeautifulSoup # 獲取管理員密碼(從系統環境變量中讀取) ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD", "admin123") # 默認密碼是 "admin123",可通過環境變量設置。 # 提取 Markdown 第一行並轉化為文本 def parse_markdown(markdown_string): # 將 Markdown 轉化為 HTML html_content = markdown(markdown_string) # 使用 BeautifulSoup 提取 HTML 內容中的文本 soup = BeautifulSoup(html_content, "html.parser") # 提取第一行文本 first_line = soup.text.split("\n")[0] return first_line # 管理員模式:接收上傳的 Excel 文件並返回第一行的分析 def admin_mode(password, file): if password != ADMIN_PASSWORD: return "密碼錯誤,無法進入管理員模式。" if file is None: return "請上傳一個 Excel 文件。" try: # 讀取 Excel 文件 df = pd.read_excel(file) # 提取 "Output" 和 "Initial Output" 列並返回第一行 output_first_line = parse_markdown(str(df["Output"].iloc[0])) if "Output" in df.columns else "Output 列不存在。" initial_output_first_line = parse_markdown(str(df["Initial Output"].iloc[0])) if "Initial Output" in df.columns else "Initial Output 列不存在。" return f"Output 第一行: {output_first_line}\nInitial Output 第一行: {initial_output_first_line}" except Exception as e: return f"處理文件時發生錯誤:{str(e)}" # 用戶模式:使用預設的 Excel 文件進行分析 def user_mode(): # 假設預設的 Excel 文件在當前目錄下,文件名為 "default.xlsx" default_excel_path = "default.xlsx" if not os.path.exists(default_excel_path): return "預設的 Excel 文件不存在。" try: # 讀取 Excel 文件 df = pd.read_excel(default_excel_path) # 提取 "Output" 和 "Initial Output" 列並返回第一行 output_first_line = parse_markdown(str(df["Output"].iloc[0])) if "Output" in df.columns else "Output 列不存在。" initial_output_first_line = parse_markdown(str(df["Initial Output"].iloc[0])) if "Initial Output" in df.columns else "Initial Output 列不存在。" return f"Output 第一行: {output_first_line}\nInitial Output 第一行: {initial_output_first_line}" except Exception as e: return f"處理文件時發生錯誤:{str(e)}" # Gradio 界面 def main(password, file): if password: # 如果輸入了密碼,進入管理員模式 return admin_mode(password, file) else: # 否則進入用戶模式 return user_mode() # 設置 Gradio 介面 iface = gr.Interface( fn=main, inputs=[ gr.Textbox(label="管理員密碼", placeholder="輸入密碼以進入管理員模式(可選)"), gr.File(label="上傳 Excel 文件(僅管理員模式需要)"), ], outputs=gr.Textbox(label="分析結果"), title="問卷調查系統", description="輸入密碼以進入管理員模式,或留空以進入用戶模式。管理員模式可上傳自定義的 Excel 文件,用戶模式會使用預設的 Excel 文件進行分析。", ) # 啟動應用 iface.launch()