petertulip86 commited on
Commit
e9c6277
·
verified ·
1 Parent(s): 16f3cb0

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +150 -0
app.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ from bs4 import BeautifulSoup
3
+ import pandas as pd
4
+ import gradio as gr
5
+
6
+ def fetch_occupancy_data(hospital_id="10", floor=""):
7
+ """
8
+ 爬取奇美醫院佔床率資料
9
+
10
+ Args:
11
+ hospital_id (str): 醫院ID,默認為"10"(總院)
12
+ floor (str): 樓層篩選,默認為空
13
+
14
+ Returns:
15
+ tuple: (DataFrame, str) - 佔床資料的DataFrame和狀態訊息
16
+ """
17
+ # URL of the page to scrape
18
+ url = f"https://www.chimei.org.tw/%E4%BD%94%E5%BA%8A%E7%8E%87%E6%9F%A5%E8%A9%A2/%E4%BD%94%E5%BA%8A%E7%8E%87%E6%9F%A5%E8%A9%A2.aspx?ihospital={hospital_id}&ffloor={floor}"
19
+
20
+ try:
21
+ # Send HTTP request
22
+ response = requests.get(url)
23
+ response.encoding = 'utf-8' # Set encoding to handle Chinese characters
24
+
25
+ # Create BeautifulSoup object
26
+ soup = BeautifulSoup(response.text, 'html.parser')
27
+
28
+ # Find the target table (DG1)
29
+ target_table = soup.find('table', {'id': 'DG1'})
30
+
31
+ # Extract data from the table
32
+ data = []
33
+ if target_table:
34
+ rows = target_table.find_all('tr')
35
+
36
+ # Skip the header row
37
+ for row in rows[1:]:
38
+ cols = row.find_all('td')
39
+ if len(cols) == 5: # Ensure row has 5 columns
40
+ bed_type = cols[0].text.strip()
41
+ total_beds = int(cols[1].text.strip())
42
+ occupied_beds = int(cols[2].text.strip())
43
+ available_beds = int(cols[3].text.strip())
44
+ occupancy_rate = cols[4].text.strip()
45
+
46
+ data.append({
47
+ '病床類別': bed_type,
48
+ '總床數': total_beds,
49
+ '佔床數': occupied_beds,
50
+ '空床數': available_beds,
51
+ '佔床率': occupancy_rate
52
+ })
53
+
54
+ # Create pandas DataFrame
55
+ df = pd.DataFrame(data)
56
+
57
+ if df.empty:
58
+ return None, "無法獲取資料,請檢查網絡連接或醫院ID。"
59
+
60
+ return df, "資料獲取成功!"
61
+
62
+ except Exception as e:
63
+ return None, f"發生錯誤: {str(e)}"
64
+
65
+ def create_visualization(df):
66
+ """
67
+ 建立資料視覺化圖表
68
+
69
+ Args:
70
+ df (DataFrame): 佔床率資料
71
+
72
+ Returns:
73
+ matplotlib.figure.Figure: 視覺化圖表
74
+ """
75
+ if df is None or df.empty:
76
+ return None
77
+
78
+ # 建立佔床率圖表
79
+ fig = df.plot(x='病床類別', y=['佔床數', '空床數'], kind='bar', stacked=True,
80
+ figsize=(10, 6), title='奇美醫院各類病床佔用情況').get_figure()
81
+
82
+ return fig
83
+
84
+ def process_query(hospital_id, floor):
85
+ """
86
+ 處理使用者查詢
87
+
88
+ Args:
89
+ hospital_id (str): 醫院ID
90
+ floor (str): 樓層篩選
91
+
92
+ Returns:
93
+ tuple: (DataFrame HTML, 圖表, 訊息)
94
+ """
95
+ df, message = fetch_occupancy_data(hospital_id, floor)
96
+
97
+ if df is not None:
98
+ fig = create_visualization(df)
99
+ html_table = df.to_html(classes="table table-striped", index=False)
100
+ return html_table, fig, message
101
+ else:
102
+ return None, None, message
103
+
104
+ # 定義Gradio介面
105
+ with gr.Blocks(title="奇美醫院佔床率查詢系統") as app:
106
+ gr.Markdown("# 奇美醫院佔床率查詢系統")
107
+ gr.Markdown("該系統可以即時查詢奇美醫院各類病床的佔用情況")
108
+
109
+ with gr.Row():
110
+ with gr.Column(scale=1):
111
+ # 輸入欄位
112
+ hospital_id = gr.Dropdown(
113
+ choices=[
114
+ ("總院", "10"),
115
+ ("柳營分院", "20"),
116
+ ("佳里分院", "30"),
117
+ ("鹽埕分院", "40")
118
+ ],
119
+ value="10",
120
+ label="選擇醫院"
121
+ )
122
+
123
+ floor = gr.Textbox(label="樓層篩選 (可選)", placeholder="例如:3F、5F")
124
+
125
+ query_btn = gr.Button("查詢佔床率", variant="primary")
126
+
127
+ with gr.Column(scale=2):
128
+ # 輸出欄位
129
+ output_message = gr.Textbox(label="查詢狀態")
130
+ output_table = gr.HTML(label="佔床率資料表")
131
+ output_chart = gr.Plot(label="佔床情況視覺化")
132
+
133
+ # 設定查詢按鈕動作
134
+ query_btn.click(
135
+ fn=process_query,
136
+ inputs=[hospital_id, floor],
137
+ outputs=[output_table, output_chart, output_message]
138
+ )
139
+
140
+ gr.Markdown("### 使用說明")
141
+ gr.Markdown("""
142
+ 1. 從下拉選單選擇要查詢的醫院
143
+ 2. 可選擇性地輸入特定樓層進行篩選
144
+ 3. 點擊"查詢佔床率"按鈕獲取最新資料
145
+ 4. 系統會顯示表格和視覺化圖表
146
+ """)
147
+
148
+ # 啟動Gradio應用
149
+ if __name__ == "__main__":
150
+ app.launch()