Roberta2024 commited on
Commit
b628f0a
·
verified ·
1 Parent(s): 6f0480e

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +78 -0
app.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ from bs4 import BeautifulSoup
3
+ import pandas as pd
4
+ import gradio as gr
5
+ from google.oauth2.service_account import Credentials
6
+ import gspread
7
+
8
+ def get_hospital_data(url):
9
+ # 發送GET請求獲取網頁內容
10
+ response = requests.get(url)
11
+ response.encoding = 'utf-8' # 設置正確的編碼
12
+
13
+ # 使用BeautifulSoup解析HTML
14
+ soup = BeautifulSoup(response.text, 'html.parser')
15
+
16
+ # 提取醫院名稱
17
+ hospital_name = soup.find('span', id='Lbl抬頭').text.strip()
18
+
19
+ # 提取查詢院區
20
+ queried_hospital = soup.find('span', id='Lbl結果').text.strip().split(':')[1].split()[0]
21
+
22
+ # 提取病床數據
23
+ table = soup.find('table', id='DG1')
24
+ rows = table.find_all('tr')[1:] # 跳過表頭
25
+
26
+ # 解析病床數據
27
+ bed_data = []
28
+ for row in rows:
29
+ cols = row.find_all('td')
30
+ if len(cols) == 5:
31
+ category = cols[0].text.strip()
32
+ total = int(cols[1].text.strip())
33
+ occupied = int(cols[2].text.strip())
34
+ available = int(cols[3].text.strip())
35
+ rate = float(cols[4].text.strip().rstrip('%'))
36
+ bed_data.append([category, total, occupied, available, rate])
37
+
38
+ # 創建DataFrame
39
+ df = pd.DataFrame(bed_data, columns=['病床類別', '總床數', '佔床數', '空床數', '佔床率'])
40
+
41
+ # 提取備註
42
+ remarks = []
43
+ for i in range(6):
44
+ remark = soup.find('span', id=f'Lbl備註{i}')
45
+ if remark:
46
+ remarks.append(remark.text.strip())
47
+
48
+ # 格式化輸出
49
+ result = f"{hospital_name}\n查詢院區: {queried_hospital}\n\n各類病床明細表:\n{df.to_string(index=False)}\n\n備註:\n" + "\n".join(remarks)
50
+
51
+ # 儲存 CSV 檔案
52
+ df.to_csv("CM2024.csv", encoding="utf-8-sig")
53
+
54
+ return result, df
55
+
56
+ def upload_to_google_sheets(df):
57
+ # Google Sheets API 認證
58
+ scope = ['https://www.googleapis.com/auth/spreadsheets']
59
+ creds = Credentials.from_service_account_file("/content/gdrive/My Drive/omega-wind-430312-e2-eb1dbac8ba3d.json", scopes=scope)
60
+ gs = gspread.authorize(creds)
61
+
62
+ # 打開 Google 試算表
63
+ sheet = gs.open_by_url('https://docs.google.com/spreadsheets/d/1puPO2mIwwTLSqQ-E3tB15vIl4WTclSRvHghdrwgeN9c/edit?gid=0#gid=0')
64
+ worksheet = sheet.get_worksheet(0)
65
+
66
+ # 轉換 DataFrame 為字串格式
67
+ df1 = df.astype(str)
68
+
69
+ # 更新試算表
70
+ worksheet.update([df1.columns.values.tolist()] + df1.values.tolist())
71
+
72
+ def gradio_interface(url):
73
+ result, df = get_hospital_data(url)
74
+ upload_to_google_sheets(df)
75
+ return result
76
+
77
+ iface = gr.Interface(fn=gradio_interface, inputs="text", outputs="text", title="Hospital Bed Data")
78
+ iface.launch()