Levin-Aleksey commited on
Commit
e36a311
·
1 Parent(s): 5fa7f77
Files changed (4) hide show
  1. Dockerfile +1 -1
  2. __pycache__/app.cpython-312.pyc +0 -0
  3. app.py +37 -142
  4. requirements.txt +3 -4
Dockerfile CHANGED
@@ -1,4 +1,4 @@
1
- FROM python:3.10-slim
2
  WORKDIR /app
3
  COPY requirements.txt .
4
  RUN pip install --no-cache-dir -r requirements.txt
 
1
+ FROM python:3.11-slim
2
  WORKDIR /app
3
  COPY requirements.txt .
4
  RUN pip install --no-cache-dir -r requirements.txt
__pycache__/app.cpython-312.pyc CHANGED
Binary files a/__pycache__/app.cpython-312.pyc and b/__pycache__/app.cpython-312.pyc differ
 
app.py CHANGED
@@ -8,171 +8,66 @@ import json
8
  import os
9
 
10
  st.set_page_config(page_title="Crypto Dash", layout="wide")
11
- IS_HF_SPACE = bool(os.getenv("SPACE_ID") or os.getenv("SPACE_REPO_NAME"))
12
 
13
 
14
- def normalize_cohorts(raw_cohorts) -> pd.DataFrame:
15
- """Return a normalized DataFrame with columns: cohort_day, user_count."""
16
- if raw_cohorts is None:
17
- return pd.DataFrame(columns=["cohort_day", "user_count"])
18
-
19
- if isinstance(raw_cohorts, dict):
20
- rows = []
21
- for day, count in raw_cohorts.items():
22
- rows.append({"cohort_day": day, "user_count": count})
23
- df = pd.DataFrame(rows)
24
- else:
25
- df = pd.DataFrame(raw_cohorts)
26
-
27
- if df.empty:
28
- return pd.DataFrame(columns=["cohort_day", "user_count"])
29
 
30
- # Some payloads can use alternative field names.
31
- rename_map = {
32
- "day": "cohort_day",
33
- "cohort": "cohort_day",
34
- "count": "user_count",
35
- "users": "user_count",
36
- "tx_count": "user_count",
37
- }
38
- df = df.rename(columns=rename_map)
39
 
40
- required_cols = {"cohort_day", "user_count"}
41
- if not required_cols.issubset(df.columns):
 
42
  return pd.DataFrame(columns=["cohort_day", "user_count"])
43
-
44
  df["cohort_day"] = pd.to_numeric(df["cohort_day"], errors="coerce")
45
  df["user_count"] = pd.to_numeric(df["user_count"], errors="coerce")
46
- df = df.dropna(subset=["cohort_day", "user_count"]).sort_values("cohort_day")
47
-
48
- if df.empty:
49
- return pd.DataFrame(columns=["cohort_day", "user_count"])
50
-
51
- return df[["cohort_day", "user_count"]]
52
-
53
-
54
- def cohorts_from_daily_map(raw_daily_map) -> pd.DataFrame:
55
- """Build cohorts from txs_per_day_by_cohorts format.
56
-
57
- Expected shape:
58
- {
59
- "2025-07-27": {"2": 1, "3": 2, ...},
60
- "2025-07-28": {"2": 3, ...}
61
- }
62
- """
63
- if not isinstance(raw_daily_map, dict) or not raw_daily_map:
64
- return pd.DataFrame(columns=["cohort_day", "user_count"])
65
-
66
- totals = {}
67
- for _, cohorts in raw_daily_map.items():
68
- if not isinstance(cohorts, dict):
69
- continue
70
- for day, count in cohorts.items():
71
- try:
72
- d = float(day)
73
- c = float(count)
74
- except (TypeError, ValueError):
75
- continue
76
- totals[d] = totals.get(d, 0.0) + c
77
-
78
- if not totals:
79
- return pd.DataFrame(columns=["cohort_day", "user_count"])
80
 
