Spaces:
Sleeping
Sleeping
fix bug for dates filters
Browse files
map.py
CHANGED
|
@@ -1,506 +1,507 @@
|
|
| 1 |
-
import json
|
| 2 |
-
import streamlit as st
|
| 3 |
-
#import geopandas as gpd
|
| 4 |
-
from keplergl import keplergl
|
| 5 |
-
import pandas as pd
|
| 6 |
-
import streamlit as st
|
| 7 |
-
import pandas as pd
|
| 8 |
-
import numpy as np
|
| 9 |
-
import matplotlib.pyplot as plt
|
| 10 |
-
import seaborn as sns
|
| 11 |
-
from uap_analyzer import UAPParser, UAPAnalyzer, UAPVisualizer
|
| 12 |
-
# import ChartGen
|
| 13 |
-
# from ChartGen import ChartGPT
|
| 14 |
-
from Levenshtein import distance
|
| 15 |
-
from sklearn.model_selection import train_test_split
|
| 16 |
-
from sklearn.metrics import confusion_matrix
|
| 17 |
-
from stqdm import stqdm
|
| 18 |
-
stqdm.pandas()
|
| 19 |
-
import streamlit.components.v1 as components
|
| 20 |
-
from dateutil import parser
|
| 21 |
-
from sentence_transformers import SentenceTransformer
|
| 22 |
-
import torch
|
| 23 |
-
import squarify
|
| 24 |
-
import matplotlib.colors as mcolors
|
| 25 |
-
import textwrap
|
| 26 |
-
import datamapplot
|
| 27 |
-
from streamlit_extras.stateful_button import button as stateful_button
|
| 28 |
-
from streamlit_keplergl import keplergl_static
|
| 29 |
-
from keplergl import KeplerGl
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
st.set_option('deprecation.showPyplotGlobalUse', False)
|
| 33 |
-
|
| 34 |
-
from pandas.api.types import (
|
| 35 |
-
is_categorical_dtype,
|
| 36 |
-
is_datetime64_any_dtype,
|
| 37 |
-
is_numeric_dtype,
|
| 38 |
-
is_object_dtype,
|
| 39 |
-
)
|
| 40 |
-
|
| 41 |
-
st.title('Interactive Map')
|
| 42 |
-
|
| 43 |
-
# Initialize session state
|
| 44 |
-
if 'analyzers' not in st.session_state:
|
| 45 |
-
st.session_state['analyzers'] = []
|
| 46 |
-
if 'col_names' not in st.session_state:
|
| 47 |
-
st.session_state['col_names'] = []
|
| 48 |
-
if 'clusters' not in st.session_state:
|
| 49 |
-
st.session_state['clusters'] = {}
|
| 50 |
-
if 'new_data' not in st.session_state:
|
| 51 |
-
st.session_state['new_data'] = pd.DataFrame()
|
| 52 |
-
if 'dataset' not in st.session_state:
|
| 53 |
-
st.session_state['dataset'] = pd.DataFrame()
|
| 54 |
-
if 'data_processed' not in st.session_state:
|
| 55 |
-
st.session_state['data_processed'] = False
|
| 56 |
-
if 'stage' not in st.session_state:
|
| 57 |
-
st.session_state['stage'] = 0
|
| 58 |
-
if 'filtered_data' not in st.session_state:
|
| 59 |
-
st.session_state['filtered_data'] = None
|
| 60 |
-
if 'gemini_answer' not in st.session_state:
|
| 61 |
-
st.session_state['gemini_answer'] = None
|
| 62 |
-
if 'parsed_responses' not in st.session_state:
|
| 63 |
-
st.session_state['parsed_responses'] = None
|
| 64 |
-
if 'map_generated' not in st.session_state:
|
| 65 |
-
st.session_state['map_generated'] = False
|
| 66 |
-
if 'date_loaded' not in st.session_state:
|
| 67 |
-
st.session_state['data_loaded'] = False
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
if "datasets" not in st.session_state:
|
| 71 |
-
st.session_state.datasets = []
|
| 72 |
-
|
| 73 |
-
# sf_zip_geo_gdf = gpd.read_file("sf_zip_geo.geojson")
|
| 74 |
-
# sf_zip_geo_gdf.label = "SF Zip Geo"
|
| 75 |
-
# sf_zip_geo_gdf.id = "sf-zip-geo"
|
| 76 |
-
# st.session_state.datasets.append(sf_zip_geo_gdf)
|
| 77 |
-
|
| 78 |
-
def plot_treemap(df, column, top_n=32):
|
| 79 |
-
# Get the value counts and the top N labels
|
| 80 |
-
value_counts = df[column].value_counts()
|
| 81 |
-
top_labels = value_counts.iloc[:top_n].index
|
| 82 |
-
|
| 83 |
-
# Use np.where to replace all values not in the top N with 'Other'
|
| 84 |
-
revised_column = f'{column}_revised'
|
| 85 |
-
df[revised_column] = np.where(df[column].isin(top_labels), df[column], 'Other')
|
| 86 |
-
|
| 87 |
-
# Get the value counts including the 'Other' category
|
| 88 |
-
sizes = df[revised_column].value_counts().values
|
| 89 |
-
labels = df[revised_column].value_counts().index
|
| 90 |
-
|
| 91 |
-
# Get a gradient of colors
|
| 92 |
-
# colors = list(mcolors.TABLEAU_COLORS.values())
|
| 93 |
-
|
| 94 |
-
n_colors = len(sizes)
|
| 95 |
-
colors = plt.cm.Oranges(np.linspace(0.3, 0.9, n_colors))[::-1]
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
# Get % of each category
|
| 99 |
-
percents = sizes / sizes.sum()
|
| 100 |
-
|
| 101 |
-
# Prepare labels with percentages
|
| 102 |
-
labels = [f'{label}\n {percent:.1%}' for label, percent in zip(labels, percents)]
|
| 103 |
-
|
| 104 |
-
fig, ax = plt.subplots(figsize=(20, 12))
|
| 105 |
-
|
| 106 |
-
# Plot the treemap
|
| 107 |
-
squarify.plot(sizes=sizes, label=labels, alpha=0.7, pad=True, color=colors, text_kwargs={'fontsize': 10})
|
| 108 |
-
|
| 109 |
-
ax = plt.gca()
|
| 110 |
-
# Iterate over text elements and rectangles (patches) in the axes for color adjustment
|
| 111 |
-
for text, rect in zip(ax.texts, ax.patches):
|
| 112 |
-
background_color = rect.get_facecolor()
|
| 113 |
-
r, g, b, _ = mcolors.to_rgba(background_color)
|
| 114 |
-
brightness = np.average([r, g, b])
|
| 115 |
-
text.set_color('white' if brightness < 0.5 else 'black')
|
| 116 |
-
|
| 117 |
-
# Adjust font size based on rectangle's area and wrap long text
|
| 118 |
-
coef = 0.8
|
| 119 |
-
font_size = np.sqrt(rect.get_width() * rect.get_height()) * coef
|
| 120 |
-
text.set_fontsize(font_size)
|
| 121 |
-
wrapped_text = textwrap.fill(text.get_text(), width=20)
|
| 122 |
-
text.set_text(wrapped_text)
|
| 123 |
-
|
| 124 |
-
plt.axis('off')
|
| 125 |
-
plt.gca().invert_yaxis()
|
| 126 |
-
plt.gcf().set_size_inches(20, 12)
|
| 127 |
-
|
| 128 |
-
fig.patch.set_alpha(0)
|
| 129 |
-
|
| 130 |
-
ax.patch.set_alpha(0)
|
| 131 |
-
return fig
|
| 132 |
-
|
| 133 |
-
def plot_hist(df, column, bins=10, kde=True):
|
| 134 |
-
fig, ax = plt.subplots(figsize=(12, 6))
|
| 135 |
-
sns.histplot(data=df, x=column, kde=True, bins=bins,color='orange')
|
| 136 |
-
# set the ticks and frame in orange
|
| 137 |
-
ax.spines['bottom'].set_color('orange')
|
| 138 |
-
ax.spines['top'].set_color('orange')
|
| 139 |
-
ax.spines['right'].set_color('orange')
|
| 140 |
-
ax.spines['left'].set_color('orange')
|
| 141 |
-
ax.xaxis.label.set_color('orange')
|
| 142 |
-
ax.yaxis.label.set_color('orange')
|
| 143 |
-
ax.tick_params(axis='x', colors='orange')
|
| 144 |
-
ax.tick_params(axis='y', colors='orange')
|
| 145 |
-
ax.title.set_color('orange')
|
| 146 |
-
|
| 147 |
-
# Set transparent background
|
| 148 |
-
fig.patch.set_alpha(0)
|
| 149 |
-
ax.patch.set_alpha(0)
|
| 150 |
-
return fig
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
def plot_line(df, x_column, y_columns, figsize=(12, 10), color='orange', title=None, rolling_mean_value=2):
|
| 154 |
-
import matplotlib.cm as cm
|
| 155 |
-
# Sort the dataframe by the date column
|
| 156 |
-
df = df.sort_values(by=x_column)
|
| 157 |
-
|
| 158 |
-
# Calculate rolling mean for each y_column
|
| 159 |
-
if rolling_mean_value:
|
| 160 |
-
df[y_columns] = df[y_columns].rolling(len(df) // rolling_mean_value).mean()
|
| 161 |
-
|
| 162 |
-
# Create the plot
|
| 163 |
-
fig, ax = plt.subplots(figsize=figsize)
|
| 164 |
-
|
| 165 |
-
colors = cm.Oranges(np.linspace(0.2, 1, len(y_columns)))
|
| 166 |
-
|
| 167 |
-
# Plot each y_column as a separate line with a different color
|
| 168 |
-
for i, y_column in enumerate(y_columns):
|
| 169 |
-
df.plot(x=x_column, y=y_column, ax=ax, color=colors[i], label=y_column, linewidth=.5)
|
| 170 |
-
|
| 171 |
-
# Rotate x-axis labels
|
| 172 |
-
ax.set_xticklabels(ax.get_xticklabels(), rotation=30, ha='right')
|
| 173 |
-
|
| 174 |
-
# Format x_column as date if it is
|
| 175 |
-
if np.issubdtype(df[x_column].dtype, np.datetime64) or np.issubdtype(df[x_column].dtype, np.timedelta64):
|
| 176 |
-
df[x_column] = pd.to_datetime(df[x_column]).dt.date
|
| 177 |
-
|
| 178 |
-
# Set title, labels, and legend
|
| 179 |
-
ax.set_title(title or f'{", ".join(y_columns)} over {x_column}', color=color, fontweight='bold')
|
| 180 |
-
ax.set_xlabel(x_column, color=color)
|
| 181 |
-
ax.set_ylabel(', '.join(y_columns), color=color)
|
| 182 |
-
ax.spines['bottom'].set_color('orange')
|
| 183 |
-
ax.spines['top'].set_color('orange')
|
| 184 |
-
ax.spines['right'].set_color('orange')
|
| 185 |
-
ax.spines['left'].set_color('orange')
|
| 186 |
-
ax.xaxis.label.set_color('orange')
|
| 187 |
-
ax.yaxis.label.set_color('orange')
|
| 188 |
-
ax.tick_params(axis='x', colors='orange')
|
| 189 |
-
ax.tick_params(axis='y', colors='orange')
|
| 190 |
-
ax.title.set_color('orange')
|
| 191 |
-
|
| 192 |
-
ax.legend(loc='upper right', bbox_to_anchor=(1, 1), facecolor='black', framealpha=.4, labelcolor='orange', edgecolor='orange')
|
| 193 |
-
|
| 194 |
-
# Remove background
|
| 195 |
-
fig.patch.set_alpha(0)
|
| 196 |
-
ax.patch.set_alpha(0)
|
| 197 |
-
|
| 198 |
-
return fig
|
| 199 |
-
|
| 200 |
-
def plot_bar(df, x_column, y_column, figsize=(12, 10), color='orange', title=None):
|
| 201 |
-
fig, ax = plt.subplots(figsize=figsize)
|
| 202 |
-
|
| 203 |
-
sns.barplot(data=df, x=x_column, y=y_column, color=color, ax=ax)
|
| 204 |
-
|
| 205 |
-
ax.set_title(title if title else f'{y_column} by {x_column}', color=color, fontweight='bold')
|
| 206 |
-
ax.set_xlabel(x_column, color=color)
|
| 207 |
-
ax.set_ylabel(y_column, color=color)
|
| 208 |
-
|
| 209 |
-
ax.tick_params(axis='x', colors=color)
|
| 210 |
-
ax.tick_params(axis='y', colors=color)
|
| 211 |
-
|
| 212 |
-
# Remove background
|
| 213 |
-
fig.patch.set_alpha(0)
|
| 214 |
-
ax.patch.set_alpha(0)
|
| 215 |
-
ax.spines['bottom'].set_color('orange')
|
| 216 |
-
ax.spines['top'].set_color('orange')
|
| 217 |
-
ax.spines['right'].set_color('orange')
|
| 218 |
-
ax.spines['left'].set_color('orange')
|
| 219 |
-
ax.xaxis.label.set_color('orange')
|
| 220 |
-
ax.yaxis.label.set_color('orange')
|
| 221 |
-
ax.tick_params(axis='x', colors='orange')
|
| 222 |
-
ax.tick_params(axis='y', colors='orange')
|
| 223 |
-
ax.title.set_color('orange')
|
| 224 |
-
ax.legend(loc='upper right', bbox_to_anchor=(1, 1), facecolor='black', framealpha=.4, labelcolor='orange', edgecolor='orange')
|
| 225 |
-
|
| 226 |
-
return fig
|
| 227 |
-
|
| 228 |
-
def plot_grouped_bar(df, x_columns, y_column, figsize=(12, 10), colors=None, title=None):
|
| 229 |
-
fig, ax = plt.subplots(figsize=figsize)
|
| 230 |
-
|
| 231 |
-
width = 0.8 / len(x_columns) # the width of the bars
|
| 232 |
-
x = np.arange(len(df)) # the label locations
|
| 233 |
-
|
| 234 |
-
for i, x_column in enumerate(x_columns):
|
| 235 |
-
sns.barplot(data=df, x=x, y=y_column, color=colors[i] if colors else None, ax=ax, width=width, label=x_column)
|
| 236 |
-
x += width # add the width of the bar to the x position for the next bar
|
| 237 |
-
|
| 238 |
-
ax.set_title(title if title else f'{y_column} by {", ".join(x_columns)}', color='orange', fontweight='bold')
|
| 239 |
-
ax.set_xlabel('Groups', color='orange')
|
| 240 |
-
ax.set_ylabel(y_column, color='orange')
|
| 241 |
-
|
| 242 |
-
ax.set_xticks(x - width * len(x_columns) / 2)
|
| 243 |
-
ax.set_xticklabels(df.index)
|
| 244 |
-
|
| 245 |
-
ax.tick_params(axis='x', colors='orange')
|
| 246 |
-
ax.tick_params(axis='y', colors='orange')
|
| 247 |
-
|
| 248 |
-
# Remove background
|
| 249 |
-
fig.patch.set_alpha(0)
|
| 250 |
-
ax.patch.set_alpha(0)
|
| 251 |
-
ax.spines['bottom'].set_color('orange')
|
| 252 |
-
ax.spines['top'].set_color('orange')
|
| 253 |
-
ax.spines['right'].set_color('orange')
|
| 254 |
-
ax.spines['left'].set_color('orange')
|
| 255 |
-
ax.xaxis.label.set_color('orange')
|
| 256 |
-
ax.yaxis.label.set_color('orange')
|
| 257 |
-
ax.title.set_color('orange')
|
| 258 |
-
ax.legend(loc='upper right', bbox_to_anchor=(1, 1), facecolor='black', framealpha=.4, labelcolor='orange', edgecolor='orange')
|
| 259 |
-
|
| 260 |
-
return fig
|
| 261 |
-
|
| 262 |
-
def generate_kepler_map(data):
|
| 263 |
-
map_config = keplergl(data, height=400)
|
| 264 |
-
return map_config
|
| 265 |
-
|
| 266 |
-
def filter_dataframe(df: pd.DataFrame) -> pd.DataFrame:
|
| 267 |
-
"""
|
| 268 |
-
Adds a UI on top of a dataframe to let viewers filter columns
|
| 269 |
-
|
| 270 |
-
Args:
|
| 271 |
-
df (pd.DataFrame): Original dataframe
|
| 272 |
-
|
| 273 |
-
Returns:
|
| 274 |
-
pd.DataFrame: Filtered dataframe
|
| 275 |
-
"""
|
| 276 |
-
|
| 277 |
-
title_font = "Arial"
|
| 278 |
-
body_font = "Arial"
|
| 279 |
-
title_size = 32
|
| 280 |
-
colors = ["red", "green", "blue"]
|
| 281 |
-
interpretation = False
|
| 282 |
-
extract_docx = False
|
| 283 |
-
title = "My Chart"
|
| 284 |
-
regex = ".*"
|
| 285 |
-
img_path = 'default_image.png'
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
#try:
|
| 289 |
-
# modify = st.checkbox("Add filters on raw data")
|
| 290 |
-
#except:
|
| 291 |
-
# try:
|
| 292 |
-
# modify = st.checkbox("Add filters on processed data")
|
| 293 |
-
# except:
|
| 294 |
-
# try:
|
| 295 |
-
# modify = st.checkbox("Add filters on parsed data")
|
| 296 |
-
# except:
|
| 297 |
-
# pass
|
| 298 |
-
|
| 299 |
-
#if not modify:
|
| 300 |
-
# return df
|
| 301 |
-
|
| 302 |
-
df_ = df.copy()
|
| 303 |
-
# Try to convert datetimes into a standard format (datetime, no timezone)
|
| 304 |
-
|
| 305 |
-
#modification_container = st.container()
|
| 306 |
-
|
| 307 |
-
#with modification_container:
|
| 308 |
-
try:
|
| 309 |
-
to_filter_columns = st.multiselect("Filter dataframe on", df_.columns)
|
| 310 |
-
except:
|
| 311 |
-
try:
|
| 312 |
-
to_filter_columns = st.multiselect("Filter dataframe", df_.columns)
|
| 313 |
-
except:
|
| 314 |
-
try:
|
| 315 |
-
to_filter_columns = st.multiselect("Filter the dataframe on", df_.columns)
|
| 316 |
-
except:
|
| 317 |
-
pass
|
| 318 |
-
|
| 319 |
-
date_column = None
|
| 320 |
-
filtered_columns = []
|
| 321 |
-
|
| 322 |
-
for column in to_filter_columns:
|
| 323 |
-
left, right = st.columns((1, 20))
|
| 324 |
-
# Treat columns with < 200 unique values as categorical if not date or numeric
|
| 325 |
-
if is_categorical_dtype(df_[column]) or (df_[column].nunique() < 120 and not is_datetime64_any_dtype(df_[column]) and not is_numeric_dtype(df_[column])):
|
| 326 |
-
user_cat_input = right.multiselect(
|
| 327 |
-
f"Values for {column}",
|
| 328 |
-
df_[column].value_counts().index.tolist(),
|
| 329 |
-
default=list(df_[column].value_counts().index)
|
| 330 |
-
)
|
| 331 |
-
df_ = df_[df_[column].isin(user_cat_input)]
|
| 332 |
-
filtered_columns.append(column)
|
| 333 |
-
|
| 334 |
-
with st.status(f"Category Distribution: {column}", expanded=False) as stat:
|
| 335 |
-
st.pyplot(plot_treemap(df_, column))
|
| 336 |
-
|
| 337 |
-
elif is_numeric_dtype(df_[column]):
|
| 338 |
-
_min = float(df_[column].min())
|
| 339 |
-
_max = float(df_[column].max())
|
| 340 |
-
step = (_max - _min) / 100
|
| 341 |
-
user_num_input = right.slider(
|
| 342 |
-
f"Values for {column}",
|
| 343 |
-
min_value=_min,
|
| 344 |
-
max_value=_max,
|
| 345 |
-
value=(_min, _max),
|
| 346 |
-
step=step,
|
| 347 |
-
)
|
| 348 |
-
df_ = df_[df_[column].between(*user_num_input)]
|
| 349 |
-
filtered_columns.append(column)
|
| 350 |
-
|
| 351 |
-
# Chart_GPT = ChartGPT(df_, title_font, body_font, title_size,
|
| 352 |
-
# colors, interpretation, extract_docx, img_path)
|
| 353 |
-
|
| 354 |
-
with st.status(f"Numerical Distribution: {column}", expanded=False) as stat_:
|
| 355 |
-
st.pyplot(plot_hist(df_, column, bins=int(round(len(df_[column].unique())-1)/2)))
|
| 356 |
-
|
| 357 |
-
elif is_object_dtype(df_[column]):
|
| 358 |
-
try:
|
| 359 |
-
df_[column] = pd.to_datetime(df_[column], infer_datetime_format=True, errors='coerce')
|
| 360 |
-
except Exception:
|
| 361 |
-
try:
|
| 362 |
-
df_[column] = df_[column].apply(parser.parse)
|
| 363 |
-
except Exception:
|
| 364 |
-
pass
|
| 365 |
-
|
| 366 |
-
if is_datetime64_any_dtype(df_[column]):
|
| 367 |
-
df_[column] = df_[column].dt.tz_localize(None)
|
| 368 |
-
min_date = df_[column].min().date()
|
| 369 |
-
max_date = df_[column].max().date()
|
| 370 |
-
user_date_input = right.date_input(
|
| 371 |
-
f"Values for {column}",
|
| 372 |
-
value=(min_date, max_date),
|
| 373 |
-
min_value=min_date,
|
| 374 |
-
max_value=max_date,
|
| 375 |
-
)
|
| 376 |
-
# if len(user_date_input) == 2:
|
| 377 |
-
# start_date, end_date = user_date_input
|
| 378 |
-
# df_ = df_.loc[df_[column].dt.date.between(start_date, end_date)]
|
| 379 |
-
if len(user_date_input) == 2:
|
| 380 |
-
user_date_input = tuple(map(pd.to_datetime, user_date_input))
|
| 381 |
-
start_date, end_date = user_date_input
|
| 382 |
-
df_ = df_.loc[df_[column].between(start_date, end_date)]
|
| 383 |
-
|
| 384 |
-
date_column = column
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
if
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
if
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
st.
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
st.
|
| 452 |
-
st.
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
"
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
base_config
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import streamlit as st
|
| 3 |
+
#import geopandas as gpd
|
| 4 |
+
from keplergl import keplergl
|
| 5 |
+
import pandas as pd
|
| 6 |
+
import streamlit as st
|
| 7 |
+
import pandas as pd
|
| 8 |
+
import numpy as np
|
| 9 |
+
import matplotlib.pyplot as plt
|
| 10 |
+
import seaborn as sns
|
| 11 |
+
from uap_analyzer import UAPParser, UAPAnalyzer, UAPVisualizer
|
| 12 |
+
# import ChartGen
|
| 13 |
+
# from ChartGen import ChartGPT
|
| 14 |
+
from Levenshtein import distance
|
| 15 |
+
from sklearn.model_selection import train_test_split
|
| 16 |
+
from sklearn.metrics import confusion_matrix
|
| 17 |
+
from stqdm import stqdm
|
| 18 |
+
stqdm.pandas()
|
| 19 |
+
import streamlit.components.v1 as components
|
| 20 |
+
from dateutil import parser
|
| 21 |
+
from sentence_transformers import SentenceTransformer
|
| 22 |
+
import torch
|
| 23 |
+
import squarify
|
| 24 |
+
import matplotlib.colors as mcolors
|
| 25 |
+
import textwrap
|
| 26 |
+
import datamapplot
|
| 27 |
+
from streamlit_extras.stateful_button import button as stateful_button
|
| 28 |
+
from streamlit_keplergl import keplergl_static
|
| 29 |
+
from keplergl import KeplerGl
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
st.set_option('deprecation.showPyplotGlobalUse', False)
|
| 33 |
+
|
| 34 |
+
from pandas.api.types import (
|
| 35 |
+
is_categorical_dtype,
|
| 36 |
+
is_datetime64_any_dtype,
|
| 37 |
+
is_numeric_dtype,
|
| 38 |
+
is_object_dtype,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
st.title('Interactive Map')
|
| 42 |
+
|
| 43 |
+
# Initialize session state
|
| 44 |
+
if 'analyzers' not in st.session_state:
|
| 45 |
+
st.session_state['analyzers'] = []
|
| 46 |
+
if 'col_names' not in st.session_state:
|
| 47 |
+
st.session_state['col_names'] = []
|
| 48 |
+
if 'clusters' not in st.session_state:
|
| 49 |
+
st.session_state['clusters'] = {}
|
| 50 |
+
if 'new_data' not in st.session_state:
|
| 51 |
+
st.session_state['new_data'] = pd.DataFrame()
|
| 52 |
+
if 'dataset' not in st.session_state:
|
| 53 |
+
st.session_state['dataset'] = pd.DataFrame()
|
| 54 |
+
if 'data_processed' not in st.session_state:
|
| 55 |
+
st.session_state['data_processed'] = False
|
| 56 |
+
if 'stage' not in st.session_state:
|
| 57 |
+
st.session_state['stage'] = 0
|
| 58 |
+
if 'filtered_data' not in st.session_state:
|
| 59 |
+
st.session_state['filtered_data'] = None
|
| 60 |
+
if 'gemini_answer' not in st.session_state:
|
| 61 |
+
st.session_state['gemini_answer'] = None
|
| 62 |
+
if 'parsed_responses' not in st.session_state:
|
| 63 |
+
st.session_state['parsed_responses'] = None
|
| 64 |
+
if 'map_generated' not in st.session_state:
|
| 65 |
+
st.session_state['map_generated'] = False
|
| 66 |
+
if 'date_loaded' not in st.session_state:
|
| 67 |
+
st.session_state['data_loaded'] = False
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
if "datasets" not in st.session_state:
|
| 71 |
+
st.session_state.datasets = []
|
| 72 |
+
|
| 73 |
+
# sf_zip_geo_gdf = gpd.read_file("sf_zip_geo.geojson")
|
| 74 |
+
# sf_zip_geo_gdf.label = "SF Zip Geo"
|
| 75 |
+
# sf_zip_geo_gdf.id = "sf-zip-geo"
|
| 76 |
+
# st.session_state.datasets.append(sf_zip_geo_gdf)
|
| 77 |
+
|
| 78 |
+
def plot_treemap(df, column, top_n=32):
|
| 79 |
+
# Get the value counts and the top N labels
|
| 80 |
+
value_counts = df[column].value_counts()
|
| 81 |
+
top_labels = value_counts.iloc[:top_n].index
|
| 82 |
+
|
| 83 |
+
# Use np.where to replace all values not in the top N with 'Other'
|
| 84 |
+
revised_column = f'{column}_revised'
|
| 85 |
+
df[revised_column] = np.where(df[column].isin(top_labels), df[column], 'Other')
|
| 86 |
+
|
| 87 |
+
# Get the value counts including the 'Other' category
|
| 88 |
+
sizes = df[revised_column].value_counts().values
|
| 89 |
+
labels = df[revised_column].value_counts().index
|
| 90 |
+
|
| 91 |
+
# Get a gradient of colors
|
| 92 |
+
# colors = list(mcolors.TABLEAU_COLORS.values())
|
| 93 |
+
|
| 94 |
+
n_colors = len(sizes)
|
| 95 |
+
colors = plt.cm.Oranges(np.linspace(0.3, 0.9, n_colors))[::-1]
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
# Get % of each category
|
| 99 |
+
percents = sizes / sizes.sum()
|
| 100 |
+
|
| 101 |
+
# Prepare labels with percentages
|
| 102 |
+
labels = [f'{label}\n {percent:.1%}' for label, percent in zip(labels, percents)]
|
| 103 |
+
|
| 104 |
+
fig, ax = plt.subplots(figsize=(20, 12))
|
| 105 |
+
|
| 106 |
+
# Plot the treemap
|
| 107 |
+
squarify.plot(sizes=sizes, label=labels, alpha=0.7, pad=True, color=colors, text_kwargs={'fontsize': 10})
|
| 108 |
+
|
| 109 |
+
ax = plt.gca()
|
| 110 |
+
# Iterate over text elements and rectangles (patches) in the axes for color adjustment
|
| 111 |
+
for text, rect in zip(ax.texts, ax.patches):
|
| 112 |
+
background_color = rect.get_facecolor()
|
| 113 |
+
r, g, b, _ = mcolors.to_rgba(background_color)
|
| 114 |
+
brightness = np.average([r, g, b])
|
| 115 |
+
text.set_color('white' if brightness < 0.5 else 'black')
|
| 116 |
+
|
| 117 |
+
# Adjust font size based on rectangle's area and wrap long text
|
| 118 |
+
coef = 0.8
|
| 119 |
+
font_size = np.sqrt(rect.get_width() * rect.get_height()) * coef
|
| 120 |
+
text.set_fontsize(font_size)
|
| 121 |
+
wrapped_text = textwrap.fill(text.get_text(), width=20)
|
| 122 |
+
text.set_text(wrapped_text)
|
| 123 |
+
|
| 124 |
+
plt.axis('off')
|
| 125 |
+
plt.gca().invert_yaxis()
|
| 126 |
+
plt.gcf().set_size_inches(20, 12)
|
| 127 |
+
|
| 128 |
+
fig.patch.set_alpha(0)
|
| 129 |
+
|
| 130 |
+
ax.patch.set_alpha(0)
|
| 131 |
+
return fig
|
| 132 |
+
|
| 133 |
+
def plot_hist(df, column, bins=10, kde=True):
|
| 134 |
+
fig, ax = plt.subplots(figsize=(12, 6))
|
| 135 |
+
sns.histplot(data=df, x=column, kde=True, bins=bins,color='orange')
|
| 136 |
+
# set the ticks and frame in orange
|
| 137 |
+
ax.spines['bottom'].set_color('orange')
|
| 138 |
+
ax.spines['top'].set_color('orange')
|
| 139 |
+
ax.spines['right'].set_color('orange')
|
| 140 |
+
ax.spines['left'].set_color('orange')
|
| 141 |
+
ax.xaxis.label.set_color('orange')
|
| 142 |
+
ax.yaxis.label.set_color('orange')
|
| 143 |
+
ax.tick_params(axis='x', colors='orange')
|
| 144 |
+
ax.tick_params(axis='y', colors='orange')
|
| 145 |
+
ax.title.set_color('orange')
|
| 146 |
+
|
| 147 |
+
# Set transparent background
|
| 148 |
+
fig.patch.set_alpha(0)
|
| 149 |
+
ax.patch.set_alpha(0)
|
| 150 |
+
return fig
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def plot_line(df, x_column, y_columns, figsize=(12, 10), color='orange', title=None, rolling_mean_value=2):
|
| 154 |
+
import matplotlib.cm as cm
|
| 155 |
+
# Sort the dataframe by the date column
|
| 156 |
+
df = df.sort_values(by=x_column)
|
| 157 |
+
|
| 158 |
+
# Calculate rolling mean for each y_column
|
| 159 |
+
if rolling_mean_value:
|
| 160 |
+
df[y_columns] = df[y_columns].rolling(len(df) // rolling_mean_value).mean()
|
| 161 |
+
|
| 162 |
+
# Create the plot
|
| 163 |
+
fig, ax = plt.subplots(figsize=figsize)
|
| 164 |
+
|
| 165 |
+
colors = cm.Oranges(np.linspace(0.2, 1, len(y_columns)))
|
| 166 |
+
|
| 167 |
+
# Plot each y_column as a separate line with a different color
|
| 168 |
+
for i, y_column in enumerate(y_columns):
|
| 169 |
+
df.plot(x=x_column, y=y_column, ax=ax, color=colors[i], label=y_column, linewidth=.5)
|
| 170 |
+
|
| 171 |
+
# Rotate x-axis labels
|
| 172 |
+
ax.set_xticklabels(ax.get_xticklabels(), rotation=30, ha='right')
|
| 173 |
+
|
| 174 |
+
# Format x_column as date if it is
|
| 175 |
+
if np.issubdtype(df[x_column].dtype, np.datetime64) or np.issubdtype(df[x_column].dtype, np.timedelta64):
|
| 176 |
+
df[x_column] = pd.to_datetime(df[x_column]).dt.date
|
| 177 |
+
|
| 178 |
+
# Set title, labels, and legend
|
| 179 |
+
ax.set_title(title or f'{", ".join(y_columns)} over {x_column}', color=color, fontweight='bold')
|
| 180 |
+
ax.set_xlabel(x_column, color=color)
|
| 181 |
+
ax.set_ylabel(', '.join(y_columns), color=color)
|
| 182 |
+
ax.spines['bottom'].set_color('orange')
|
| 183 |
+
ax.spines['top'].set_color('orange')
|
| 184 |
+
ax.spines['right'].set_color('orange')
|
| 185 |
+
ax.spines['left'].set_color('orange')
|
| 186 |
+
ax.xaxis.label.set_color('orange')
|
| 187 |
+
ax.yaxis.label.set_color('orange')
|
| 188 |
+
ax.tick_params(axis='x', colors='orange')
|
| 189 |
+
ax.tick_params(axis='y', colors='orange')
|
| 190 |
+
ax.title.set_color('orange')
|
| 191 |
+
|
| 192 |
+
ax.legend(loc='upper right', bbox_to_anchor=(1, 1), facecolor='black', framealpha=.4, labelcolor='orange', edgecolor='orange')
|
| 193 |
+
|
| 194 |
+
# Remove background
|
| 195 |
+
fig.patch.set_alpha(0)
|
| 196 |
+
ax.patch.set_alpha(0)
|
| 197 |
+
|
| 198 |
+
return fig
|
| 199 |
+
|
| 200 |
+
def plot_bar(df, x_column, y_column, figsize=(12, 10), color='orange', title=None):
|
| 201 |
+
fig, ax = plt.subplots(figsize=figsize)
|
| 202 |
+
|
| 203 |
+
sns.barplot(data=df, x=x_column, y=y_column, color=color, ax=ax)
|
| 204 |
+
|
| 205 |
+
ax.set_title(title if title else f'{y_column} by {x_column}', color=color, fontweight='bold')
|
| 206 |
+
ax.set_xlabel(x_column, color=color)
|
| 207 |
+
ax.set_ylabel(y_column, color=color)
|
| 208 |
+
|
| 209 |
+
ax.tick_params(axis='x', colors=color)
|
| 210 |
+
ax.tick_params(axis='y', colors=color)
|
| 211 |
+
|
| 212 |
+
# Remove background
|
| 213 |
+
fig.patch.set_alpha(0)
|
| 214 |
+
ax.patch.set_alpha(0)
|
| 215 |
+
ax.spines['bottom'].set_color('orange')
|
| 216 |
+
ax.spines['top'].set_color('orange')
|
| 217 |
+
ax.spines['right'].set_color('orange')
|
| 218 |
+
ax.spines['left'].set_color('orange')
|
| 219 |
+
ax.xaxis.label.set_color('orange')
|
| 220 |
+
ax.yaxis.label.set_color('orange')
|
| 221 |
+
ax.tick_params(axis='x', colors='orange')
|
| 222 |
+
ax.tick_params(axis='y', colors='orange')
|
| 223 |
+
ax.title.set_color('orange')
|
| 224 |
+
ax.legend(loc='upper right', bbox_to_anchor=(1, 1), facecolor='black', framealpha=.4, labelcolor='orange', edgecolor='orange')
|
| 225 |
+
|
| 226 |
+
return fig
|
| 227 |
+
|
| 228 |
+
def plot_grouped_bar(df, x_columns, y_column, figsize=(12, 10), colors=None, title=None):
|
| 229 |
+
fig, ax = plt.subplots(figsize=figsize)
|
| 230 |
+
|
| 231 |
+
width = 0.8 / len(x_columns) # the width of the bars
|
| 232 |
+
x = np.arange(len(df)) # the label locations
|
| 233 |
+
|
| 234 |
+
for i, x_column in enumerate(x_columns):
|
| 235 |
+
sns.barplot(data=df, x=x, y=y_column, color=colors[i] if colors else None, ax=ax, width=width, label=x_column)
|
| 236 |
+
x += width # add the width of the bar to the x position for the next bar
|
| 237 |
+
|
| 238 |
+
ax.set_title(title if title else f'{y_column} by {", ".join(x_columns)}', color='orange', fontweight='bold')
|
| 239 |
+
ax.set_xlabel('Groups', color='orange')
|
| 240 |
+
ax.set_ylabel(y_column, color='orange')
|
| 241 |
+
|
| 242 |
+
ax.set_xticks(x - width * len(x_columns) / 2)
|
| 243 |
+
ax.set_xticklabels(df.index)
|
| 244 |
+
|
| 245 |
+
ax.tick_params(axis='x', colors='orange')
|
| 246 |
+
ax.tick_params(axis='y', colors='orange')
|
| 247 |
+
|
| 248 |
+
# Remove background
|
| 249 |
+
fig.patch.set_alpha(0)
|
| 250 |
+
ax.patch.set_alpha(0)
|
| 251 |
+
ax.spines['bottom'].set_color('orange')
|
| 252 |
+
ax.spines['top'].set_color('orange')
|
| 253 |
+
ax.spines['right'].set_color('orange')
|
| 254 |
+
ax.spines['left'].set_color('orange')
|
| 255 |
+
ax.xaxis.label.set_color('orange')
|
| 256 |
+
ax.yaxis.label.set_color('orange')
|
| 257 |
+
ax.title.set_color('orange')
|
| 258 |
+
ax.legend(loc='upper right', bbox_to_anchor=(1, 1), facecolor='black', framealpha=.4, labelcolor='orange', edgecolor='orange')
|
| 259 |
+
|
| 260 |
+
return fig
|
| 261 |
+
|
| 262 |
+
def generate_kepler_map(data):
|
| 263 |
+
map_config = keplergl(data, height=400)
|
| 264 |
+
return map_config
|
| 265 |
+
|
| 266 |
+
def filter_dataframe(df: pd.DataFrame) -> pd.DataFrame:
|
| 267 |
+
"""
|
| 268 |
+
Adds a UI on top of a dataframe to let viewers filter columns
|
| 269 |
+
|
| 270 |
+
Args:
|
| 271 |
+
df (pd.DataFrame): Original dataframe
|
| 272 |
+
|
| 273 |
+
Returns:
|
| 274 |
+
pd.DataFrame: Filtered dataframe
|
| 275 |
+
"""
|
| 276 |
+
|
| 277 |
+
title_font = "Arial"
|
| 278 |
+
body_font = "Arial"
|
| 279 |
+
title_size = 32
|
| 280 |
+
colors = ["red", "green", "blue"]
|
| 281 |
+
interpretation = False
|
| 282 |
+
extract_docx = False
|
| 283 |
+
title = "My Chart"
|
| 284 |
+
regex = ".*"
|
| 285 |
+
img_path = 'default_image.png'
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
#try:
|
| 289 |
+
# modify = st.checkbox("Add filters on raw data")
|
| 290 |
+
#except:
|
| 291 |
+
# try:
|
| 292 |
+
# modify = st.checkbox("Add filters on processed data")
|
| 293 |
+
# except:
|
| 294 |
+
# try:
|
| 295 |
+
# modify = st.checkbox("Add filters on parsed data")
|
| 296 |
+
# except:
|
| 297 |
+
# pass
|
| 298 |
+
|
| 299 |
+
#if not modify:
|
| 300 |
+
# return df
|
| 301 |
+
|
| 302 |
+
df_ = df.copy()
|
| 303 |
+
# Try to convert datetimes into a standard format (datetime, no timezone)
|
| 304 |
+
|
| 305 |
+
#modification_container = st.container()
|
| 306 |
+
|
| 307 |
+
#with modification_container:
|
| 308 |
+
try:
|
| 309 |
+
to_filter_columns = st.multiselect("Filter dataframe on", df_.columns)
|
| 310 |
+
except:
|
| 311 |
+
try:
|
| 312 |
+
to_filter_columns = st.multiselect("Filter dataframe", df_.columns)
|
| 313 |
+
except:
|
| 314 |
+
try:
|
| 315 |
+
to_filter_columns = st.multiselect("Filter the dataframe on", df_.columns)
|
| 316 |
+
except:
|
| 317 |
+
pass
|
| 318 |
+
|
| 319 |
+
date_column = None
|
| 320 |
+
filtered_columns = []
|
| 321 |
+
|
| 322 |
+
for column in to_filter_columns:
|
| 323 |
+
left, right = st.columns((1, 20))
|
| 324 |
+
# Treat columns with < 200 unique values as categorical if not date or numeric
|
| 325 |
+
if is_categorical_dtype(df_[column]) or (df_[column].nunique() < 120 and not is_datetime64_any_dtype(df_[column]) and not is_numeric_dtype(df_[column])):
|
| 326 |
+
user_cat_input = right.multiselect(
|
| 327 |
+
f"Values for {column}",
|
| 328 |
+
df_[column].value_counts().index.tolist(),
|
| 329 |
+
default=list(df_[column].value_counts().index)
|
| 330 |
+
)
|
| 331 |
+
df_ = df_[df_[column].isin(user_cat_input)]
|
| 332 |
+
filtered_columns.append(column)
|
| 333 |
+
|
| 334 |
+
with st.status(f"Category Distribution: {column}", expanded=False) as stat:
|
| 335 |
+
st.pyplot(plot_treemap(df_, column))
|
| 336 |
+
|
| 337 |
+
elif is_numeric_dtype(df_[column]):
|
| 338 |
+
_min = float(df_[column].min())
|
| 339 |
+
_max = float(df_[column].max())
|
| 340 |
+
step = (_max - _min) / 100
|
| 341 |
+
user_num_input = right.slider(
|
| 342 |
+
f"Values for {column}",
|
| 343 |
+
min_value=_min,
|
| 344 |
+
max_value=_max,
|
| 345 |
+
value=(_min, _max),
|
| 346 |
+
step=step,
|
| 347 |
+
)
|
| 348 |
+
df_ = df_[df_[column].between(*user_num_input)]
|
| 349 |
+
filtered_columns.append(column)
|
| 350 |
+
|
| 351 |
+
# Chart_GPT = ChartGPT(df_, title_font, body_font, title_size,
|
| 352 |
+
# colors, interpretation, extract_docx, img_path)
|
| 353 |
+
|
| 354 |
+
with st.status(f"Numerical Distribution: {column}", expanded=False) as stat_:
|
| 355 |
+
st.pyplot(plot_hist(df_, column, bins=int(round(len(df_[column].unique())-1)/2)))
|
| 356 |
+
|
| 357 |
+
elif is_object_dtype(df_[column]):
|
| 358 |
+
try:
|
| 359 |
+
df_[column] = pd.to_datetime(df_[column], infer_datetime_format=True, errors='coerce')
|
| 360 |
+
except Exception:
|
| 361 |
+
try:
|
| 362 |
+
df_[column] = df_[column].apply(parser.parse)
|
| 363 |
+
except Exception:
|
| 364 |
+
pass
|
| 365 |
+
|
| 366 |
+
if is_datetime64_any_dtype(df_[column]):
|
| 367 |
+
df_[column] = df_[column].dt.tz_localize(None)
|
| 368 |
+
min_date = df_[column].min().date()
|
| 369 |
+
max_date = df_[column].max().date()
|
| 370 |
+
user_date_input = right.date_input(
|
| 371 |
+
f"Values for {column}",
|
| 372 |
+
value=(min_date, max_date),
|
| 373 |
+
min_value=min_date,
|
| 374 |
+
max_value=max_date,
|
| 375 |
+
)
|
| 376 |
+
# if len(user_date_input) == 2:
|
| 377 |
+
# start_date, end_date = user_date_input
|
| 378 |
+
# df_ = df_.loc[df_[column].dt.date.between(start_date, end_date)]
|
| 379 |
+
if len(user_date_input) == 2:
|
| 380 |
+
user_date_input = tuple(map(pd.to_datetime, user_date_input))
|
| 381 |
+
start_date, end_date = user_date_input
|
| 382 |
+
df_ = df_.loc[df_[column].between(start_date, end_date)]
|
| 383 |
+
|
| 384 |
+
date_column = column
|
| 385 |
+
df_[column] = df_[column].dt.strftime('%Y-%m-%d %H:%M:%S')
|
| 386 |
+
|
| 387 |
+
if date_column and filtered_columns:
|
| 388 |
+
numeric_columns = [col for col in filtered_columns if is_numeric_dtype(df_[col])]
|
| 389 |
+
if numeric_columns:
|
| 390 |
+
fig = plot_line(df_, date_column, numeric_columns)
|
| 391 |
+
#st.pyplot(fig)
|
| 392 |
+
# now to deal with categorical columns
|
| 393 |
+
categorical_columns = [col for col in filtered_columns if is_categorical_dtype(df_[col])]
|
| 394 |
+
if categorical_columns:
|
| 395 |
+
fig2 = plot_bar(df_, date_column, categorical_columns[0])
|
| 396 |
+
#st.pyplot(fig2)
|
| 397 |
+
with st.status(f"Date Distribution: {column}", expanded=False) as stat:
|
| 398 |
+
try:
|
| 399 |
+
st.pyplot(fig)
|
| 400 |
+
except Exception as e:
|
| 401 |
+
st.error(f"Error plotting line chart: {e}")
|
| 402 |
+
pass
|
| 403 |
+
try:
|
| 404 |
+
st.pyplot(fig2)
|
| 405 |
+
except Exception as e:
|
| 406 |
+
st.error(f"Error plotting bar chart: {e}")
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
else:
|
| 410 |
+
user_text_input = right.text_input(
|
| 411 |
+
f"Substring or regex in {column}",
|
| 412 |
+
)
|
| 413 |
+
if user_text_input:
|
| 414 |
+
df_ = df_[df_[column].astype(str).str.contains(user_text_input)]
|
| 415 |
+
# write len of df after filtering with % of original
|
| 416 |
+
st.write(f"{len(df_)} rows ({len(df_) / len(df) * 100:.2f}%)")
|
| 417 |
+
return df_
|
| 418 |
+
|
| 419 |
+
def find_lat_lon_columns(df):
|
| 420 |
+
lat_columns = df.columns[df.columns.str.lower().str.contains('lat')]
|
| 421 |
+
lon_columns = df.columns[df.columns.str.lower().str.contains('lon|lng')]
|
| 422 |
+
|
| 423 |
+
if len(lat_columns) > 0 and len(lon_columns) > 0:
|
| 424 |
+
return lat_columns[0], lon_columns[0]
|
| 425 |
+
else:
|
| 426 |
+
return None, None
|
| 427 |
+
|
| 428 |
+
my_dataset = st.file_uploader("Upload Parsed DataFrame", type=["csv", "xlsx"])
|
| 429 |
+
map_1 = KeplerGl(height=800)
|
| 430 |
+
powerplant = pd.read_csv('global_power_plant_database.csv')
|
| 431 |
+
secret_bases = pd.read_csv('secret_bases.csv')
|
| 432 |
+
|
| 433 |
+
map_1.add_data(
|
| 434 |
+
data=secret_bases, name="secret_bases"
|
| 435 |
+
)
|
| 436 |
+
map_1.add_data(
|
| 437 |
+
data=powerplant, name='nuclear_powerplants'
|
| 438 |
+
)
|
| 439 |
+
|
| 440 |
+
|
| 441 |
+
if my_dataset is not None :
|
| 442 |
+
try:
|
| 443 |
+
if my_dataset.type == "text/csv":
|
| 444 |
+
data = pd.read_csv(my_dataset)
|
| 445 |
+
elif my_dataset.type == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
|
| 446 |
+
data = pd.read_excel(my_dataset)
|
| 447 |
+
else:
|
| 448 |
+
st.error("Unsupported file type. Please upload a CSV, Excel or HD5 file.")
|
| 449 |
+
st.stop()
|
| 450 |
+
parser = filter_dataframe(data)
|
| 451 |
+
st.session_state['parsed_responses'] = parser
|
| 452 |
+
st.dataframe(parser)
|
| 453 |
+
st.success(f"Successfully loaded and displayed data from {my_dataset.name}")
|
| 454 |
+
#h3_hex_id_df = pd.read_csv("keplergl/h3_data.csv")
|
| 455 |
+
st.session_state['data_loaded'] = True
|
| 456 |
+
# Load the base config
|
| 457 |
+
with open('military_config.kgl', 'r') as f:
|
| 458 |
+
base_config = json.load(f)
|
| 459 |
+
|
| 460 |
+
with open('uap_config.kgl', 'r') as f:
|
| 461 |
+
uap_config = json.load(f)
|
| 462 |
+
|
| 463 |
+
if parser.columns.str.contains('date').any():
|
| 464 |
+
# Get the date column name
|
| 465 |
+
date_column = parser.columns[parser.columns.str.contains('date')].values[0]
|
| 466 |
+
|
| 467 |
+
# Create a new filter
|
| 468 |
+
new_filter = {
|
| 469 |
+
"dataId": "uap_sightings",
|
| 470 |
+
"name": date_column
|
| 471 |
+
}
|
| 472 |
+
|
| 473 |
+
# Append the new filter to the existing filters
|
| 474 |
+
base_config['config']['visState']['filters'].append(new_filter)
|
| 475 |
+
|
| 476 |
+
# Update the map config
|
| 477 |
+
map_1.config = base_config
|
| 478 |
+
|
| 479 |
+
map_1.add_data(
|
| 480 |
+
data=parser, name="uap_sightings"
|
| 481 |
+
)
|
| 482 |
+
|
| 483 |
+
# Find the latitude and longitude columns in the dataframe
|
| 484 |
+
lat_col, lon_col = find_lat_lon_columns(parser)
|
| 485 |
+
|
| 486 |
+
if lat_col and lon_col:
|
| 487 |
+
# Update the layer configurations
|
| 488 |
+
for layer in uap_config['config']['visState']['layers']:
|
| 489 |
+
if 'config' in layer and 'columns' in layer['config']:
|
| 490 |
+
if 'lat' in layer['config']['columns']:
|
| 491 |
+
layer['config']['columns']['lat'] = lat_col
|
| 492 |
+
if 'lng' in layer['config']['columns']:
|
| 493 |
+
layer['config']['columns']['lng'] = lon_col
|
| 494 |
+
|
| 495 |
+
# Now extend the base_config with the updated uap_config layers
|
| 496 |
+
base_config['config']['visState']['layers'].extend(uap_config['config']['visState']['layers'])
|
| 497 |
+
map_1.config = base_config
|
| 498 |
+
else:
|
| 499 |
+
base_config['config']['visState']['layers'].extend([layer for layer in uap_config['config']['visState']['layers']])
|
| 500 |
+
map_1.config = base_config
|
| 501 |
+
|
| 502 |
+
keplergl_static(map_1, center_map=True)
|
| 503 |
+
st.session_state['map_generated'] = True
|
| 504 |
+
except Exception as e:
|
| 505 |
+
st.error(f"An error occurred while reading the file: {e}")
|
| 506 |
+
else:
|
| 507 |
+
st.warning("Please upload a file to get started.")
|