# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# +
import pandas as pd
import geopandas as gpd
import matplotlib.pyplot as plt
import matplotlib
import folium
import folium.plugins
import mapclassify
import numpy as np
import cv2
import base64
import webbrowser

data = pd.read_csv("../../data/full/train/data_train.csv")


# + pycharm={"name": "#%%\n"}
def create_popup(image_path: str) -> folium.Popup:
    encoded = base64.b64encode(open(image_path, 'rb').read())
    html = '<img src="data:image/png;base64,{}" width="200" height="200">'.format
    iframe = folium.IFrame(html(encoded.decode('UTF-8')), width=220, height=220)
    return folium.Popup(iframe, max_width=400)


# + pycharm={"name": "#%%\n"}
def create_interactive_map(df: pd.DataFrame, output_html_path: str, group_column: str = None, group_columns : list = None) -> str:
    """
    Input:
        df: pd.DataFrame
            Input data.
        output_html_path : str
            Where to save the interactive map html.
        group_column : str
            If not None, specifies which column defines the group / cluster. Each group will be colored differently on the map.
        group_columns : list of column names
            If not None, specifies which columns define the RGB (blue -> red -> green) color of the dots.

    Output:
        map_path: str
            Path to HTML interactive map.
    """

    if group_column and group_columns:
        print("Error! Can't color by both class and value.")
        return "err"

    # colormap
    n_clusters = 1
    if group_column:
        n_clusters = df[group_column].nunique()
        colors = ['red', 'blue', 'green', 'purple', 'orange', 'darkred', 'lightred', 'beige', 'darkblue', 'darkgreen',
                  'cadetblue', 'darkpurple', 'white', 'pink', 'lightblue', 'lightgreen', 'gray', 'black', 'lightgray']

    if group_columns:
        colors = np.zeros((len(df), 3))
        for idx, col in enumerate(group_columns):
             colors[:, idx] = df[col].values
             colors[:, idx] = (colors[:, idx] - colors[:, idx].min()) / (colors[:, idx].max() - colors[:, idx].min())

        colors = colors[:, [1, 2, 0]]

    def get_color(idx, row: pd.Series):
        if group_column:
            return colors[row[group_column]]
        if group_columns:
            return matplotlib.colors.to_hex(colors[idx, :])
        return 'cadetblue'

    map_path = output_html_path + "brightness2.html"
    map = folium.Map(location=[44.813555, 15.978054], zoom_start=8, tiles="cartodb positron",
                     max_bounds=True,
                     min_lat=42.44, max_lat=48.55,
                     min_lon=13.5, max_lon=19.43,
                     min_zoom=8,
                     prefer_canvas=True
                     )

    for idx, (_, row) in enumerate(df.iterrows()):
        angle = str(np.random.choice([0, 90, 180, 270]))
        image_path = f"../../data/full/train/{row.uuid}/{angle}.jpg"
        popup = create_popup(image_path)
        lat, long = round(row.latitude, 3), round(row.longitude, 3)
        folium.CircleMarker(location=(row.latitude, row.longitude), radius=4,
                            popup=popup, tooltip=f"({lat}, {long})",
                            color=get_color(idx, row), fill=False,  #get_color(row),
                            ).add_to(map)

    map.save(map_path)
    return map_path


# + pycharm={"name": "#%%\n"}
from skimage.io import imread

temp = data.sample(250).copy()


for index in temp.index.values:
    M = 0
    for angle in [0, 90, 180, 270]:
        image_path = f"../../data/full/train/{temp.loc[index, 'uuid']}/{angle}.jpg"
        img = imread(image_path)
        M += img.mean() / 4
    temp.loc[index, 'brightness'] = M

temp['brightness'] = (temp['brightness'] - temp['brightness'].min()) / (temp['brightness'].max() - temp['brightness'].min())
temp['brightness'] = 1/(1 + np.exp(-temp['brightness']))

# + pycharm={"name": "#%%\n"}
# temp = data.sample(120).copy()
# temp["cluster"] = np.random.randint(0, 5, 120)
# map_path = create_interactive_map(df=temp, output_html_path="", group_column="cluster")
# webbrowser.open(map_path)




temp[["a", "b"]] = np.random.randn(len(temp), 2)
map_path = create_interactive_map(df=temp, output_html_path="", group_columns=["brightness", "brightness"])
webbrowser.open(map_path)

# + pycharm={"name": "#%%\n"}


StarcoderdataJupyterScriptsDedupFiltered