81
- df = pd.DataFrame(
82
- [{"cohort_day": day, "user_count": count} for day, count in totals.items()]
83
- ).sort_values("cohort_day")
84
- return df
85
 
86
- def load_report_data() -> dict:
87
- """Load report data from data.json next to app.py.
88
-
89
- Handles both formats: a list with one report or a single report object.
90
- """
91
- app_dir = os.path.dirname(os.path.abspath(__file__))
92
- data_path = os.path.join(app_dir, "data.json")
93
-
94
- if not os.path.exists(data_path):
95
- st.error(f"Файл data.json не найден: {data_path}")
96
- st.stop()
97
-
98
- try:
99
- with open(data_path, "r", encoding="utf-8") as f:
100
- payload = json.load(f)
101
- except json.JSONDecodeError as exc:
102
- st.error(f"Ошибка формата JSON в data.json: {exc}")
103
- st.stop()
104
-
105
- if isinstance(payload, list):
106
- if not payload:
107
- st.error("data.json содержит пустой список.")
108
- st.stop()
109
- return payload[0]
110
-
111
- if isinstance(payload, dict):
112
- return payload
113
-
114
- st.error("Неподдерживаемый формат data.json. Ожидался объект или список объектов.")
115
  st.stop()
116
 
117
-
118
- data = load_report_data()
119
-
120
  st.title("📊 Blockchain Dashboard")
121
 
122
- # KPI блоки
123
  c1, c2, c3 = st.columns(3)
124
  c1.metric("Total TX", f"{data['total_tx_amount']:,}")
125
  c2.metric("DAU", f"{data['dau']:,}")
126
  c3.metric("New Wallets", f"{data['new_wallets_amount']:,}")
127
 
128
- # График когорт
129
  st.subheader("User Activity by Cohort Day")
130
- cohorts_raw = data.get("users_by_cohorts", [])
131
- df_cohorts = normalize_cohorts(cohorts_raw)
132
 
133
- if df_cohorts.empty:
134
- # Fallback source when users_by_cohorts is missing/invalid in some reports.
135
- daily_map_raw = data.get("txs_per_day_by_cohorts", {})
136
- df_cohorts = cohorts_from_daily_map(daily_map_raw)
137
 
138
- st.info(f"🔍 Debug Info: DataFrame is empty? {df_cohorts.empty} | Shape: {df_cohorts.shape}")
139
-
140
- if df_cohorts.empty:
141
- st.warning("Нет данных для графика: users_by_cohorts и txs_per_day_by_cohorts пустые или невалидные.")
142
  else:
143
- st.caption("1. Table Data (Guaranteed Fallback)")
144
- st.table(df_cohorts.head(10))
145
-
146
- st.caption("2. Server-rendered fallback (matplotlib - No JS required)")
147
- mpl_fig, mpl_ax = plt.subplots(figsize=(9, 4))
148
- mpl_ax.plot(df_cohorts["cohort_day"], df_cohorts["user_count"], linewidth=2)
149
- mpl_ax.fill_between(df_cohorts["cohort_day"], df_cohorts["user_count"], alpha=0.25)
150
- mpl_ax.set_xlabel("cohort_day")
151
- mpl_ax.set_ylabel("user_count")
152
- mpl_ax.grid(alpha=0.2)
 
 
 
 
 
153
  st.pyplot(mpl_fig)
154
  plt.close(mpl_fig)
155
 
156
- st.caption("3. Native chart (Altair)")
157
- st.area_chart(df_cohorts.set_index("cohort_day")["user_count"])
158
-
159
- try:
160
- st.caption("4. Plotly chart")
161
- fig = px.area(df_cohorts, x="cohort_day", y="user_count", template="plotly")
162
- fig.update_layout(height=400, margin=dict(l=20, r=20, t=20, b=20))
163
- st.plotly_chart(fig)
164
- except Exception as exc:
165
- st.warning(f"Plotly не отрисован: {exc}")
166
-
167
- st.caption("Chart debug")
168
- st.metric("Rows", len(df_cohorts))
169
- st.metric("Min day", int(df_cohorts["cohort_day"].min()))
170
- st.metric("Max day", int(df_cohorts["cohort_day"].max()))
171
-
172
- # Guaranteed non-visual fallback for environments where JS charts are blocked.
173
- with st.expander("Chart data preview"):
174
- st.dataframe(df_cohorts)
175
-
176
- # Проверка данных внизу
177
  with st.expander("Raw Data"):
