ELVISIO commited on
Commit
efa0177
·
verified ·
1 Parent(s): b0d74e7

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +72 -0
app.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import pandas as pd
4
+ from markdown import markdown
5
+ from bs4 import BeautifulSoup
6
+
7
+ # 獲取管理員密碼(從系統環境變量中讀取)
8
+ ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD", "admin123") # 默認密碼是 "admin123",可通過環境變量設置。
9
+
10
+ # 提取 Markdown 第一行並轉化為文本
11
+ def parse_markdown(markdown_string):
12
+ # 將 Markdown 轉化為 HTML
13
+ html_content = markdown(markdown_string)
14
+ # 使用 BeautifulSoup 提取 HTML 內容中的文本
15
+ soup = BeautifulSoup(html_content, "html.parser")
16
+ # 提取第一行文本
17
+ first_line = soup.text.split("\n")[0]
18
+ return first_line
19
+
20
+ # 管理員模式:接收上傳的 Excel 文件並返回第一行的分析
21
+ def admin_mode(password, file):
22
+ if password != ADMIN_PASSWORD:
23
+ return "密碼錯誤,無法進入管理員模式。"
24
+ if file is None:
25
+ return "請上傳一個 Excel 文件。"
26
+ try:
27
+ # 讀取 Excel 文件
28
+ df = pd.read_excel(file)
29
+ # 提取 "Output" 和 "Initial Output" 列並返回第一行
30
+ output_first_line = parse_markdown(str(df["Output"].iloc[0])) if "Output" in df.columns else "Output 列不存在。"
31
+ initial_output_first_line = parse_markdown(str(df["Initial Output"].iloc[0])) if "Initial Output" in df.columns else "Initial Output 列不存在。"
32
+ return f"Output 第一行: {output_first_line}\nInitial Output 第一行: {initial_output_first_line}"
33
+ except Exception as e:
34
+ return f"處理文件時發生錯誤:{str(e)}"
35
+
36
+ # 用戶模式:使用預設的 Excel 文件進行分析
37
+ def user_mode():
38
+ # 假設預設的 Excel 文件在當前目錄下,文件名為 "default.xlsx"
39
+ default_excel_path = "default.xlsx"
40
+ if not os.path.exists(default_excel_path):
41
+ return "預設的 Excel 文件不存在。"
42
+ try:
43
+ # 讀取 Excel 文件
44
+ df = pd.read_excel(default_excel_path)
45
+ # 提取 "Output" 和 "Initial Output" 列並返回第一行
46
+ output_first_line = parse_markdown(str(df["Output"].iloc[0])) if "Output" in df.columns else "Output 列不存在。"
47
+ initial_output_first_line = parse_markdown(str(df["Initial Output"].iloc[0])) if "Initial Output" in df.columns else "Initial Output 列不存在。"
48
+ return f"Output 第一行: {output_first_line}\nInitial Output 第一行: {initial_output_first_line}"
49
+ except Exception as e:
50
+ return f"處理文件時發生錯誤:{str(e)}"
51
+
52
+ # Gradio 界面
53
+ def main(password, file):
54
+ if password: # 如果輸入了密碼,進入管理員模式
55
+ return admin_mode(password, file)
56
+ else: # 否則進入用戶模式
57
+ return user_mode()
58
+
59
+ # 設置 Gradio 介面
60
+ iface = gr.Interface(
61
+ fn=main,
62
+ inputs=[
63
+ gr.Textbox(label="管理員密碼", placeholder="輸入密碼以進入管理員模式(可選)"),
64
+ gr.File(label="上傳 Excel 文件(僅管理員模式需要)"),
65
+ ],
66
+ outputs=gr.Textbox(label="分析結果"),
67
+ title="問卷調查系統",
68
+ description="輸入密碼以進入管理員模式,或留空以進入用戶模式。管理員模式可上傳自定義的 Excel 文件,用戶模式會使用預設的 Excel 文件進行分析。",
69
+ )
70
+
71
+ # 啟動應用
72
+ iface.launch()