PLN-G4-PF / Interfaz Web.ipynb
Interfaz Web.ipynb
Raw
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import geopandas as gpd\n",
    "\n",
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "from sklearn.neighbors import KNeighborsRegressor\n",
    "from sklearn.ensemble import GradientBoostingRegressor\n",
    "from sklearn.linear_model import Lasso, Ridge\n",
    "from sklearn.linear_model import LinearRegression\n",
    "from sklearn.svm import SVR\n",
    "from sklearn.ensemble import RandomForestRegressor\n",
    "\n",
    "from sklearn.ensemble import GradientBoostingClassifier\n",
    "from sklearn.tree import DecisionTreeClassifier\n",
    "from sklearn.linear_model import LogisticRegression\n",
    "from sklearn.svm import SVC\n",
    "from sklearn.neighbors import KNeighborsClassifier\n",
    "from sklearn.ensemble import RandomForestClassifier\n",
    "from sklearn.naive_bayes import GaussianNB\n",
    "import pickle\n",
    "\n",
    "from sklearn.metrics import accuracy_score\n",
    "from sklearn.metrics import mean_squared_error\n",
    "\n",
    "import numpy as np\n",
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "def preprocess_inputs(name):\n",
    "    data_geo = gpd.read_file('https://raw.githubusercontent.com/CMinge77/DBjson/main/uBurt.json')\n",
    "    df_variables = pd.read_csv('datasets/{}'.format(name), index_col=[0])\n",
    "\n",
    "    X, y = df_variables[['support_rate_rodolfo', 'tasa_aumento_pib', 'tasa_aumento_desempleo']], df_variables['support_rate_rodolfo_real']\n",
    "    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=5682)\n",
    "    RF_reg = RandomForestRegressor(max_depth=2, random_state=0)\n",
    "    RF_reg.fit(X_train, y_train)\n",
    "\n",
    "    y_class = np.round(y).astype(int)\n",
    "    X_train, X_test, y_train, y_test = train_test_split(X, y_class, test_size=0.3, random_state=5682)\n",
    "    DT_class = DecisionTreeClassifier(random_state=0)\n",
    "    DT_class.fit(X_train, y_train)\n",
    "\n",
    "    df_variables['prediccion_regresion'] = RF_reg.predict(df_variables[['support_rate_rodolfo','tasa_aumento_pib','tasa_aumento_desempleo']])\n",
    "    df_variables['prediccion_clasificacion'] = DT_class.predict(df_variables[['support_rate_rodolfo','tasa_aumento_pib','tasa_aumento_desempleo']])\n",
    "    df_variables['ubicacion'] = df_variables['ubicacion'].str.replace('Bogotá', 'Cundinamarca')\n",
    "\n",
    "    data_geo = data_geo.merge(df_variables, left_on='NAME_1', right_on='ubicacion', how='left')\n",
    "    data_geo = data_geo.drop('ubicacion', axis=1)\n",
    "\n",
    "    data_geo['support_rate_rodolfo'] = (data_geo['support_rate_rodolfo']*100)\n",
    "    data_geo['tasa_aumento_pib'] = (data_geo['tasa_aumento_pib']*100)\n",
    "    data_geo['tasa_aumento_desempleo'] = (data_geo['tasa_aumento_desempleo']*100)\n",
    "    data_geo['support_rate_rodolfo_real'] = (data_geo['support_rate_rodolfo_real']*100)\n",
    "    data_geo['support_rate_rodolfo_real_b'] = np.round(data_geo['support_rate_rodolfo_real']/100)\n",
    "\n",
    "    data_geo['support_rate_rodolfo'] = pd.to_numeric(data_geo['support_rate_rodolfo'],errors='coerce')\n",
    "    data_geo['tasa_aumento_pib'] = pd.to_numeric(data_geo['tasa_aumento_pib'],errors='coerce')\n",
    "    data_geo['tasa_aumento_desempleo'] = pd.to_numeric(data_geo['tasa_aumento_desempleo'],errors='coerce')\n",
    "    data_geo['support_rate_rodolfo_real'] = pd.to_numeric(data_geo['support_rate_rodolfo_real'],errors='coerce')\n",
    "    data_geo['prediccion_clasificacion'] = pd.to_numeric(data_geo['prediccion_clasificacion'],errors='coerce')\n",
    "    data_geo['prediccion_regresion'] = pd.to_numeric(data_geo['prediccion_regresion'],errors='coerce')\n",
    "    data_geo['VARNAME_1'] = pd.to_numeric(data_geo['VARNAME_1'],errors='coerce')\n",
    "\n",
    "    data_geo = data_geo.drop_duplicates()\n",
    "\n",
    "    return data_geo"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "def load_model(sentiment_model_name, model_name, dept):\n",
    "    \n",
    "    sentiment_model_name = sentiment_model_name.get()\n",
    "    model_name = model_name.get()\n",
    "    dept = dept.get()\n",
    "\n",
    "    if sentiment_model_name == 'Robertuito':\n",
    "        name = 'variables_procesadas_robertuito-sentiment-analysis.csv'\n",
    "    elif sentiment_model_name == 'Beto':\n",
    "        name = 'variables_procesadas_bert_BetoSentimentAnalysis.csv'\n",
    "    elif sentiment_model_name == 'Codeswitch':\n",
    "        name = 'variables_procesadas_codeswitch-spaeng-sentiment-analysis-lince.csv'\n",
    "    else:\n",
    "        name = 'variables_procesadas_robertuito-sentiment-analysis.csv'\n",
    "\n",
    "    df_variables = pd.read_csv('datasets/{}'.format(name), index_col=[0])\n",
    "    X, y = df_variables[['support_rate_rodolfo', 'tasa_aumento_pib', 'tasa_aumento_desempleo']], df_variables['support_rate_rodolfo_real']\n",
    "    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=5682)\n",
    "    \n",
    "    y_class = np.round(y).astype(int)\n",
    "    X_train_c, X_test_c, y_train_c, y_test_c = train_test_split(X, y_class, test_size=0.3, random_state=5682)\n",
    "\n",
    "    if model_name == 'Gaussian Naive Bayes Classifier':\n",
    "        model = GaussianNB()\n",
    "        model.fit(X_train_c, y_train_c)\n",
    "        y_pred = model.predict(X_test_c)\n",
    "    elif model_name == 'Random Forest Classifier':\n",
    "        model = RandomForestClassifier(max_depth=2, random_state=0)\n",
    "        model.fit(X_train_c, y_train_c)\n",
    "        y_pred = model.predict(X_test_c)\n",
    "    elif model_name == 'MLP Classifier':\n",
    "        model = keras.models.Sequential()\n",
    "        model.add(keras.layers.Dense(4, activation=\"relu\"))\n",
    "        model.add(keras.layers.Dense(3, activation=\"relu\"))\n",
    "        model.add(keras.layers.Dense(2, activation=\"relu\"))\n",
    "        model.add(keras.layers.Dense(1, activation='softmax'))\n",
    "        model.compile(loss=\"binary_crossentropy\", optimizer=\"adam\", metrics=[\"accuracy\"])\n",
    "        history = model.fit(X_train_c, y_train_c, epochs=30, verbose=False)\n",
    "        y_pred = model.predict(X_test_c, verbose=False)\n",
    "    elif model_name == 'Gradient Boosting Classifier':\n",
    "        model = GradientBoostingClassifier(n_estimators=100, learning_rate=1.0, max_depth=1, random_state=0)\n",
    "        model.fit(X_train_c, y_train_c)\n",
    "        y_pred = model.predict(X_test_c)\n",
    "    elif model_name == 'Decision Tree Classifier':\n",
    "        model = DecisionTreeClassifier(random_state=0)\n",
    "        model.fit(X_train_c, y_train_c)\n",
    "        y_pred = model.predict(X_test_c)\n",
    "    elif model_name == 'K-Nearest-Neighbors Classifier':\n",
    "        model = KNeighborsClassifier(n_neighbors=3)\n",
    "        model.fit(X_train_c, y_train_c)\n",
    "        y_pred = model.predict(X_test_c)\n",
    "    elif model_name == 'Logistic Regression Classifier':\n",
    "        model = LogisticRegression(random_state=0)\n",
    "        model.fit(X_train_c, y_train_c)\n",
    "        y_pred = model.predict(X_test_c)\n",
    "    elif model_name == 'Support Vector Classifier':\n",
    "        model = SVC(gamma='auto')\n",
    "        model.fit(X_train_c, y_train_c)\n",
    "        y_pred = model.predict(X_test_c)\n",
    "    elif model_name == 'Linear Regression':\n",
    "        model = LinearRegression()\n",
    "        model.fit(X_train, y_train)\n",
    "        y_pred = model.predict(X_test)\n",
    "    elif model_name == 'Support Vector Regression':\n",
    "        model = SVR(C=1.0, epsilon=0.2)\n",
    "        model.fit(X_train, y_train)\n",
    "        y_pred = model.predict(X_test)\n",
    "    elif model_name == 'Random Forest Regression':\n",
    "        model = RandomForestRegressor(max_depth=2, random_state=0)\n",
    "        model.fit(X_train, y_train)\n",
    "        y_pred = model.predict(X_test)\n",
    "    elif model_name == 'Ridge Regression':\n",
    "        model = Ridge(alpha=0.1)\n",
    "        model.fit(X_train, y_train)\n",
    "        y_pred = model.predict(X_test)\n",
    "    elif model_name == 'Lasso Regression':\n",
    "        model = Lasso(alpha=0.1)\n",
    "        model.fit(X_train, y_train)\n",
    "        y_pred = model.predict(X_test)\n",
    "    elif model_name == 'Gradient Boosting Trees Regression':\n",
    "        model = GradientBoostingRegressor(n_estimators=100, learning_rate=1.0, max_depth=1, random_state=0)\n",
    "        model.fit(X_train, y_train)\n",
    "        y_pred = model.predict(X_test)\n",
    "    elif model_name == 'k-Nearest-Neighbors Regression':\n",
    "        model = KNeighborsRegressor(n_neighbors=3)\n",
    "        model.fit(X_train, y_train)\n",
    "        y_pred = model.predict(X_test)\n",
    "    elif model_name == 'MLP Regression':\n",
    "        model = keras.models.Sequential()\n",
    "        model.add(keras.layers.Dense(4, activation=\"relu\"))\n",
    "        model.add(keras.layers.Dense(3, activation=\"relu\"))\n",
    "        model.add(keras.layers.Dense(2, activation=\"relu\"))\n",
    "        model.add(keras.layers.Dense(1))\n",
    "        model.compile(loss=\"mean_squared_error\", optimizer=\"adam\", metrics=[\"mse\"])\n",
    "        history = model.fit(X_train, y_train, epochs=30, verbose=False)\n",
    "        y_pred = model.predict(X_test, verbose=False)\n",
    "    \n",
    "    if model_name[-10:] == 'Classifier':\n",
    "        #metricas de evaluacion de modelo\n",
    "        metric = \"Accuracy: {}\".format(np.round(accuracy_score(np.round(y_test.values).astype(int), y_pred), decimals=4))\n",
    "    elif model_name[-10:] == 'Regression':\n",
    "        #RMSE\n",
    "        metric = 'RMSE: {}'.format(np.round(mean_squared_error(y_test, y_pred, squared=False), decimals=4))\n",
    "\n",
    "    df_variables['prediccion'] = model.predict(df_variables[['support_rate_rodolfo','tasa_aumento_pib','tasa_aumento_desempleo']])\n",
    "    dept_pred = df_variables[df_variables['ubicacion'] == dept]['prediccion'].values[0]\n",
    "    support_real = df_variables[df_variables['ubicacion'] == dept]['support_rate_rodolfo'].values[0]\n",
    "    tasa_pib = df_variables[df_variables['ubicacion'] == dept]['tasa_aumento_pib'].values[0]\n",
    "    tasa_desempleo = df_variables[df_variables['ubicacion'] == dept]['tasa_aumento_desempleo'].values[0]\n",
    "\n",
    "    \n",
    "    return metric, np.round(dept_pred, decimals=4), np.round(support_real, decimals=4), np.round(tasa_pib, decimals=4), np.round(tasa_desempleo, decimals=4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Exception ignored in: <function PhotoImage.__del__ at 0x00000202303E2E60>\n",
      "Traceback (most recent call last):\n",
      "  File \"d:\\Anaconda_39\\envs\\DL\\lib\\site-packages\\PIL\\ImageTk.py\", line 118, in __del__\n",
      "    name = self.__photo.name\n",
      "AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'\n",
      "Exception ignored in: <function PhotoImage.__del__ at 0x00000202303E2E60>\n",
      "Traceback (most recent call last):\n",
      "  File \"d:\\Anaconda_39\\envs\\DL\\lib\\site-packages\\PIL\\ImageTk.py\", line 118, in __del__\n",
      "Exception ignored in: <function PhotoImage.__del__ at 0x00000202303E2E60>\n",
      "Traceback (most recent call last):\n",
      "  File \"d:\\Anaconda_39\\envs\\DL\\lib\\site-packages\\PIL\\ImageTk.py\", line 118, in __del__\n",
      "    name = self.__photo.name\n",
      "AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'\n",
      "    name = self.__photo.name\n",
      "AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'\n",
      "Exception ignored in: <function PhotoImage.__del__ at 0x00000202303E2E60>\n",
      "Traceback (most recent call last):\n",
      "  File \"d:\\Anaconda_39\\envs\\DL\\lib\\site-packages\\PIL\\ImageTk.py\", line 118, in __del__\n",
      "Exception ignored in: <function PhotoImage.__del__ at 0x00000202303E2E60>\n",
      "Traceback (most recent call last):\n",
      "  File \"d:\\Anaconda_39\\envs\\DL\\lib\\site-packages\\PIL\\ImageTk.py\", line 118, in __del__\n",
      "    name = self.__photo.name\n",
      "AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'\n",
      "    name = self.__photo.name\n",
      "AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'\n",
      "Exception ignored in: <function PhotoImage.__del__ at 0x00000202303E2E60>\n",
      "Traceback (most recent call last):\n",
      "  File \"d:\\Anaconda_39\\envs\\DL\\lib\\site-packages\\PIL\\ImageTk.py\", line 118, in __del__\n",
      "Exception ignored in: <function PhotoImage.__del__ at 0x00000202303E2E60>\n",
      "Traceback (most recent call last):\n",
      "  File \"d:\\Anaconda_39\\envs\\DL\\lib\\site-packages\\PIL\\ImageTk.py\", line 118, in __del__\n",
      "Exception ignored in: <function PhotoImage.__del__ at 0x00000202303E2E60>\n",
      "Traceback (most recent call last):\n",
      "  File \"d:\\Anaconda_39\\envs\\DL\\lib\\site-packages\\PIL\\ImageTk.py\", line 118, in __del__\n",
      "Exception ignored in: <function PhotoImage.__del__ at 0x00000202303E2E60>\n",
      "Traceback (most recent call last):\n",
      "  File \"d:\\Anaconda_39\\envs\\DL\\lib\\site-packages\\PIL\\ImageTk.py\", line 118, in __del__\n",
      "        name = self.__photo.name\n",
      "AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'\n",
      "    name = self.__photo.name\n",
      "AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'\n",
      "name = self.__photo.name\n",
      "AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'\n",
      "    name = self.__photo.name\n",
      "AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'\n",
      "Exception ignored in: <function PhotoImage.__del__ at 0x00000202303E2E60>\n",
      "Traceback (most recent call last):\n",
      "  File \"d:\\Anaconda_39\\envs\\DL\\lib\\site-packages\\PIL\\ImageTk.py\", line 118, in __del__\n",
      "Exception ignored in: <function PhotoImage.__del__ at 0x00000202303E2E60>\n",
      "Traceback (most recent call last):\n",
      "  File \"d:\\Anaconda_39\\envs\\DL\\lib\\site-packages\\PIL\\ImageTk.py\", line 118, in __del__\n",
      "    name = self.__photo.name\n",
      "AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'\n",
      "    name = self.__photo.name\n",
      "AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'\n",
      "Exception ignored in: <function PhotoImage.__del__ at 0x00000202303E2E60>\n",
      "Traceback (most recent call last):\n",
      "  File \"d:\\Anaconda_39\\envs\\DL\\lib\\site-packages\\PIL\\ImageTk.py\", line 118, in __del__\n",
      "    name = self.__photo.name\n",
      "AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'\n",
      "Exception ignored in: <function PhotoImage.__del__ at 0x00000202303E2E60>\n",
      "Traceback (most recent call last):\n",
      "  File \"d:\\Anaconda_39\\envs\\DL\\lib\\site-packages\\PIL\\ImageTk.py\", line 118, in __del__\n",
      "    name = self.__photo.name\n",
      "AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'\n",
      "Exception ignored in: <function PhotoImage.__del__ at 0x00000202303E2E60>\n",
      "Traceback (most recent call last):\n",
      "  File \"d:\\Anaconda_39\\envs\\DL\\lib\\site-packages\\PIL\\ImageTk.py\", line 118, in __del__\n",
      "Exception ignored in: <function PhotoImage.__del__ at 0x00000202303E2E60>\n",
      "Traceback (most recent call last):\n",
      "  File \"d:\\Anaconda_39\\envs\\DL\\lib\\site-packages\\PIL\\ImageTk.py\", line 118, in __del__\n",
      "Exception ignored in: <function PhotoImage.__del__ at 0x00000202303E2E60>\n",
      "Traceback (most recent call last):\n",
      "  File \"d:\\Anaconda_39\\envs\\DL\\lib\\site-packages\\PIL\\ImageTk.py\", line 118, in __del__\n",
      "Exception ignored in: <function PhotoImage.__del__ at 0x00000202303E2E60>\n",
      "Traceback (most recent call last):\n",
      "  File \"d:\\Anaconda_39\\envs\\DL\\lib\\site-packages\\PIL\\ImageTk.py\", line 118, in __del__\n",
      "    name = self.__photo.name\n",
      "AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'\n",
      "    name = self.__photo.name\n",
      "AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'\n",
      "Exception ignored in: <function PhotoImage.__del__ at 0x00000202303E2E60>\n",
      "Traceback (most recent call last):\n",
      "  File \"d:\\Anaconda_39\\envs\\DL\\lib\\site-packages\\PIL\\ImageTk.py\", line 118, in __del__\n",
      "    name = self.__photo.name\n",
      "AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'\n",
      "    name = self.__photo.name\n",
      "AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'\n",
      "Exception ignored in: <function PhotoImage.__del__ at 0x00000202303E2E60>\n",
      "Traceback (most recent call last):\n",
      "  File \"d:\\Anaconda_39\\envs\\DL\\lib\\site-packages\\PIL\\ImageTk.py\", line 118, in __del__\n",
      "Exception ignored in: <function PhotoImage.__del__ at 0x00000202303E2E60>\n",
      "Traceback (most recent call last):\n",
      "  File \"d:\\Anaconda_39\\envs\\DL\\lib\\site-packages\\PIL\\ImageTk.py\", line 118, in __del__\n",
      "Exception ignored in: <function PhotoImage.__del__ at 0x00000202303E2E60>\n",
      "Traceback (most recent call last):\n",
      "  File \"d:\\Anaconda_39\\envs\\DL\\lib\\site-packages\\PIL\\ImageTk.py\", line 118, in __del__\n",
      "    name = self.__photo.name\n",
      "AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'\n",
      "    name = self.__photo.name\n",
      "AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'\n",
      "Exception ignored in: <function PhotoImage.__del__ at 0x00000202303E2E60>\n",
      "Traceback (most recent call last):\n",
      "  File \"d:\\Anaconda_39\\envs\\DL\\lib\\site-packages\\PIL\\ImageTk.py\", line 118, in __del__\n",
      "Exception ignored in: <function PhotoImage.__del__ at 0x00000202303E2E60>\n",
      "Traceback (most recent call last):\n",
      "  File \"d:\\Anaconda_39\\envs\\DL\\lib\\site-packages\\PIL\\ImageTk.py\", line 118, in __del__\n",
      "Exception ignored in: <function PhotoImage.__del__ at 0x00000202303E2E60>\n",
      "Traceback (most recent call last):\n",
      "  File \"d:\\Anaconda_39\\envs\\DL\\lib\\site-packages\\PIL\\ImageTk.py\", line 118, in __del__\n",
      "Exception ignored in: <function PhotoImage.__del__ at 0x00000202303E2E60>\n",
      "Traceback (most recent call last):\n",
      "  File \"d:\\Anaconda_39\\envs\\DL\\lib\\site-packages\\PIL\\ImageTk.py\", line 118, in __del__\n",
      "Exception ignored in: <function PhotoImage.__del__ at 0x00000202303E2E60>\n",
      "Traceback (most recent call last):\n",
      "  File \"d:\\Anaconda_39\\envs\\DL\\lib\\site-packages\\PIL\\ImageTk.py\", line 118, in __del__\n",
      "    name = self.__photo.name\n",
      "AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'\n",
      "    name = self.__photo.name\n",
      "AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'\n",
      "    name = self.__photo.name\n",
      "AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'\n",
      "    name = self.__photo.name\n",
      "AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'\n",
      "    name = self.__photo.name\n",
      "AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'\n",
      "        name = self.__photo.name\n",
      "AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'\n",
      "name = self.__photo.name\n",
      "AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'\n",
      "Exception in Tkinter callback\n",
      "Traceback (most recent call last):\n",
      "  File \"d:\\Anaconda_39\\envs\\DL\\lib\\tkinter\\__init__.py\", line 1921, in __call__\n",
      "    return self.func(*args)\n",
      "  File \"d:\\Anaconda_39\\envs\\DL\\lib\\tkinter\\__init__.py\", line 3977, in __call__\n",
      "    self.__callback(self.__value, *args)\n",
      "  File \"C:\\Users\\DanielBaron\\AppData\\Local\\Temp\\ipykernel_7388\\2333319793.py\", line 107, in change_department\n",
      "    self.update_labels()\n",
      "  File \"C:\\Users\\DanielBaron\\AppData\\Local\\Temp\\ipykernel_7388\\2333319793.py\", line 33, in update_labels\n",
      "    metric, dept_pred, support_real, tasa_pib, tasa_desempleo = load_model(self.variable_sent, self.variable_model, self.variable_dept)\n",
      "  File \"C:\\Users\\DanielBaron\\AppData\\Local\\Temp\\ipykernel_7388\\3275372269.py\", line 106, in load_model\n",
      "    dept_pred = df_variables[df_variables['ubicacion'] == dept]['prediccion'].values[0]\n",
      "IndexError: index 0 is out of bounds for axis 0 with size 0\n"
     ]
    }
   ],
   "source": [
    "from tkinter import *\n",
    "import tkinter as tk\n",
    "import tkintermapview\n",
    "\n",
    "class Apliccation():\n",
    "    def __init__(self):\n",
    "        self.GUI = Tk()\n",
    "        self.width= self.GUI.winfo_screenwidth()               \n",
    "        self.height= self.GUI.winfo_screenheight()               \n",
    "        self.GUI.geometry(\"%dx%d\" % (self.width, self.height))\n",
    "        self.GUI.title('Predicción de elecciones presidenciales Colombia 2022')\n",
    "        self.polygon_1 = None\n",
    "        self.map_widget = tkintermapview.TkinterMapView(self.GUI, width=self.width*0.95, height=self.height*0.5, corner_radius=0)\n",
    "        self.map_widget.set_position(4.570868, -74.297333)  \n",
    "        self.map_widget.set_zoom(6)\n",
    "        self.map_widget.place(relx=0.5, rely=0.6, anchor=tk.CENTER)\n",
    "        self.data_geo = preprocess_inputs('variables_procesadas_robertuito-sentiment-analysis.csv')\n",
    "        self.departamentos = list(self.data_geo['NAME_1'].drop_duplicates())\n",
    "        self.variable_sent = StringVar(self.GUI)\n",
    "        self.variable_dept = StringVar(self.GUI)\n",
    "        self.variable_model = StringVar(self.GUI)\n",
    "        self.variable_dept.set(\"Boyacá\")\n",
    "        self.variable_sent.set(\"Robertuito\")\n",
    "        self.variable_model.set('MLP Regression')\n",
    "        self.models = ['']\n",
    "        self.metric = ''\n",
    "        self.dept_pred = 0\n",
    "        self.support_real = 0\n",
    "        self.tasa_pib = 0\n",
    "        self.tasa_desempleo = 0\n",
    "\n",
    "    def update_labels(self):\n",
    "        metric, dept_pred, support_real, tasa_pib, tasa_desempleo = load_model(self.variable_sent, self.variable_model, self.variable_dept)\n",
    "        self.metric = metric\n",
    "        self.dept_pred = dept_pred\n",
    "        self.support_real = support_real\n",
    "        self.tasa_pib = tasa_pib\n",
    "        self.tasa_desempleo = tasa_desempleo\n",
    "\n",
    "        label_sr = Label(self.GUI, text=\"Support Rate Real: \")\n",
    "        label_sr.grid(row=3, column=0, sticky='ew')\n",
    "        label_sr.config(fg=\"black\", bg=\"lightgray\", font=(\"Verdana\",21))\n",
    "\n",
    "        label_sr_v = Label(self.GUI, text=\"{}%\".format(np.round(self.support_real*100, decimals=4)))\n",
    "        label_sr_v.grid(row=3, column=1, sticky='ew')\n",
    "        label_sr_v.config(fg=\"black\", bg=\"lightgray\", font=(\"Verdana\",21))\n",
    "\n",
    "        label_sp = Label(self.GUI, text=\"Support Rate Predicho: \")\n",
    "        label_sp.grid(row=4, column=0, sticky='ew')\n",
    "        label_sp.config(fg=\"black\", bg=\"lightgray\", font=(\"Verdana\",21))\n",
    "\n",
    "        label_sp_v = Label(self.GUI, text=\"{}%\".format(self.dept_pred*100))\n",
    "        label_sp_v.grid(row=4, column=1, sticky='ew')\n",
    "        label_sp_v.config(fg=\"black\", bg=\"lightgray\", font=(\"Verdana\",21))\n",
    "\n",
    "        label_pib = Label(self.GUI, text=\"Tasa Incremento PIB: \")\n",
    "        label_pib.grid(row=5, column=0, sticky='ew')\n",
    "        label_pib.config(fg=\"black\", bg=\"lightgray\", font=(\"Verdana\",21))\n",
    "\n",
    "        label_pib_v = Label(self.GUI, text=\"{}%\".format(self.tasa_pib*100))\n",
    "        label_pib_v.grid(row=5, column=1, sticky='ew')\n",
    "        label_pib_v.config(fg=\"black\", bg=\"lightgray\", font=(\"Verdana\",21))\n",
    "\n",
    "        label_des = Label(self.GUI, text=\"Tasa Incremento Desempleo: \")\n",
    "        label_des.grid(row=6, column=0, sticky='ew')\n",
    "        label_des.config(fg=\"black\", bg=\"lightgray\", font=(\"Verdana\",21))\n",
    "\n",
    "        label_des_v = Label(self.GUI, text=\"{}%\".format(self.tasa_desempleo*100))\n",
    "        label_des_v.grid(row=6, column=1, sticky='ew')\n",
    "        label_des_v.config(fg=\"black\", bg=\"lightgray\", font=(\"Verdana\",21)) \n",
    "\n",
    "        label_mt = Label(self.GUI, text=\"Métricas: \")\n",
    "        label_mt.grid(row=7, column=0, sticky='ew')\n",
    "        label_mt.config(fg=\"black\", bg=\"lightgray\", font=(\"Verdana\",21))\n",
    "\n",
    "        label_mt_v = Label(self.GUI, text=self.metric)\n",
    "        label_mt_v.grid(row=7, column=1, sticky='ew')\n",
    "        label_mt_v.config(fg=\"black\", bg=\"lightgray\", font=(\"Verdana\",21))\n",
    "\n",
    "        \n",
    "    def change_department(self, choice):\n",
    "\n",
    "        if self.polygon_1 != None:\n",
    "            self.map_widget.set_position(4.570868, -74.297333) \n",
    "            self.polygon_1.delete()\n",
    "\n",
    "        self.map_widget.set_position(4.570868, -74.297333) \n",
    "        choice = self.variable_dept.get()\n",
    "        values = self.data_geo[self.data_geo['NAME_1']==choice]['geometry'].values[0].__geo_interface__\n",
    "        \n",
    "        if values['type'] == 'Polygon':\n",
    "            coordinates = [(item[1], item[0]) for sublist in values['coordinates'] for item in sublist]\n",
    "            lat, lon = np.mean([x[0] for x in coordinates]), np.mean([x[1] for x in coordinates])\n",
    "            self.map_widget.set_position(lat, lon)\n",
    "            self.map_widget.set_zoom(7)\n",
    "            self.polygon_1 = self.map_widget.set_polygon(coordinates, fill_color=\"blue\", outline_color=\"blue\", border_width=5)\n",
    "        elif values['type'] == 'MultiPolygon':\n",
    "            coord = []\n",
    "            for coordinate in values['coordinates']:\n",
    "                coord.append([(x[1], x[0]) for x in coordinate[0]])\n",
    "            coordinate_f = max(coord, key=len)\n",
    "            lat, lon = np.mean([x[0] for x in coordinate_f]), np.mean([x[1] for x in coordinate_f])\n",
    "            self.map_widget.set_position(lat, lon)\n",
    "            self.map_widget.set_zoom(7)\n",
    "            self.polygon_1 = self.map_widget.set_polygon(coordinate_f, fill_color=\"blue\", outline_color=\"blue\", border_width=5)\n",
    "\n",
    "        self.update_labels()\n",
    "\n",
    "    def change_sentiment_model(self, choice):\n",
    "        \n",
    "        choice = self.variable_sent.get()\n",
    "        if choice == 'Robertuito':\n",
    "            name = 'variables_procesadas_robertuito-sentiment-analysis.csv'\n",
    "        elif choice == 'Beto':\n",
    "            name = 'variables_procesadas_bert_BetoSentimentAnalysis.csv'\n",
    "        elif choice == 'Codeswitch':\n",
    "            name = 'variables_procesadas_codeswitch-spaeng-sentiment-analysis-lince.csv'\n",
    "        \n",
    "        self.data_geo = preprocess_inputs(name)\n",
    "        self.departamentos = list(self.data_geo['NAME_1'].drop_duplicates())\n",
    "        self.update_labels()\n",
    "\n",
    "    def change_prediction_model(self):\n",
    "        \n",
    "        choice = self.variable_sent.get()\n",
    "        if choice == 'Robertuito':\n",
    "            reg_models = pd.read_csv('resultados/regresion_variables_procesadas_robertuito-sentiment-analysis.csv', index_col=[0])\n",
    "            class_models = pd.read_csv('resultados/clasificacion_variables_procesadas_robertuito-sentiment-analysis.csv', index_col=[0])\n",
    "        elif choice == 'Beto':\n",
    "            reg_models = pd.read_csv('resultados/regresion_variables_procesadas_bert_BetoSentimentAnalysis.csv', index_col=[0])\n",
    "            class_models = pd.read_csv('resultados/clasificacion_variables_procesadas_bert_BetoSentimentAnalysis.csv', index_col=[0])\n",
    "        elif choice == 'Codeswitch':\n",
    "            reg_models = pd.read_csv('resultados/regresion_variables_procesadas_codeswitch-spaeng-sentiment-analysis-lince.csv', index_col=[0])\n",
    "            class_models = pd.read_csv('resultados/clasificacion_variables_procesadas_codeswitch-spaeng-sentiment-analysis-lince.csv', index_col=[0])\n",
    "\n",
    "        both_models = [x[0] for x in pd.concat([reg_models[['Model']], class_models[['Model']]]).values]\n",
    "\n",
    "        self.update_labels()\n",
    "\n",
    "        return both_models\n",
    "        \n",
    "\n",
    "    def main(self):\n",
    "        # setting variable for Integers\n",
    "        \n",
    "        self.variable_sent.set(\"Robertuito\")\n",
    "        sentiments = ['Robertuito', 'Beto', 'Codeswitch']\n",
    "\n",
    "        # creating widget\n",
    "        dropdown_sent = OptionMenu(\n",
    "            self.GUI,\n",
    "            self.variable_sent,\n",
    "            *sentiments,\n",
    "            command=self.change_sentiment_model\n",
    "        )\n",
    "\n",
    "        label_m = Label(self.GUI, text=\"Modelo Análisis de Sentimientos: \")\n",
    "        label_m.grid(row=0, column=0, sticky='ew')\n",
    "        label_m.config(fg=\"black\", bg=\"lightgray\", font=(\"Verdana\",18))\n",
    "        self.GUI.rowconfigure(0, {'minsize': 50})\n",
    "        \n",
    "        dropdown_sent.grid(row=0, column=1, sticky='ew')\n",
    "        dropdown_sent.config(fg=\"black\", bg=\"lightgray\", font=(\"Verdana\",18)) \n",
    "\n",
    "        label_p = Label(self.GUI, text=\"Modelo de Predicción: \")\n",
    "        label_p.grid(row=1, column=0, sticky='ew')\n",
    "        label_p.config(fg=\"black\", bg=\"lightgray\", font=(\"Verdana\",18))\n",
    "\n",
    "        self.variable_model.set(\"Random Forest Classifier\")\n",
    "\n",
    "        self.models = self.change_prediction_model()\n",
    "\n",
    "        # creating widget\n",
    "        dropdown_model = OptionMenu(\n",
    "            self.GUI,\n",
    "            self.variable_model,\n",
    "            *self.models\n",
    "            )\n",
    "        dropdown_model.grid(row=1, column=1, sticky='ew')\n",
    "        dropdown_model.config(fg=\"black\", bg=\"lightgray\", font=(\"Verdana\",18)) \n",
    "\n",
    "        label_d = Label(self.GUI, text=\"Departamento: \")\n",
    "        label_d.grid(row=2, column=0, sticky='ew')\n",
    "        label_d.config(fg=\"black\", bg=\"lightgray\", font=(\"Verdana\",18))\n",
    "\n",
    "        self.variable_dept.set(\"Boyacá\") # default value\n",
    "\n",
    "        departamentos = self.departamentos\n",
    "\n",
    "        # creating widget\n",
    "        dropdown_dept = OptionMenu(\n",
    "            self.GUI,\n",
    "            self.variable_dept,\n",
    "            *departamentos,\n",
    "            command=self.change_department\n",
    "        )\n",
    "\n",
    "        dropdown_dept.grid(row=2, column=1, sticky='ew')\n",
    "        dropdown_dept.config(fg=\"black\", bg=\"lightgray\", font=(\"Verdana\",18)) \n",
    "\n",
    "        self.GUI.mainloop()\n",
    "\n",
    "app = Apliccation()\n",
    "app.main()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.10.4 ('DL')",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.4"
  },
  "orig_nbformat": 4,
  "vscode": {
   "interpreter": {
    "hash": "7b12e629898a100bac456066adb1052da5bab249d92357a99acd404c7e8e3e0e"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}