178
- st.write(data)
 
8
  import os
9
 
10
  st.set_page_config(page_title="Crypto Dash", layout="wide")
 
11
 
12
 
13
+ def load_data() -> dict:
14
+ app_dir = os.path.dirname(os.path.abspath(__file__))
15
+ data_path = os.path.join(app_dir, "data.json")
16
+ with open(data_path, "r", encoding="utf-8") as f:
17
+ payload = json.load(f)
18
+ return payload[0] if isinstance(payload, list) else payload
 
 
 
 
 
 
 
 
 
19
 
 
 
 
 
 
 
 
 
 
20
 
21
+ def build_cohorts_df(data: dict) -> pd.DataFrame:
22
+ raw = data.get("users_by_cohorts", [])
23
+ if not raw:
24
  return pd.DataFrame(columns=["cohort_day", "user_count"])
25
+ df = pd.DataFrame(raw)
26
  df["cohort_day"] = pd.to_numeric(df["cohort_day"], errors="coerce")
27
  df["user_count"] = pd.to_numeric(df["user_count"], errors="coerce")
28
+ return df.dropna().sort_values("cohort_day").reset_index(drop=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
 
 
 
 
30
 
31
+ try:
32
+ data = load_data()
33
+ except Exception as e:
34
+ st.error(f"Ошибка загрузки data.json: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  st.stop()
36
 
 
 
 
37
  st.title("📊 Blockchain Dashboard")
38
 
39
+ # KPI
40
  c1, c2, c3 = st.columns(3)
41
  c1.metric("Total TX", f"{data['total_tx_amount']:,}")
42
  c2.metric("DAU", f"{data['dau']:,}")
43
  c3.metric("New Wallets", f"{data['new_wallets_amount']:,}")
44
 
45
+ # Chart
46
  st.subheader("User Activity by Cohort Day")
 
 
47
 
48
+ df = build_cohorts_df(data)
 
 
 
49
 
50
+ if df.empty:
51
+ st.warning("Нет данных для графика.")
 
 
52
  else:
53
+ # 1. Plotly (primary)
54
+ fig = px.area(df, x="cohort_day", y="user_count",
55
+ title="Cohort Activity",
56
+ template="plotly_white")
57
+ fig.update_layout(height=400, margin=dict(l=20, r=20, t=40, b=20))
58
+ st.plotly_chart(fig, use_container_width=True)
59
+
60
+ # 2. Matplotlib PNG (server-side, always visible)
61
+ mpl_fig, ax = plt.subplots(figsize=(10, 3))
62
+ ax.fill_between(df["cohort_day"], df["user_count"], alpha=0.4)
63
+ ax.plot(df["cohort_day"], df["user_count"], linewidth=2)
64
+ ax.set_xlabel("Cohort Day")
65
+ ax.set_ylabel("Users")
66
+ ax.set_title("Cohort Activity (server-rendered)")
67
+ ax.grid(alpha=0.3)
68
  st.pyplot(mpl_fig)
69
  plt.close(mpl_fig)
70
 
71
+ # Raw data
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  with st.expander("Raw Data"):
73
+ st.write(data)
requirements.txt CHANGED
@@ -1,5 +1,4 @@
1
- streamlit==1.55.0
2
  pandas
3
- plotly==6.6.0
4
- matplotlib
5
- websockets
 
1
+ streamlit
2
  pandas
3
+ plotly
4
+ matplotlib