Spaces:
Running
Running
Update pages/Statistics.py
Browse files- pages/Statistics.py +14 -58
pages/Statistics.py
CHANGED
@@ -14,9 +14,9 @@ from streamlit_extras.metric_cards import style_metric_cards
|
|
14 |
from streamlit_elements import elements, mui, html
|
15 |
|
16 |
# Definiowanie 艣cie偶ek do plik贸w JSON
|
17 |
-
FAKE_NUMBERS_FILE = 'data
|
18 |
-
HISTORY_FILE = 'data
|
19 |
-
STATS_FILE = 'data
|
20 |
|
21 |
# Definiowanie t艂umacze艅 dla zak艂adki "Statystyki"
|
22 |
page_translations = {
|
@@ -109,7 +109,7 @@ def save_json(file_path, data):
|
|
109 |
"""Zapisuje dane do pliku JSON."""
|
110 |
with open(file_path, 'w', encoding='utf-8') as file:
|
111 |
json.dump(data, file, ensure_ascii=False, indent=4)
|
112 |
-
|
113 |
|
114 |
def get_stats_from_json():
|
115 |
"""Pobiera statystyki z pliku stats.json."""
|
@@ -135,16 +135,6 @@ def get_country_code(name):
|
|
135 |
def main(language):
|
136 |
translations = page_translations[language]
|
137 |
|
138 |
-
# Inicjalizacja loggera w sesji Streamlit
|
139 |
-
if 'logger' not in st.session_state:
|
140 |
-
import logging
|
141 |
-
logging.basicConfig(
|
142 |
-
filename='app.log',
|
143 |
-
level=logging.INFO,
|
144 |
-
format='%(asctime)s %(levelname)s:%(message)s'
|
145 |
-
)
|
146 |
-
st.session_state['logger'] = logging.getLogger()
|
147 |
-
|
148 |
# Pobieranie danych z plik贸w JSON
|
149 |
stats = get_stats_from_json()
|
150 |
history = get_history_from_json()
|
@@ -156,22 +146,11 @@ def main(language):
|
|
156 |
# Stylizacja kart metryk
|
157 |
style_metric_cards()
|
158 |
|
159 |
-
# Wy艣wietlenie metryk
|
160 |
-
col1, col2, col3 = st.columns(3)
|
161 |
-
col1.metric(label=translations['total_analyses'], value=total_analyses)
|
162 |
-
col2.metric(label=translations['total_frauds_detected'], value=total_frauds_detected)
|
163 |
-
if total_analyses > 0:
|
164 |
-
fraud_percentage = (total_frauds_detected / total_analyses) * 100
|
165 |
-
else:
|
166 |
-
fraud_percentage = 0 # Ustawienie na 0% w przypadku braku analiz
|
167 |
-
col3.metric(label=translations['fraud_percentage'], value=f"{fraud_percentage:.2f}%")
|
168 |
-
|
169 |
# Dodanie interaktywnego filtra daty
|
170 |
st.sidebar.header(translations['select_date_range'])
|
171 |
-
recent_days = translations[language]['recent_days']
|
172 |
start_date = st.sidebar.date_input(
|
173 |
"Start Date",
|
174 |
-
value=datetime.now().date() - pd.Timedelta(days=recent_days),
|
175 |
min_value=datetime.now().date() - pd.Timedelta(days=365),
|
176 |
max_value=datetime.now().date()
|
177 |
)
|
@@ -197,11 +176,10 @@ def main(language):
|
|
197 |
fraud_percentage_filtered = (frauds_filtered / total_filtered) * 100 if total_filtered > 0 else 0
|
198 |
|
199 |
# Wy艣wietlenie metryk dla filtrowanej historii
|
200 |
-
st.
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
col6.metric(label=translations['fraud_percentage'], value=f"{fraud_percentage_filtered:.2f}%")
|
205 |
|
206 |
# Wizualizacja procentowego podzia艂u oszustw
|
207 |
st.markdown("### " + translations['fraud_vs_nonfraud'])
|
@@ -258,7 +236,7 @@ def main(language):
|
|
258 |
color_continuous_scale=px.colors.sequential.Plasma,
|
259 |
title=translations['fraud_country_distribution_title']
|
260 |
)
|
261 |
-
fig_map.update_geos(showcountries=True, showcoastlines=True)
|
262 |
st.plotly_chart(fig_map, use_container_width=True)
|
263 |
else:
|
264 |
st.info(translations['no_data'])
|
@@ -267,24 +245,11 @@ def main(language):
|
|
267 |
st.markdown("### " + translations['heatmap_title'])
|
268 |
# Heatmapa oszustw na podstawie lokalizacji
|
269 |
if not fraud_countries.empty:
|
270 |
-
# Przygotowanie danych geograficznych
|
271 |
-
# Mo偶emy u偶y膰 centroid贸w kraj贸w lub innej dost臋pnej lokalizacji
|
272 |
-
# Dla uproszczenia u偶yjemy szeroko艣ci i d艂ugo艣ci geograficznej kraj贸w
|
273 |
-
country_coords = {
|
274 |
-
'Poland': (52.237049, 21.017532),
|
275 |
-
'Germany': (51.165691, 10.451526),
|
276 |
-
'Unknown': (20.0, 0.0) # Centrum 艣wiata
|
277 |
-
# Dodaj inne kraje w razie potrzeby
|
278 |
-
}
|
279 |
-
|
280 |
-
fraud_countries['lat'] = fraud_countries['country'].apply(lambda x: country_coords.get(x, (20.0, 0.0))[0])
|
281 |
-
fraud_countries['lon'] = fraud_countries['country'].apply(lambda x: country_coords.get(x, (20.0, 0.0))[1])
|
282 |
-
|
283 |
-
# Tworzenie Heatmapy
|
284 |
fig_heatmap = px.density_mapbox(
|
285 |
fraud_countries,
|
286 |
-
lat='
|
287 |
-
lon='
|
288 |
z='counts',
|
289 |
radius=10,
|
290 |
center=dict(lat=20, lon=0),
|
@@ -292,6 +257,7 @@ def main(language):
|
|
292 |
mapbox_style="stamen-terrain",
|
293 |
title=translations['heatmap_title']
|
294 |
)
|
|
|
295 |
st.plotly_chart(fig_heatmap, use_container_width=True)
|
296 |
else:
|
297 |
st.info(translations['no_data'])
|
@@ -320,13 +286,3 @@ def main(language):
|
|
320 |
}
|
321 |
))
|
322 |
st.plotly_chart(fig_gauge, use_container_width=True)
|
323 |
-
|
324 |
-
# Heatmap z u偶yciem streamlit-elements (opcjonalne)
|
325 |
-
elements("heatmap_section")
|
326 |
-
with elements("heatmap_section"):
|
327 |
-
html.Div(
|
328 |
-
html.H3(translations['heatmap_title']),
|
329 |
-
style={"textAlign": "center", "marginBottom": "20px"}
|
330 |
-
)
|
331 |
-
# Mo偶esz doda膰 dodatkowe elementy interaktywne tutaj
|
332 |
-
|
|
|
14 |
from streamlit_elements import elements, mui, html
|
15 |
|
16 |
# Definiowanie 艣cie偶ek do plik贸w JSON
|
17 |
+
FAKE_NUMBERS_FILE = os.path.join('data', 'fake_numbers.json')
|
18 |
+
HISTORY_FILE = os.path.join('data', 'history.json')
|
19 |
+
STATS_FILE = os.path.join('data', 'stats.json')
|
20 |
|
21 |
# Definiowanie t艂umacze艅 dla zak艂adki "Statystyki"
|
22 |
page_translations = {
|
|
|
109 |
"""Zapisuje dane do pliku JSON."""
|
110 |
with open(file_path, 'w', encoding='utf-8') as file:
|
111 |
json.dump(data, file, ensure_ascii=False, indent=4)
|
112 |
+
logging.info(f"Dane zosta艂y zapisane do {file_path}.")
|
113 |
|
114 |
def get_stats_from_json():
|
115 |
"""Pobiera statystyki z pliku stats.json."""
|
|
|
135 |
def main(language):
|
136 |
translations = page_translations[language]
|
137 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
138 |
# Pobieranie danych z plik贸w JSON
|
139 |
stats = get_stats_from_json()
|
140 |
history = get_history_from_json()
|
|
|
146 |
# Stylizacja kart metryk
|
147 |
style_metric_cards()
|
148 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
149 |
# Dodanie interaktywnego filtra daty
|
150 |
st.sidebar.header(translations['select_date_range'])
|
|
|
151 |
start_date = st.sidebar.date_input(
|
152 |
"Start Date",
|
153 |
+
value=datetime.now().date() - pd.Timedelta(days=translations['recent_days']),
|
154 |
min_value=datetime.now().date() - pd.Timedelta(days=365),
|
155 |
max_value=datetime.now().date()
|
156 |
)
|
|
|
176 |
fraud_percentage_filtered = (frauds_filtered / total_filtered) * 100 if total_filtered > 0 else 0
|
177 |
|
178 |
# Wy艣wietlenie metryk dla filtrowanej historii
|
179 |
+
col1, col2, col3 = st.columns(3)
|
180 |
+
col1.metric(label=translations['total_analyses'], value=total_filtered)
|
181 |
+
col2.metric(label=translations['total_frauds_detected'], value=frauds_filtered)
|
182 |
+
col3.metric(label=translations['fraud_percentage'], value=f"{fraud_percentage_filtered:.2f}%")
|
|
|
183 |
|
184 |
# Wizualizacja procentowego podzia艂u oszustw
|
185 |
st.markdown("### " + translations['fraud_vs_nonfraud'])
|
|
|
236 |
color_continuous_scale=px.colors.sequential.Plasma,
|
237 |
title=translations['fraud_country_distribution_title']
|
238 |
)
|
239 |
+
fig_map.update_geos(showcountries=True, showcoastlines=True)
|
240 |
st.plotly_chart(fig_map, use_container_width=True)
|
241 |
else:
|
242 |
st.info(translations['no_data'])
|
|
|
245 |
st.markdown("### " + translations['heatmap_title'])
|
246 |
# Heatmapa oszustw na podstawie lokalizacji
|
247 |
if not fraud_countries.empty:
|
248 |
+
# Przygotowanie danych geograficznych za pomoc膮 Plotly bez konieczno艣ci r臋cznego wprowadzania lat/lon
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
249 |
fig_heatmap = px.density_mapbox(
|
250 |
fraud_countries,
|
251 |
+
lat=fraud_countries['iso_alpha'].apply(lambda x: pycountry.countries.get(alpha_3=x).latitude if hasattr(pycountry.countries.get(alpha_3=x), 'latitude') else None),
|
252 |
+
lon=fraud_countries['iso_alpha'].apply(lambda x: pycountry.countries.get(alpha_3=x).longitude if hasattr(pycountry.countries.get(alpha_3=x), 'longitude') else None),
|
253 |
z='counts',
|
254 |
radius=10,
|
255 |
center=dict(lat=20, lon=0),
|
|
|
257 |
mapbox_style="stamen-terrain",
|
258 |
title=translations['heatmap_title']
|
259 |
)
|
260 |
+
fig_heatmap.update_layout(margin={"r":0,"t":50,"l":0,"b":0})
|
261 |
st.plotly_chart(fig_heatmap, use_container_width=True)
|
262 |
else:
|
263 |
st.info(translations['no_data'])
|
|
|
286 |
}
|
287 |
))
|
288 |
st.plotly_chart(fig_gauge, use_container_width=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|