Rooobert commited on
Commit
7d40d46
·
verified ·
1 Parent(s): 2b10009

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +105 -0
app.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import plotly.express as px
4
+ from dataclasses import dataclass, field
5
+ import numpy as np
6
+ from typing import Dict, Tuple, Any
7
+
8
+ # 📥 讀取 Google 試算表函數
9
+ def read_google_sheet(sheet_id, sheet_number=0):
10
+ """📥 從 Google Sheets 讀取數據"""
11
+ url = f'https://docs.google.com/spreadsheets/d/{sheet_id}/export?format=csv&gid={sheet_number}'
12
+ try:
13
+ df = pd.read_csv(url)
14
+ return df
15
+ except Exception as e:
16
+ st.error(f"❌ 讀取失敗:{str(e)}")
17
+ return None
18
+
19
+ # 📊 Google Sheets ID
20
+ sheet_id = "1Wc15DZWq48MxL7nXAsROJ6sRvH5njSa1ea0aaOGUOVk"
21
+ gid = "1168424766"
22
+
23
+ @dataclass
24
+ class SurveyMappings:
25
+ """📋 問卷數據對應"""
26
+ gender: Dict[str, int] = field(default_factory=lambda: {'男性': 1, '女性': 2})
27
+ education: Dict[str, int] = field(default_factory=lambda: {
28
+ '國小(含)以下': 1, '國/初中': 2, '高中/職': 3, '專科': 4, '大學': 5, '研究所(含)以上': 6})
29
+ frequency: Dict[str, int] = field(default_factory=lambda: {
30
+ '第1次': 1, '2-3次': 2, '4-6次': 3, '6次以上': 4, '經常來學習,忘記次數了': 5})
31
+
32
+ class SurveyAnalyzer:
33
+ """📊 問卷分析類"""
34
+
35
+ def __init__(self):
36
+ self.mappings = SurveyMappings()
37
+ self.satisfaction_columns = [
38
+ '1. 示範場域提供多元的數位課程與活動',
39
+ '2.示範場域的數位課程與活動對我的生活應用有幫助',
40
+ '3. 示範場域的服務人員親切有禮貌',
41
+ '4.示範場域的服務空間與數位設備友善方便',
42
+ '5.在示範場域可以獲得需要的協助',
43
+ '6.對於示範場域的服務感到滿意'
44
+ ]
45
+
46
+ def plot_satisfaction_correlation(self, df: pd.DataFrame):
47
+ """🔥 滿意度相關性熱力圖"""
48
+ correlation_matrix = df[self.satisfaction_columns].corr()
49
+ fig = px.imshow(correlation_matrix, text_auto=True, color_continuous_scale='viridis',
50
+ title='🔥 滿意度項目相關性熱力圖')
51
+
52
+ # ✅ 放大圖表
53
+ fig.update_layout(
54
+ font=dict(size=20),
55
+ title_font=dict(size=26, family="Arial Black"),
56
+ width=1000,
57
+ height=800,
58
+ coloraxis_colorbar=dict(title="相關性"),
59
+ )
60
+
61
+ st.plotly_chart(fig, use_container_width=True)
62
+
63
+ def generate_report(self, df: pd.DataFrame) -> Dict[str, Any]:
64
+ """📝 生成問卷調查報告"""
65
+ return {
66
+ '基本統計': {
67
+ '總受訪人數': len(df),
68
+ '性別分布': df['1. 性別'].value_counts().to_dict(),
69
+ '教育程度分布': df['3.教育程度'].value_counts().to_dict(),
70
+ '平均年齡': f"{pd.to_numeric(df['2.出生年(民國__年)'], errors='coerce').mean():.1f}歲"
71
+ },
72
+ '滿意度統計': {
73
+ '整體平均滿意度': f"{df['6.對於示範場域的服務感到滿意'].mean():.2f}",
74
+ '最高分項目': df[self.satisfaction_columns].mean().idxmax(),
75
+ '最低分項目': df[self.satisfaction_columns].mean().idxmin()
76
+ }
77
+ }
78
+
79
+ # 🎨 Streamlit UI
80
+ def main():
81
+ st.set_page_config(page_title="問卷調查分析", layout="wide")
82
+
83
+ st.title("📊 問卷調查分析報告")
84
+ st.write("本頁面展示問卷調查數據的分析結果,包括統計信息與視覺化圖表。")
85
+
86
+ # 讀取數據
87
+ df = read_google_sheet(sheet_id, gid)
88
+
89
+ if df is not None:
90
+ analyzer = SurveyAnalyzer()
91
+
92
+ # 📌 基本統計數據
93
+ st.header("📋 問卷統計報告")
94
+ report = analyzer.generate_report(df)
95
+ for category, stats in report.items():
96
+ with st.expander(f"🔍 {category}"):
97
+ for key, value in stats.items():
98
+ st.write(f"**{key}**: {value}")
99
+
100
+ # 📊 滿意度熱力圖
101
+ st.header("🔥 滿意度相關性熱力圖")
102
+ analyzer.plot_satisfaction_correlation(df)
103
+
104
+ if __name__ == "__main__":
105
+ main()