Roberta2024 commited on
Commit
31905b8
·
verified ·
1 Parent(s): 24e354c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +179 -0
app.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ from bs4 import BeautifulSoup
3
+ import requests
4
+ import streamlit as st
5
+ import plotly.express as px
6
+ import io
7
+ import tempfile
8
+
9
+ # Function to send messages and images via LINE
10
+ def send_line_message(channel_access_token, user_id, df, img_paths):
11
+ line_bot_api = LineBotApi(channel_access_token)
12
+
13
+ # Send DataFrame as a text message
14
+ text_message = TextSendMessage(text=df.to_string())
15
+ line_bot_api.push_message(user_id, text_message)
16
+
17
+ # Send images
18
+ for img_path in img_paths:
19
+ image_message = ImageSendMessage(original_content_url=img_path, preview_image_url=img_path)
20
+ line_bot_api.push_message(user_id, image_message)
21
+
22
+ def fetch_table_data(url, table_id, has_header=True, rename_columns=None, drop_columns=None, custom_columns=None):
23
+ response = requests.get(url)
24
+ soup = BeautifulSoup(response.text, "html.parser")
25
+ table = soup.find("table", {"id": table_id})
26
+
27
+ if not table:
28
+ st.warning(f"在 {url} 中找不到 ID 為 {table_id} 的表格")
29
+ return pd.DataFrame()
30
+
31
+ rows = table.find_all("tr")
32
+
33
+ if not rows:
34
+ st.warning(f"在 {url} 中,ID 為 {table_id} 的表格中找不到任何行")
35
+ return pd.DataFrame()
36
+
37
+ if has_header:
38
+ columns = [th.text.strip() for th in rows[0].find_all("th")]
39
+ data = []
40
+ for row in rows[1:]:
41
+ row_data = [td.text.strip() for td in row.find_all("td")]
42
+ if row_data:
43
+ data.append(row_data)
44
+ else:
45
+ columns = custom_columns
46
+ data = []
47
+ for row in rows:
48
+ row_data = [td.text.strip() for td in row.find_all("td")]
49
+ if row_data:
50
+ data.append(row_data)
51
+
52
+ if not data:
53
+ st.warning(f"在 {url} 中,ID 為 {table_id} 的表格中找不到任何資料行")
54
+ return pd.DataFrame()
55
+
56
+ if len(columns) > 0:
57
+ for i, row in enumerate(data):
58
+ if len(row) != len(columns):
59
+ st.warning(f"資料行 {i+1} 的列數與標題列數不一致:{len(row)} vs {len(columns)}")
60
+ return pd.DataFrame()
61
+
62
+ df = pd.DataFrame(data, columns=columns)
63
+
64
+ if rename_columns:
65
+ df = df.rename(columns=rename_columns)
66
+ if drop_columns:
67
+ df = df.drop(columns=drop_columns)
68
+
69
+ return df
70
+
71
+ def calculate_stats(df):
72
+ df["病床數"] = pd.to_numeric(df["病床數"], errors='coerce')
73
+ df["佔床數"] = pd.to_numeric(df["佔床數"], errors='coerce')
74
+ df["空床數"] = df["病床數"] - df["佔床數"]
75
+
76
+ total_beds = df["病床數"].sum()
77
+ occupied_beds = df["佔床數"].sum()
78
+ occupancy_rate = (occupied_beds / total_beds) * 100 if total_beds > 0 else 0
79
+
80
+ return total_beds, occupied_beds, occupancy_rate
81
+
82
+ def main():
83
+ st.title("醫院病床狀態查詢")
84
+
85
+ url1 = "https://www.tmh.org.tw/tmh2016/ImpBD.aspx?Kind=2"
86
+ url2 = "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=10&ffloor="
87
+ url3 = "https://web.hosp.ncku.edu.tw/nckm/Bedstatus/BedStatus.aspx"
88
+
89
+ table_id1 = "ctl00_ContentPlaceHolder1_GV_Bed"
90
+ table_id2 = "DG1"
91
+ table_id3 = "GV_EmgInsure"
92
+
93
+ df1 = fetch_table_data(url1, table_id1, rename_columns={'床位別數':'病床數', '住院人數':'佔床數'}, drop_columns=['佔床率'])
94
+ df2 = fetch_table_data(url2, table_id2, has_header=False, custom_columns=["病床類別", "病床數", "佔床數", "空床數", "佔床率"], drop_columns=['佔床率'])
95
+ df3 = fetch_table_data(url3, table_id3)
96
+
97
+ if not df1.empty:
98
+ df1 = df1.rename(columns={'病床種類':'病床類別'})
99
+ df1['醫院'] = '台南市立醫院'
100
+
101
+ if not df2.empty:
102
+ df2 = df2.drop(index=0)
103
+ df2['醫院'] = '奇美醫院'
104
+
105
+ if not df3.empty:
106
+ df3['醫院'] = '成大醫院'
107
+
108
+ combined_df = pd.concat([df for df in [df1, df2, df3] if not df.empty], ignore_index=True)
109
+
110
+ hospital_choice = st.selectbox(
111
+ "選擇醫院或顯示合併數據",
112
+ ("台南市立醫院", "奇美醫院", "成大醫院", "三間醫院合併顯示")
113
+ )
114
+
115
+ def plot_hospital_data(df, hospital_name):
116
+ total_beds, occupied_beds, occupancy_rate = calculate_stats(df)
117
+ st.subheader(hospital_name)
118
+ st.write(f"總病床數: {total_beds}")
119
+ st.write(f"佔床數: {occupied_beds}")
120
+ st.write(f"佔床率: {occupancy_rate:.2f}%")
121
+
122
+ df_long = df.melt(id_vars=["病床類別"], value_vars=["病床數", "佔床數", "空床數"],
123
+ var_name="類型", value_name="數量")
124
+
125
+ fig = px.bar(df_long, x="病床類別", y="數量", color="類型", barmode="group",
126
+ title=f"{hospital_name}病床狀況")
127
+ st.write(df)
128
+ st.plotly_chart(fig)
129
+
130
+ if hospital_choice == "台南市立醫院" and not df1.empty:
131
+ plot_hospital_data(df1, "台南市立醫��")
132
+
133
+ elif hospital_choice == "奇美醫院" and not df2.empty:
134
+ plot_hospital_data(df2, "奇美醫院")
135
+
136
+ elif hospital_choice == "成大醫院" and not df3.empty:
137
+ plot_hospital_data(df3, "成大醫院")
138
+
139
+ elif hospital_choice == "三間醫院合併顯示" and not combined_df.empty:
140
+ total_beds, occupied_beds, occupancy_rate = calculate_stats(combined_df)
141
+ st.subheader("合併後的數據")
142
+ st.write(f"總病床數: {total_beds}")
143
+ st.write(f"佔床數: {occupied_beds}")
144
+ st.write(f"佔床率: {occupancy_rate:.2f}%")
145
+
146
+ combined_df_long = combined_df.melt(id_vars=["醫院", "病床類別"],
147
+ value_vars=["病床數", "佔床數", "空床數"],
148
+ var_name="類型", value_name="數量")
149
+
150
+ fig = px.bar(combined_df_long, x="醫院", y="數量", color="類型", barmode="group",
151
+ title="合併後的病床狀況")
152
+ st.write(combined_df)
153
+ st.plotly_chart(fig)
154
+
155
+ # 新增三個按鈕並排放置,並放大圓餅圖尺寸
156
+ col1, col2, col3 = st.columns(3)
157
+
158
+ with col1:
159
+ if st.button("顯示圓餅圖:病床數"):
160
+ fig_pie = px.pie(combined_df, names="醫院", values="病床數", title="合併後各醫院病床總數分布")
161
+ fig_pie.update_layout(width=600, height=600) # 調整圓餅圖的尺寸
162
+ st.plotly_chart(fig_pie)
163
+
164
+ with col2:
165
+ if st.button("顯示圓餅圖:佔床數"):
166
+ fig_pie2 = px.pie(combined_df, names="醫院", values="佔床數", title="合併後各醫院佔床總數分布")
167
+ fig_pie2.update_layout(width=600, height=600) # 調整圓餅圖的尺寸
168
+ st.plotly_chart(fig_pie2)
169
+
170
+ with col3:
171
+ if st.button("顯示圓餅圖:空床數"):
172
+ fig_pie3 = px.pie(combined_df, names="醫院", values="空床數", title="合併後各醫院空床總數分布")
173
+ fig_pie3.update_layout(width=600, height=600) # 調整圓餅圖的尺寸
174
+ st.plotly_chart(fig_pie3)
175
+
176
+
177
+
178
+ if __name__ == "__main__":
179
+ main()