Commit 9eacaaec authored by Chamodi Yapa's avatar Chamodi Yapa

Updated ML Model

parent f5166c3b
{"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"provenance":[],"collapsed_sections":["jUmxIhRVrcCH","d_F1Z7g5-wyO"],"mount_file_id":"1XjE2t5aszB_bV4eenZaLLIvwA4TNp6r-","authorship_tag":"ABX9TyOSQ5+fE7ffPrdAkLrWOEI4"},"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"}},"cells":[{"cell_type":"markdown","source":["##Main function"],"metadata":{"id":"z1OYLkChBIYU"}},{"cell_type":"code","execution_count":null,"metadata":{"id":"f6nsrxyzM_fg"},"outputs":[],"source":["!pip install scikit-learn==1.3.2\n","!pip install --upgrade joblib\n","!pip install pmdarima"]},{"cell_type":"markdown","source":["##import data in firebase"],"metadata":{"id":"jUmxIhRVrcCH"}},{"cell_type":"code","source":["#%%writefile firebase_data.py\n","\n","import firebase_admin\n","from firebase_admin import credentials, firestore\n","import pandas as pd\n","\n","# Initialize the Firebase Admin SDK with your service account key\n","service_account_info = {\n"," \"type\": \"service_account\",\n"," \"project_id\": \"learnjoy-1e23a\",\n"," \"private_key_id\": \"a7bbb4784a85a5fa4bd877e649abf0b628561d83\",\n"," \"private_key\": \"-----BEGIN PRIVATE KEY-----\\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDsDyg2Zx+YSPXK\\nYCQvQUiY3EgYBWvE+jTb1qWSjLipo84o4h0MoDjWHtU4W0WOOSwUAFAv764qjbkl\\nk7VIxG7YLQIHJysBavqhJH8+LdVAUc4SjurxM1XoXIW/lvUJBF8g1QTBaNZNlV05\\neW6bc9Fj3CuXJrmiGu2b2y4/Q8bijLp2uQii8UJLkEoLmKl40+fLGKw8VkLl2YMJ\\nb48yUEtdKeefYAVngK2W/ZI0ax19a+UiwJMBZsmGiq8pEwYEuWNHg+B7jASiATC0\\nvSD7lNRQHvv5tNSslX8gmrbm9QUutJcvQWXf1swaxylvVLPP6kxp3qJADNE4oom2\\n8RJGVTulAgMBAAECggEACiuuWDG3QHDG+PI4J4+7g1fdBKlEdxcvVy13XXS8sWpt\\nA9aXg9IUwNJRQ31YkNkmbLIwF5tPDhGkdtmssjbsbln6FWQloTOtGsD0zoaxAnVu\\ngzQvK+HsrfdBN/usEQ25f4j4tyXqMyuKpGL2q1yhGplY3h6oBDOpeyaau9USvkis\\nFwFnrPOj4SGXxvX8uhwi1cZIRnF1DWxZD2l0EiC3yIg83VaCUJDFpQzBL9ejcqZw\\nUYXyQYploW9Kuz076frors+eGtFGTFnJhJLdWSndMGmeyt27VFijGgTpJyujBTv/\\nxesFYawHJ6fswa8G+Z9Me8SlucHGBOOs9ZOdqDXWAQKBgQD58BjQCU9pHNJ1+8sC\\n/u0KsPcjFvep2C59ShmoFcLxBmWN0KU0wnaVXy6z4oemkgxzuo7CiDvqT4BfIHuv\\n0qj41/otWiDgvR2ZIrvPBaZ/7bSUQhMMQMkBtCJq9R8rR0ujqohErQyCi2VVsdBM\\nRkStFUzY3KPi1ja7HUJ228A2JQKBgQDxyOKlHuhHLTfHBEAIr1B1wVTvzPAJH26J\\ngF6QBeffQeHuYYnb0dGXy8NNemZx959c3D+dcl55NHqB2YKm3ZU8fs1m39XW1b2d\\n0tL/sn0958RS0iYC3GeDE3A+CSeUvYWwxLBeZJ4HliyxHNKljV6YEkDXSI8PU07m\\nRUDqL/g3gQKBgQC4gaIPkY/pzLkhF+vaHk7m4ZTPdpkF7O0E2Lrv9oCeZVZ6xlfv\\nBs97nXRgnw38zTwcAtB4kxGH+4CMuPIV7bGHYgjxieNThMhgz99NCKLNNbFk8RIW\\nrYy1kUEHLEUCMfOIss89w3HEvRrllAptBEKWc27zeI4TWoe0wfjavYa7cQKBgQCh\\nmCpqQ1ro3z7NI3kMlOdInFsBHk47Oqes/H+28EuFeknfAY+avAPB2SyBptG7T81R\\nyd42g47CoSFTkaTxk1y/ntv26pjHyfi9936P6KIt8q3S0KMY/GeuQhqdS48JqRUm\\nDH73x3WbCnJ6ORJMFUzohCKT/+mlS3+LBTQakM7rgQKBgBhr4LDP3JESsJyQsRnT\\nfMwLc7cqpG/zras/YJdvm2xNc+Dat3hb20oGPSkoSofOKSJY2WJ9NFTLIuWC6cp5\\nbp62Nh41HfQXN4th/JDe03GDVBSbP49N6RzKPmN7NYLsZBXb70IGIjzB2QHOAIMd\\n5uvE3IKYz4F35ROcpbbN0Gge\\n-----END PRIVATE KEY-----\\n\",\n"," \"client_email\": \"firebase-adminsdk-a29bq@learnjoy-1e23a.iam.gserviceaccount.com\",\n"," \"client_id\": \"111350571579855703236\",\n"," \"auth_uri\": \"https://accounts.google.com/o/oauth2/auth\",\n"," \"token_uri\": \"https://oauth2.googleapis.com/token\",\n"," \"auth_provider_x509_cert_url\": \"https://www.googleapis.com/oauth2/v1/certs\",\n"," \"client_x509_cert_url\": \"https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-a29bq%40learnjoy-1e23a.iam.gserviceaccount.com\",\n"," \"universe_domain\": \"googleapis.com\"\n"," }\n","\n","\n","#cred = credentials.Certificate(r\"/content/learnjoy-1e23a-firebase-adminsdk-a29bq-a7bbb4784a.json\")\n","cred = credentials.Certificate(service_account_info)\n","\n","def fire_base_player_game(player_name:str):\n"," # Specify the desired app name\n"," app_name = 'myapp'\n","\n"," try:\n"," # Try to initialize a new app\n"," app = firebase_admin.initialize_app(cred, name=app_name)\n"," except ValueError as e:\n"," # If the app already exists, get the existing app\n"," if str(e).startswith('Firebase app named \"{0}\" already exists'.format(app_name)):\n"," app = firebase_admin.get_app(app_name)\n"," else:\n"," # If the error is for some other reason, re-raise the exception\n"," raise e\n","\n"," # Now you can communicate with Firestore using the unique app name\n"," db = firestore.client(app=app)\n","\n"," # Reference to the collection\n"," collection_ref = db.collection(\"GameStatistics\")\n","\n"," # Fetch documents from the collection\n"," documents = collection_ref.get()\n","\n"," # Extract data from documents\n"," data = [doc.to_dict() for doc in documents]\n","\n"," # Create a DataFrame\n"," df = pd.DataFrame(data)\n","\n"," # Display the DataFrame\n"," df=df.reindex(columns=[\"id\",\"date\",\"playerName\",\"gameName\",\"gameLevel\",\"successCount\",\"attemptCount\",\"gameScoreXP\",\"engagementTime\"])\n"," df.rename(columns={\"date\":\"date\",'playerName': 'player_name', 'gameName': 'game_name',\"gameLevel\":\"game_level\",\"successCount\":\"success_count\",\"attemptCount\":\"attempt_count\",\"gameScoreXP\":\"game_score_xp\",\"engagementTime\":\"engagement_time_mins\"}, inplace=True)\n"," df['date'] = pd.to_datetime(df['date'], format=\"%d/%m/%Y\")\n"," df = df.sort_values(by='date')#, ascending=True\n"," # Filter DataFrame based on multiple conditions using AND (&) or OR (|)\n"," filtered_df= df[(df['player_name'] == player_name)]\n"," return filtered_df"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"C_mI1CQ5rgO6","executionInfo":{"status":"ok","timestamp":1705756184213,"user_tz":-330,"elapsed":18,"user":{"displayName":"Kaushi Gihan","userId":"11214181140146971518"}},"outputId":"8abed6af-e0f0-4052-fafe-3fef6ecd7ea1"},"execution_count":64,"outputs":[{"output_type":"stream","name":"stdout","text":["Writing firebase_data.py\n"]}]},{"cell_type":"code","source":["df=fire_base_player_game(\"rQIRSQe3ZYTRDGfvRb8dvzaCKkA2\")\n","df.tail(10)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":556},"id":"8SyZI70R91nB","executionInfo":{"status":"ok","timestamp":1705756022627,"user_tz":-330,"elapsed":421,"user":{"displayName":"Kaushi Gihan","userId":"11214181140146971518"}},"outputId":"1237ca3c-7d9d-46b2-c8d2-3821b30bdafd"},"execution_count":58,"outputs":[{"output_type":"execute_result","data":{"text/plain":[" id date player_name \\\n","26 aF4o3QNLLc9hMVtI7VlZ 2024-01-11 rQIRSQe3ZYTRDGfvRb8dvzaCKkA2 \n","24 ZARiHIYnw4d1ycEFr7ok 2024-01-11 rQIRSQe3ZYTRDGfvRb8dvzaCKkA2 \n","20 X83ZjYtFnAcwzzCu4uej 2024-01-11 rQIRSQe3ZYTRDGfvRb8dvzaCKkA2 \n","17 RR8144bnXatm3HBaJ1H8 2024-01-11 rQIRSQe3ZYTRDGfvRb8dvzaCKkA2 \n","10 HpeGJjoiWXMi2T2zay3S 2024-01-11 rQIRSQe3ZYTRDGfvRb8dvzaCKkA2 \n","4 5vHHhGwsMPZ047NoZAe3 2024-01-11 rQIRSQe3ZYTRDGfvRb8dvzaCKkA2 \n","3 3i0xvV1W284tw6Mwul1P 2024-01-11 rQIRSQe3ZYTRDGfvRb8dvzaCKkA2 \n","34 oNOFi18RJGlZXujo5tg0 2024-01-11 rQIRSQe3ZYTRDGfvRb8dvzaCKkA2 \n","23 Z8kMMTAJpGkqrJzvNvVz 2024-01-11 rQIRSQe3ZYTRDGfvRb8dvzaCKkA2 \n","40 sRQmlY6Vo8VlU0aCCowG 2024-01-16 rQIRSQe3ZYTRDGfvRb8dvzaCKkA2 \n","\n"," game_name game_level success_count attempt_count game_score_xp \\\n","26 MoneyMaster 6 10 10 94.0 \n","24 MoneyMaster 5 10 10 95.0 \n","20 CountingPractice 1 10 10 97.0 \n","17 MoneyMaster 8 10 10 94.0 \n","10 MoneyMaster 2 10 10 93.0 \n","4 MoneyMaster 9 10 10 94.0 \n","3 CountingPractice 1 10 10 97.0 \n","34 ClockChallenge 1 10 10 78.0 \n","23 MoneyMaster 1 10 10 88.0 \n","40 Dysgraphia 2 10 10 95.0 \n","\n"," engagement_time_mins \n","26 18.0 \n","24 17.0 \n","20 11.0 \n","17 18.0 \n","10 22.0 \n","4 19.0 \n","3 9.0 \n","34 68.0 \n","23 36.0 \n","40 15.0 "],"text/html":["\n"," <div id=\"df-f5e52bbe-bf15-4d3f-9e59-81f6eb1d332f\" class=\"colab-df-container\">\n"," <div>\n","<style scoped>\n"," .dataframe tbody tr th:only-of-type {\n"," vertical-align: middle;\n"," }\n","\n"," .dataframe tbody tr th {\n"," vertical-align: top;\n"," }\n","\n"," .dataframe thead th {\n"," text-align: right;\n"," }\n","</style>\n","<table border=\"1\" class=\"dataframe\">\n"," <thead>\n"," <tr style=\"text-align: right;\">\n"," <th></th>\n"," <th>id</th>\n"," <th>date</th>\n"," <th>player_name</th>\n"," <th>game_name</th>\n"," <th>game_level</th>\n"," <th>success_count</th>\n"," <th>attempt_count</th>\n"," <th>game_score_xp</th>\n"," <th>engagement_time_mins</th>\n"," </tr>\n"," </thead>\n"," <tbody>\n"," <tr>\n"," <th>26</th>\n"," <td>aF4o3QNLLc9hMVtI7VlZ</td>\n"," <td>2024-01-11</td>\n"," <td>rQIRSQe3ZYTRDGfvRb8dvzaCKkA2</td>\n"," <td>MoneyMaster</td>\n"," <td>6</td>\n"," <td>10</td>\n"," <td>10</td>\n"," <td>94.0</td>\n"," <td>18.0</td>\n"," </tr>\n"," <tr>\n"," <th>24</th>\n"," <td>ZARiHIYnw4d1ycEFr7ok</td>\n"," <td>2024-01-11</td>\n"," <td>rQIRSQe3ZYTRDGfvRb8dvzaCKkA2</td>\n"," <td>MoneyMaster</td>\n"," <td>5</td>\n"," <td>10</td>\n"," <td>10</td>\n"," <td>95.0</td>\n"," <td>17.0</td>\n"," </tr>\n"," <tr>\n"," <th>20</th>\n"," <td>X83ZjYtFnAcwzzCu4uej</td>\n"," <td>2024-01-11</td>\n"," <td>rQIRSQe3ZYTRDGfvRb8dvzaCKkA2</td>\n"," <td>CountingPractice</td>\n"," <td>1</td>\n"," <td>10</td>\n"," <td>10</td>\n"," <td>97.0</td>\n"," <td>11.0</td>\n"," </tr>\n"," <tr>\n"," <th>17</th>\n"," <td>RR8144bnXatm3HBaJ1H8</td>\n"," <td>2024-01-11</td>\n"," <td>rQIRSQe3ZYTRDGfvRb8dvzaCKkA2</td>\n"," <td>MoneyMaster</td>\n"," <td>8</td>\n"," <td>10</td>\n"," <td>10</td>\n"," <td>94.0</td>\n"," <td>18.0</td>\n"," </tr>\n"," <tr>\n"," <th>10</th>\n"," <td>HpeGJjoiWXMi2T2zay3S</td>\n"," <td>2024-01-11</td>\n"," <td>rQIRSQe3ZYTRDGfvRb8dvzaCKkA2</td>\n"," <td>MoneyMaster</td>\n"," <td>2</td>\n"," <td>10</td>\n"," <td>10</td>\n"," <td>93.0</td>\n"," <td>22.0</td>\n"," </tr>\n"," <tr>\n"," <th>4</th>\n"," <td>5vHHhGwsMPZ047NoZAe3</td>\n"," <td>2024-01-11</td>\n"," <td>rQIRSQe3ZYTRDGfvRb8dvzaCKkA2</td>\n"," <td>MoneyMaster</td>\n"," <td>9</td>\n"," <td>10</td>\n"," <td>10</td>\n"," <td>94.0</td>\n"," <td>19.0</td>\n"," </tr>\n"," <tr>\n"," <th>3</th>\n"," <td>3i0xvV1W284tw6Mwul1P</td>\n"," <td>2024-01-11</td>\n"," <td>rQIRSQe3ZYTRDGfvRb8dvzaCKkA2</td>\n"," <td>CountingPractice</td>\n"," <td>1</td>\n"," <td>10</td>\n"," <td>10</td>\n"," <td>97.0</td>\n"," <td>9.0</td>\n"," </tr>\n"," <tr>\n"," <th>34</th>\n"," <td>oNOFi18RJGlZXujo5tg0</td>\n"," <td>2024-01-11</td>\n"," <td>rQIRSQe3ZYTRDGfvRb8dvzaCKkA2</td>\n"," <td>ClockChallenge</td>\n"," <td>1</td>\n"," <td>10</td>\n"," <td>10</td>\n"," <td>78.0</td>\n"," <td>68.0</td>\n"," </tr>\n"," <tr>\n"," <th>23</th>\n"," <td>Z8kMMTAJpGkqrJzvNvVz</td>\n"," <td>2024-01-11</td>\n"," <td>rQIRSQe3ZYTRDGfvRb8dvzaCKkA2</td>\n"," <td>MoneyMaster</td>\n"," <td>1</td>\n"," <td>10</td>\n"," <td>10</td>\n"," <td>88.0</td>\n"," <td>36.0</td>\n"," </tr>\n"," <tr>\n"," <th>40</th>\n"," <td>sRQmlY6Vo8VlU0aCCowG</td>\n"," <td>2024-01-16</td>\n"," <td>rQIRSQe3ZYTRDGfvRb8dvzaCKkA2</td>\n"," <td>Dysgraphia</td>\n"," <td>2</td>\n"," <td>10</td>\n"," <td>10</td>\n"," <td>95.0</td>\n"," <td>15.0</td>\n"," </tr>\n"," </tbody>\n","</table>\n","</div>\n"," <div class=\"colab-df-buttons\">\n","\n"," <div class=\"colab-df-container\">\n"," <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-f5e52bbe-bf15-4d3f-9e59-81f6eb1d332f')\"\n"," title=\"Convert this dataframe to an interactive table.\"\n"," style=\"display:none;\">\n","\n"," <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n"," <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n"," </svg>\n"," </button>\n","\n"," <style>\n"," .colab-df-container {\n"," display:flex;\n"," gap: 12px;\n"," }\n","\n"," .colab-df-convert {\n"," background-color: #E8F0FE;\n"," border: none;\n"," border-radius: 50%;\n"," cursor: pointer;\n"," display: none;\n"," fill: #1967D2;\n"," height: 32px;\n"," padding: 0 0 0 0;\n"," width: 32px;\n"," }\n","\n"," .colab-df-convert:hover {\n"," background-color: #E2EBFA;\n"," box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n"," fill: #174EA6;\n"," }\n","\n"," .colab-df-buttons div {\n"," margin-bottom: 4px;\n"," }\n","\n"," [theme=dark] .colab-df-convert {\n"," background-color: #3B4455;\n"," fill: #D2E3FC;\n"," }\n","\n"," [theme=dark] .colab-df-convert:hover {\n"," background-color: #434B5C;\n"," box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n"," filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n"," fill: #FFFFFF;\n"," }\n"," </style>\n","\n"," <script>\n"," const buttonEl =\n"," document.querySelector('#df-f5e52bbe-bf15-4d3f-9e59-81f6eb1d332f button.colab-df-convert');\n"," buttonEl.style.display =\n"," google.colab.kernel.accessAllowed ? 'block' : 'none';\n","\n"," async function convertToInteractive(key) {\n"," const element = document.querySelector('#df-f5e52bbe-bf15-4d3f-9e59-81f6eb1d332f');\n"," const dataTable =\n"," await google.colab.kernel.invokeFunction('convertToInteractive',\n"," [key], {});\n"," if (!dataTable) return;\n","\n"," const docLinkHtml = 'Like what you see? Visit the ' +\n"," '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n"," + ' to learn more about interactive tables.';\n"," element.innerHTML = '';\n"," dataTable['output_type'] = 'display_data';\n"," await google.colab.output.renderOutput(dataTable, element);\n"," const docLink = document.createElement('div');\n"," docLink.innerHTML = docLinkHtml;\n"," element.appendChild(docLink);\n"," }\n"," </script>\n"," </div>\n","\n","\n","<div id=\"df-72b9b6e4-7337-4a0c-90d6-a891c652afbc\">\n"," <button class=\"colab-df-quickchart\" onclick=\"quickchart('df-72b9b6e4-7337-4a0c-90d6-a891c652afbc')\"\n"," title=\"Suggest charts\"\n"," style=\"display:none;\">\n","\n","<svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\"viewBox=\"0 0 24 24\"\n"," width=\"24px\">\n"," <g>\n"," <path d=\"M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z\"/>\n"," </g>\n","</svg>\n"," </button>\n","\n","<style>\n"," .colab-df-quickchart {\n"," --bg-color: #E8F0FE;\n"," --fill-color: #1967D2;\n"," --hover-bg-color: #E2EBFA;\n"," --hover-fill-color: #174EA6;\n"," --disabled-fill-color: #AAA;\n"," --disabled-bg-color: #DDD;\n"," }\n","\n"," [theme=dark] .colab-df-quickchart {\n"," --bg-color: #3B4455;\n"," --fill-color: #D2E3FC;\n"," --hover-bg-color: #434B5C;\n"," --hover-fill-color: #FFFFFF;\n"," --disabled-bg-color: #3B4455;\n"," --disabled-fill-color: #666;\n"," }\n","\n"," .colab-df-quickchart {\n"," background-color: var(--bg-color);\n"," border: none;\n"," border-radius: 50%;\n"," cursor: pointer;\n"," display: none;\n"," fill: var(--fill-color);\n"," height: 32px;\n"," padding: 0;\n"," width: 32px;\n"," }\n","\n"," .colab-df-quickchart:hover {\n"," background-color: var(--hover-bg-color);\n"," box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);\n"," fill: var(--button-hover-fill-color);\n"," }\n","\n"," .colab-df-quickchart-complete:disabled,\n"," .colab-df-quickchart-complete:disabled:hover {\n"," background-color: var(--disabled-bg-color);\n"," fill: var(--disabled-fill-color);\n"," box-shadow: none;\n"," }\n","\n"," .colab-df-spinner {\n"," border: 2px solid var(--fill-color);\n"," border-color: transparent;\n"," border-bottom-color: var(--fill-color);\n"," animation:\n"," spin 1s steps(1) infinite;\n"," }\n","\n"," @keyframes spin {\n"," 0% {\n"," border-color: transparent;\n"," border-bottom-color: var(--fill-color);\n"," border-left-color: var(--fill-color);\n"," }\n"," 20% {\n"," border-color: transparent;\n"," border-left-color: var(--fill-color);\n"," border-top-color: var(--fill-color);\n"," }\n"," 30% {\n"," border-color: transparent;\n"," border-left-color: var(--fill-color);\n"," border-top-color: var(--fill-color);\n"," border-right-color: var(--fill-color);\n"," }\n"," 40% {\n"," border-color: transparent;\n"," border-right-color: var(--fill-color);\n"," border-top-color: var(--fill-color);\n"," }\n"," 60% {\n"," border-color: transparent;\n"," border-right-color: var(--fill-color);\n"," }\n"," 80% {\n"," border-color: transparent;\n"," border-right-color: var(--fill-color);\n"," border-bottom-color: var(--fill-color);\n"," }\n"," 90% {\n"," border-color: transparent;\n"," border-bottom-color: var(--fill-color);\n"," }\n"," }\n","</style>\n","\n"," <script>\n"," async function quickchart(key) {\n"," const quickchartButtonEl =\n"," document.querySelector('#' + key + ' button');\n"," quickchartButtonEl.disabled = true; // To prevent multiple clicks.\n"," quickchartButtonEl.classList.add('colab-df-spinner');\n"," try {\n"," const charts = await google.colab.kernel.invokeFunction(\n"," 'suggestCharts', [key], {});\n"," } catch (error) {\n"," console.error('Error during call to suggestCharts:', error);\n"," }\n"," quickchartButtonEl.classList.remove('colab-df-spinner');\n"," quickchartButtonEl.classList.add('colab-df-quickchart-complete');\n"," }\n"," (() => {\n"," let quickchartButtonEl =\n"," document.querySelector('#df-72b9b6e4-7337-4a0c-90d6-a891c652afbc button');\n"," quickchartButtonEl.style.display =\n"," google.colab.kernel.accessAllowed ? 'block' : 'none';\n"," })();\n"," </script>\n","</div>\n","\n"," </div>\n"," </div>\n"]},"metadata":{},"execution_count":58}]},{"cell_type":"code","source":["#%%writefile self_improvement.py\n","import pandas as pd\n","import numpy as np\n","import os\n","import joblib\n","import math\n","import pmdarima as pm\n","\n","from pmdarima.model_selection import train_test_split\n","from pmdarima.arima.utils import ndiffs\n","from datetime import datetime\n","from sklearn.preprocessing import StandardScaler\n","from .firebase_data import fire_base_player_game\n","\n","\n","rf_model = joblib.load(\"/content/drive/MyDrive/Work_space/Silverline_IT/Project/Learn_Joy/API/app/service01/fun01_model/rf_model.pkl\")\n","scaler_X = joblib.load(\"/content/drive/MyDrive/Work_space/Silverline_IT/Project/Learn_Joy/API/app/service01/fun01_model/scaler_X.pkl\")\n","scaler_y = joblib.load(\"/content/drive/MyDrive/Work_space/Silverline_IT/Project/Learn_Joy/API/app/service01/fun01_model/scaler_y.pkl\")\n","\n","current_dir=os.path.dirname(os.path.abspath(__file__))\n","\n","rf_model = joblib.load(os.path.join(current_dir,\"fun01_model/rf_model.pkl\"))\n","scaler_X = joblib.load(os.path.join(current_dir,\"fun01_model/scaler_X.pkl\"))\n","scaler_y = joblib.load(os.path.join(current_dir,\"fun01_model/scaler_y.pkl\"))\n","\n","def improvement_score (success_count:int, attempt_count:int, game_score_xp:int, game_level:int, engagement_time_mins:int):\n","\n"," user_inputs = np.array([success_count, attempt_count, game_score_xp, game_level, engagement_time_mins]).reshape(1, -1)\n","\n"," # Scale the user inputs using the loaded scalers\n"," # Assuming X is your input data\n"," #scaler = StandardScaler()\n"," #user_inputs_scaled= scaler.fit_transform(user_inputs)\n"," user_inputs_scaled = scaler_X.transform(user_inputs)\n","\n"," # Make the prediction using the loaded model\n"," predicted_score_scaled = rf_model.predict(user_inputs_scaled)\n","\n"," # Inverse transform to get the predicted score back to the original scale\n"," predicted_score = scaler_y.inverse_transform(predicted_score_scaled.reshape(1, -1))\n","\n"," # Convert the predicted score to a percentage string\n"," improvement_score = f\"{predicted_score[0][0] * 10:.2f}%\"\n","\n"," return improvement_score\n","\n","def find_cosine_similarity(y1, y2):\n"," point1=y1\n"," point2=y2\n"," # Calculate the dot product of the two vectors\n"," dot_product = sum(a * b for a, b in zip(point1, point2))\n","\n"," # Calculate the magnitudes of the two vectors\n"," magnitude1 = math.sqrt(sum(a ** 2 for a in point1))\n"," magnitude2 = math.sqrt(sum(b ** 2 for b in point2))\n","\n"," # Calculate the cosine similarity\n"," cosine_similarity = dot_product / (magnitude1 * magnitude2)\n","\n"," return 1-cosine_similarity\n","\n","def arima(engagement_time_mins,n_predictions):\n","\n"," model = pm.auto_arima(engagement_time_mins, seasonal=False, m=1, suppress_warnings=True)\n","\n"," # Summary of the selected model\n"," #print(model.summary())\n","\n"," n_periods = n_predictions # You can adjust this based on how many periods you want to forecast\n"," forecast, conf_int = model.predict(n_periods=n_periods, return_conf_int=True)\n"," return forecast\n","\n","\n","\n","def function01_main(player_name:str):\n","\n"," #Return json\n"," Real_time={}\n"," ID=\"\"\n"," Future_weeks_prediction={}\n","\n"," def real_time_improvement(last_attend_improvement_score , previouse_attend_improvement_score):\n"," if last_attend_improvement_score > previouse_attend_improvement_score:\n"," massage=f\"This time you improve your workout completion rate by {improvement_presentage}% compared to the previous time.\"\n"," trend=\"Positive\"\n"," return {\"Massage\":massage,\"This_attend_improvement_score\":last_attend_improvement_score,\"previouse_attend_improvement_score\":previouse_attend_improvement_score,\n"," \"improvement_presentage\":f\"{improvement_presentage}%\",\"trend\":trend}\n","\n"," elif last_attend_improvement_score < previouse_attend_improvement_score:\n"," massage=f\"This time you decrease your exercise completion rate by {improvement_presentage}% compared to the previous time.\"\n"," trend=\"Negative\"\n"," return {\"Massage\":massage,\"This_attend_improvement_score\":last_attend_improvement_score,\"previouse_attend_improvement_score\":previouse_attend_improvement_score,\n"," \"improvement_presentage\":f\"{improvement_presentage}%\",\"trend\":trend}\n","\n"," if last_attend_improvement_score == previouse_attend_improvement_score:\n"," massage=f\"This time you not improve your workout completion rate compared to the previous time.\"\n"," trend=\"Normal\"\n"," return {\"Massage\":massage,\"This_attend_improvement_score\":last_attend_improvement_score,\"previouse_attend_improvement_score\":previouse_attend_improvement_score,\n"," \"improvement_presentage\":f\"{improvement_presentage}%\",\"trend\":trend}\n","\n","\n"," #df=pd.read_csv(file_path)\n"," #df=pd.read_csv(\"/content/drive/MyDrive/Work_space/Data set/Learn_Joy/function1/prediction/player_game_dataset.csv\")\n"," df=fire_base_player_game(player_name)\n","\n"," if len(df) != 0:\n"," #get the last attend game details\n"," pre_game=df.iloc[-1]\n","\n","\n"," ##select palyer last game and level\n"," cal_df=df[(df[\"game_name\"]==pre_game[\"game_name\"])]\n"," cal_df = cal_df.copy()\n","\n"," #create success_ratio & Success_engagement_time_mins columns & engagement_time_mins_Per_attend\n"," cal_df[\"success_ratio\"]=(cal_df[\"success_count\"] /cal_df[\"attempt_count\"])\n"," cal_df[\"Success_engagement_time_mins\"]=(cal_df[\"success_ratio\"]*cal_df[\"engagement_time_mins\"])\n"," cal_df[\"engagement_time_mins_Per_attend\"]=(cal_df[\"engagement_time_mins\"]/cal_df[\"attempt_count\"])\n","\n"," #set date colunm type to date\n"," #cal_df.loc[:, \"date\"] = pd.to_datetime(cal_df[\"date\"])#, format=\"%d/%m/%Y\"\n"," cal_df[\"date\"] = pd.to_datetime(cal_df[\"date\"])#, format=\"%d/%m/%Y\"\n"," cal_df=cal_df.sort_values(by=\"date\")#sort dataframe base by date\n","\n","\n","\n","\n","\n"," if len(cal_df)==0:\n"," massage=\"There is not enough data to process\"\n"," Real_time={\"Massage\":massage,\"This_attend_improvement_score\":None,\"previouse_attend_improvement_score\":None,\"improvement_presentage\":None,\"trend\":None}\n"," ID=0\n"," Future_weeks_prediction=None\n","\n"," elif len(cal_df)==1:\n","\n"," last_attend=cal_df.iloc[0]\n"," #last game improvement_score\n"," last_attend_improvement_score=improvement_score (success_count=last_attend[\"success_count\"], attempt_count=last_attend[\"attempt_count\"],\n"," game_score_xp=last_attend[\"game_score_xp\"], game_level=last_attend[\"game_level\"],\n"," engagement_time_mins=last_attend[\"engagement_time_mins\"])\n"," #print(last_attend_improvement_score)\n"," massage=f\"This time you improve your workout completion to {last_attend_improvement_score}\"\n","\n"," Real_time={\"Massage\":massage,\"This_attend_improvement_score\":last_attend_improvement_score\n"," ,\"previouse_attend_improvement_score\":None,\"improvement_presentage\":None,\"trend\":None}\n"," ID=0\n"," Future_weeks_prediction=None\n","\n"," elif len(cal_df) >= 2:\n","\n","\n"," #get the last and previouse attend details\n"," last_attend=cal_df.iloc[-1]\n"," previouse_attend=cal_df.iloc[-2]\n","\n","\n"," #last game improvement_score\n"," last_attend_improvement_score=improvement_score (success_count=last_attend[\"success_count\"], attempt_count=last_attend[\"attempt_count\"], game_score_xp=last_attend[\"game_score_xp\"], game_level=last_attend[\"game_level\"], engagement_time_mins=last_attend[\"engagement_time_mins\"])\n","\n"," #previouse game improvement_score\n"," previouse_attend_improvement_score=improvement_score (success_count=previouse_attend[\"success_count\"], attempt_count=previouse_attend[\"attempt_count\"], game_score_xp=previouse_attend[\"game_score_xp\"], game_level=previouse_attend[\"game_level\"], engagement_time_mins=previouse_attend[\"engagement_time_mins\"])\n","\n"," #compaired improvement\n"," y1=(last_attend[\"success_ratio\"],last_attend[\"game_level\"],last_attend[\"Success_engagement_time_mins\"],last_attend[\"game_score_xp\"])\n"," y2=(previouse_attend[\"success_ratio\"],previouse_attend[\"game_level\"],previouse_attend[\"Success_engagement_time_mins\"],previouse_attend[\"game_score_xp\"])\n","\n"," improvement_presentage=find_cosine_similarity(y1, y2)\n"," improvement_presentage=round(improvement_presentage,2)\n","\n"," #Real time predictions\n"," real_time=real_time_improvement(last_attend_improvement_score,previouse_attend_improvement_score)\n"," Real_time=real_time\n","\n","\n"," if len(cal_df) <=7:\n"," Real_time=real_time\n"," ID=1\n"," Future_weeks_prediction=None\n","\n"," elif len(cal_df) <= 14:\n"," #get the last 14 game attended dates\n"," start_date=cal_df.iloc[-len(cal_df)]\n"," end_date=cal_df.iloc[-1]\n","\n"," #create last 14 attend frequancy in day\n"," completion_freq=len(cal_df)/((end_date[\"date\"]-start_date[\"date\"]).days)\n","\n"," #create ARIMA model to previous prediction\n"," engagement_time_mins=cal_df[\"engagement_time_mins_Per_attend\"]\n","\n"," number_predictions=int(np.round(7/completion_freq))\n"," n_predictions=''\n"," if number_predictions >=28:\n"," n_predictions=28\n"," else:\n"," n_predictions=number_predictions\n","\n"," #predict nextweek engagement time\n"," forcast=arima(engagement_time_mins,int(n_predictions))\n"," after_week_engagement_time=forcast[len(cal_df)+int(n_predictions)-1]\n","\n"," #predict nextweek improvment score\n"," next_week_improvement_score=improvement_score (success_count=cal_df[\"success_count\"].mean(),\n"," attempt_count=cal_df[\"attempt_count\"].mean(), game_score_xp=cal_df[\"game_score_xp\"].mean(),\n"," game_level=last_attend[\"game_level\"], engagement_time_mins=after_week_engagement_time)\n","\n","\n"," if next_week_improvement_score >= last_attend_improvement_score:\n"," Future_weeks_prediction={\"Improvment\":\"Positive\",\"Completion frequency\":f\"{completion_freq} perday\",\n"," \"After_week_Success_engagements_Time_Min\":after_week_engagement_time,\n"," \"future_week_Success_improvement_score\":next_week_improvement_score,\"Predict_weeks\":1}\n"," ID=2\n","\n"," else :\n"," Future_weeks_prediction={\"Improvment\":\"Normal\",\"Completion frequency\":f\"{completion_freq} perday\",\n"," \"After_week_Success_engagements_Time_Min\":after_week_engagement_time,\n"," \"future_week_Success_improvement_score\":next_week_improvement_score,\"Predict_weeks\":1}\n"," ID=2\n","\n","\n","\n"," else:\n"," #get the last 7 game attended dates\n"," start_date=cal_df.iloc[-14]\n"," end_date=cal_df.iloc[-1]\n","\n"," #create last 7 attend frequancy in day\n"," play_game_count=len(cal_df.iloc[-14:])\n"," completion_freq=play_game_count/((end_date[\"date\"]-start_date[\"date\"]).days)\n","\n"," #crate ARIMA model to previous prediction\n"," engagement_time_mins=cal_df[\"engagement_time_mins_Per_attend\"]\n","\n"," number_predictions=int(np.round(14/completion_freq))\n"," n_predictions=''\n"," if number_predictions >=28:\n"," n_predictions=28\n"," else:\n"," n_predictions=number_predictions\n","\n"," forcast=arima(engagement_time_mins,int(n_predictions))\n","\n"," #predict nextweek engagement time\n"," after_week_engagement_time=forcast[len(cal_df)+int(n_predictions)-1]\n","\n"," #predict nextweek improvment score\n"," next_week_improvement_score=improvement_score (success_count=cal_df[\"success_count\"].mean(),\n"," attempt_count=cal_df[\"attempt_count\"].mean(), game_score_xp=cal_df[\"game_score_xp\"].mean(),\n"," game_level=last_attend[\"game_level\"], engagement_time_mins=after_week_engagement_time)\n","\n","\n"," if next_week_improvement_score >= last_attend_improvement_score:\n"," Future_weeks_prediction={\"Improvment\":\"Positive\",\"Completion frequency\":f\"{completion_freq} perday\",\n"," \"After_two_two_week_Success_engagements_Time_Min\":after_week_engagement_time,\n"," \"future_week_Success_improvement_score\":next_week_improvement_score,\"Predict_weeks\":2}\n"," ID=2\n","\n"," else :\n"," Future_weeks_prediction={\"Improvment\":\"Normal\",\"Completion frequency\":f\"{completion_freq} perday\",\n"," \"After_two_two_week_Success_engagements_Time_Min\":after_week_engagement_time,\n"," \"future_week_Success_improvement_score\":next_week_improvement_score,\"Predict_weeks\":2}\n"," ID=2\n","\n","\n"," else:\n"," return {\"Massage\":\"There is not enough data to process\"}\n","\n"," return {\"ID\":ID,\"Real_Time_predictions\":Real_time,'Future_weeks_Predictions':Future_weeks_prediction}\n","\n","\n"],"metadata":{"id":"cN7IqSUqo5Hg","executionInfo":{"status":"ok","timestamp":1705756153954,"user_tz":-330,"elapsed":17,"user":{"displayName":"Kaushi Gihan","userId":"11214181140146971518"}},"colab":{"base_uri":"https://localhost:8080/"},"outputId":"ff7d4d0a-71a1-41b8-e173-22369093d1a6"},"execution_count":63,"outputs":[{"output_type":"stream","name":"stdout","text":["Writing self_improvement.py\n"]}]},{"cell_type":"code","source":["test=function01_main(\"rQIRSQe3ZYTRDGfvRb8dvzaCKkA2\")\n","#test=function01_main(\"/content/drive/MyDrive/Work_space/Silverline_IT/Project/Learn_Joy/Function1/Future improvment/test2#.csv\")"],"metadata":{"id":"vSABnMZv8LxL","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1705756039491,"user_tz":-330,"elapsed":617,"user":{"displayName":"Kaushi Gihan","userId":"11214181140146971518"}},"outputId":"2ab5af2b-ddc8-432c-cc33-2d07c600c2cb"},"execution_count":60,"outputs":[{"output_type":"stream","name":"stderr","text":["/usr/local/lib/python3.10/dist-packages/sklearn/base.py:465: UserWarning: X does not have valid feature names, but StandardScaler was fitted with feature names\n"," warnings.warn(\n","/usr/local/lib/python3.10/dist-packages/sklearn/base.py:465: UserWarning: X does not have valid feature names, but StandardScaler was fitted with feature names\n"," warnings.warn(\n"]}]},{"cell_type":"code","source":["print(test)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"CZU7ZZcAUlEb","executionInfo":{"status":"ok","timestamp":1705756043997,"user_tz":-330,"elapsed":616,"user":{"displayName":"Kaushi Gihan","userId":"11214181140146971518"}},"outputId":"4a19cf4c-4aca-4b66-ef3a-781ec20f6571"},"execution_count":61,"outputs":[{"output_type":"stream","name":"stdout","text":["{'ID': 1, 'Real_Time_predictions': {'Massage': 'This time you decrease your exercise completion rate by 0.0% compared to the previous time.', 'This_attend_improvement_score': '87.50%', 'previouse_attend_improvement_score': '88.83%', 'improvement_presentage': '0.0%', 'trend': 'Negative'}, 'Future_weeks_Predictions': None}\n"]}]},{"cell_type":"code","source":["df=pd.read_csv(\"/content/drive/MyDrive/Work_space/Silverline_IT/Project/Learn_Joy/Function1/Future improvment/player_game_dataset.csv\")\n","df.head(10)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":556},"id":"z5LE1RDLIBF2","executionInfo":{"status":"ok","timestamp":1703075682516,"user_tz":-330,"elapsed":644,"user":{"displayName":"Kaushi Gihan","userId":"11214181140146971518"}},"outputId":"60fdfb60-8d7a-43f8-e57f-58223747a4f7"},"execution_count":null,"outputs":[{"output_type":"execute_result","data":{"text/plain":[" index date player_name game_name game_level success_count \\\n","0 1 2023-12-10 player01 Clock_Challenge 1 1 \n","1 2 2023-12-10 player01 Clock_Challenge 1 1 \n","2 3 2023-12-10 player01 Clock_Challenge 1 1 \n","3 4 2023-12-10 player01 Clock_Challenge 1 1 \n","4 5 2023-12-10 player01 Clock_Challenge 1 1 \n","5 6 2023-12-10 player01 Clock_Challenge 1 1 \n","6 7 2023-12-10 player01 Clock_Challenge 1 1 \n","7 8 2023-12-10 player01 Clock_Challenge 1 1 \n","8 9 2023-12-10 player01 Clock_Challenge 1 1 \n","9 10 2023-12-11 player01 Clock_Challenge 1 1 \n","\n"," attempt_count game_score_xp engagement_time_mins improvement_score \n","0 1 91 29 4.916667 \n","1 1 86 43 4.750000 \n","2 1 89 34 4.833333 \n","3 1 84 49 5.250000 \n","4 1 91 28 4.933333 \n","5 1 87 41 4.716667 \n","6 1 83 52 5.500000 \n","7 1 89 35 4.816667 \n","8 1 99 5 5.316667 \n","9 1 85 46 5.000000 "],"text/html":["\n"," <div id=\"df-0adb9c61-6004-4fe5-8a0d-4b0835344bc5\" class=\"colab-df-container\">\n"," <div>\n","<style scoped>\n"," .dataframe tbody tr th:only-of-type {\n"," vertical-align: middle;\n"," }\n","\n"," .dataframe tbody tr th {\n"," vertical-align: top;\n"," }\n","\n"," .dataframe thead th {\n"," text-align: right;\n"," }\n","</style>\n","<table border=\"1\" class=\"dataframe\">\n"," <thead>\n"," <tr style=\"text-align: right;\">\n"," <th></th>\n"," <th>index</th>\n"," <th>date</th>\n"," <th>player_name</th>\n"," <th>game_name</th>\n"," <th>game_level</th>\n"," <th>success_count</th>\n"," <th>attempt_count</th>\n"," <th>game_score_xp</th>\n"," <th>engagement_time_mins</th>\n"," <th>improvement_score</th>\n"," </tr>\n"," </thead>\n"," <tbody>\n"," <tr>\n"," <th>0</th>\n"," <td>1</td>\n"," <td>2023-12-10</td>\n"," <td>player01</td>\n"," <td>Clock_Challenge</td>\n"," <td>1</td>\n"," <td>1</td>\n"," <td>1</td>\n"," <td>91</td>\n"," <td>29</td>\n"," <td>4.916667</td>\n"," </tr>\n"," <tr>\n"," <th>1</th>\n"," <td>2</td>\n"," <td>2023-12-10</td>\n"," <td>player01</td>\n"," <td>Clock_Challenge</td>\n"," <td>1</td>\n"," <td>1</td>\n"," <td>1</td>\n"," <td>86</td>\n"," <td>43</td>\n"," <td>4.750000</td>\n"," </tr>\n"," <tr>\n"," <th>2</th>\n"," <td>3</td>\n"," <td>2023-12-10</td>\n"," <td>player01</td>\n"," <td>Clock_Challenge</td>\n"," <td>1</td>\n"," <td>1</td>\n"," <td>1</td>\n"," <td>89</td>\n"," <td>34</td>\n"," <td>4.833333</td>\n"," </tr>\n"," <tr>\n"," <th>3</th>\n"," <td>4</td>\n"," <td>2023-12-10</td>\n"," <td>player01</td>\n"," <td>Clock_Challenge</td>\n"," <td>1</td>\n"," <td>1</td>\n"," <td>1</td>\n"," <td>84</td>\n"," <td>49</td>\n"," <td>5.250000</td>\n"," </tr>\n"," <tr>\n"," <th>4</th>\n"," <td>5</td>\n"," <td>2023-12-10</td>\n"," <td>player01</td>\n"," <td>Clock_Challenge</td>\n"," <td>1</td>\n"," <td>1</td>\n"," <td>1</td>\n"," <td>91</td>\n"," <td>28</td>\n"," <td>4.933333</td>\n"," </tr>\n"," <tr>\n"," <th>5</th>\n"," <td>6</td>\n"," <td>2023-12-10</td>\n"," <td>player01</td>\n"," <td>Clock_Challenge</td>\n"," <td>1</td>\n"," <td>1</td>\n"," <td>1</td>\n"," <td>87</td>\n"," <td>41</td>\n"," <td>4.716667</td>\n"," </tr>\n"," <tr>\n"," <th>6</th>\n"," <td>7</td>\n"," <td>2023-12-10</td>\n"," <td>player01</td>\n"," <td>Clock_Challenge</td>\n"," <td>1</td>\n"," <td>1</td>\n"," <td>1</td>\n"," <td>83</td>\n"," <td>52</td>\n"," <td>5.500000</td>\n"," </tr>\n"," <tr>\n"," <th>7</th>\n"," <td>8</td>\n"," <td>2023-12-10</td>\n"," <td>player01</td>\n"," <td>Clock_Challenge</td>\n"," <td>1</td>\n"," <td>1</td>\n"," <td>1</td>\n"," <td>89</td>\n"," <td>35</td>\n"," <td>4.816667</td>\n"," </tr>\n"," <tr>\n"," <th>8</th>\n"," <td>9</td>\n"," <td>2023-12-10</td>\n"," <td>player01</td>\n"," <td>Clock_Challenge</td>\n"," <td>1</td>\n"," <td>1</td>\n"," <td>1</td>\n"," <td>99</td>\n"," <td>5</td>\n"," <td>5.316667</td>\n"," </tr>\n"," <tr>\n"," <th>9</th>\n"," <td>10</td>\n"," <td>2023-12-11</td>\n"," <td>player01</td>\n"," <td>Clock_Challenge</td>\n"," <td>1</td>\n"," <td>1</td>\n"," <td>1</td>\n"," <td>85</td>\n"," <td>46</td>\n"," <td>5.000000</td>\n"," </tr>\n"," </tbody>\n","</table>\n","</div>\n"," <div class=\"colab-df-buttons\">\n","\n"," <div class=\"colab-df-container\">\n"," <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-0adb9c61-6004-4fe5-8a0d-4b0835344bc5')\"\n"," title=\"Convert this dataframe to an interactive table.\"\n"," style=\"display:none;\">\n","\n"," <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n"," <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n"," </svg>\n"," </button>\n","\n"," <style>\n"," .colab-df-container {\n"," display:flex;\n"," gap: 12px;\n"," }\n","\n"," .colab-df-convert {\n"," background-color: #E8F0FE;\n"," border: none;\n"," border-radius: 50%;\n"," cursor: pointer;\n"," display: none;\n"," fill: #1967D2;\n"," height: 32px;\n"," padding: 0 0 0 0;\n"," width: 32px;\n"," }\n","\n"," .colab-df-convert:hover {\n"," background-color: #E2EBFA;\n"," box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n"," fill: #174EA6;\n"," }\n","\n"," .colab-df-buttons div {\n"," margin-bottom: 4px;\n"," }\n","\n"," [theme=dark] .colab-df-convert {\n"," background-color: #3B4455;\n"," fill: #D2E3FC;\n"," }\n","\n"," [theme=dark] .colab-df-convert:hover {\n"," background-color: #434B5C;\n"," box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n"," filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n"," fill: #FFFFFF;\n"," }\n"," </style>\n","\n"," <script>\n"," const buttonEl =\n"," document.querySelector('#df-0adb9c61-6004-4fe5-8a0d-4b0835344bc5 button.colab-df-convert');\n"," buttonEl.style.display =\n"," google.colab.kernel.accessAllowed ? 'block' : 'none';\n","\n"," async function convertToInteractive(key) {\n"," const element = document.querySelector('#df-0adb9c61-6004-4fe5-8a0d-4b0835344bc5');\n"," const dataTable =\n"," await google.colab.kernel.invokeFunction('convertToInteractive',\n"," [key], {});\n"," if (!dataTable) return;\n","\n"," const docLinkHtml = 'Like what you see? Visit the ' +\n"," '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n"," + ' to learn more about interactive tables.';\n"," element.innerHTML = '';\n"," dataTable['output_type'] = 'display_data';\n"," await google.colab.output.renderOutput(dataTable, element);\n"," const docLink = document.createElement('div');\n"," docLink.innerHTML = docLinkHtml;\n"," element.appendChild(docLink);\n"," }\n"," </script>\n"," </div>\n","\n","\n","<div id=\"df-b1b869a0-5298-4ab3-b27c-5f8f5b1b44ca\">\n"," <button class=\"colab-df-quickchart\" onclick=\"quickchart('df-b1b869a0-5298-4ab3-b27c-5f8f5b1b44ca')\"\n"," title=\"Suggest charts\"\n"," style=\"display:none;\">\n","\n","<svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\"viewBox=\"0 0 24 24\"\n"," width=\"24px\">\n"," <g>\n"," <path d=\"M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z\"/>\n"," </g>\n","</svg>\n"," </button>\n","\n","<style>\n"," .colab-df-quickchart {\n"," --bg-color: #E8F0FE;\n"," --fill-color: #1967D2;\n"," --hover-bg-color: #E2EBFA;\n"," --hover-fill-color: #174EA6;\n"," --disabled-fill-color: #AAA;\n"," --disabled-bg-color: #DDD;\n"," }\n","\n"," [theme=dark] .colab-df-quickchart {\n"," --bg-color: #3B4455;\n"," --fill-color: #D2E3FC;\n"," --hover-bg-color: #434B5C;\n"," --hover-fill-color: #FFFFFF;\n"," --disabled-bg-color: #3B4455;\n"," --disabled-fill-color: #666;\n"," }\n","\n"," .colab-df-quickchart {\n"," background-color: var(--bg-color);\n"," border: none;\n"," border-radius: 50%;\n"," cursor: pointer;\n"," display: none;\n"," fill: var(--fill-color);\n"," height: 32px;\n"," padding: 0;\n"," width: 32px;\n"," }\n","\n"," .colab-df-quickchart:hover {\n"," background-color: var(--hover-bg-color);\n"," box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);\n"," fill: var(--button-hover-fill-color);\n"," }\n","\n"," .colab-df-quickchart-complete:disabled,\n"," .colab-df-quickchart-complete:disabled:hover {\n"," background-color: var(--disabled-bg-color);\n"," fill: var(--disabled-fill-color);\n"," box-shadow: none;\n"," }\n","\n"," .colab-df-spinner {\n"," border: 2px solid var(--fill-color);\n"," border-color: transparent;\n"," border-bottom-color: var(--fill-color);\n"," animation:\n"," spin 1s steps(1) infinite;\n"," }\n","\n"," @keyframes spin {\n"," 0% {\n"," border-color: transparent;\n"," border-bottom-color: var(--fill-color);\n"," border-left-color: var(--fill-color);\n"," }\n"," 20% {\n"," border-color: transparent;\n"," border-left-color: var(--fill-color);\n"," border-top-color: var(--fill-color);\n"," }\n"," 30% {\n"," border-color: transparent;\n"," border-left-color: var(--fill-color);\n"," border-top-color: var(--fill-color);\n"," border-right-color: var(--fill-color);\n"," }\n"," 40% {\n"," border-color: transparent;\n"," border-right-color: var(--fill-color);\n"," border-top-color: var(--fill-color);\n"," }\n"," 60% {\n"," border-color: transparent;\n"," border-right-color: var(--fill-color);\n"," }\n"," 80% {\n"," border-color: transparent;\n"," border-right-color: var(--fill-color);\n"," border-bottom-color: var(--fill-color);\n"," }\n"," 90% {\n"," border-color: transparent;\n"," border-bottom-color: var(--fill-color);\n"," }\n"," }\n","</style>\n","\n"," <script>\n"," async function quickchart(key) {\n"," const quickchartButtonEl =\n"," document.querySelector('#' + key + ' button');\n"," quickchartButtonEl.disabled = true; // To prevent multiple clicks.\n"," quickchartButtonEl.classList.add('colab-df-spinner');\n"," try {\n"," const charts = await google.colab.kernel.invokeFunction(\n"," 'suggestCharts', [key], {});\n"," } catch (error) {\n"," console.error('Error during call to suggestCharts:', error);\n"," }\n"," quickchartButtonEl.classList.remove('colab-df-spinner');\n"," quickchartButtonEl.classList.add('colab-df-quickchart-complete');\n"," }\n"," (() => {\n"," let quickchartButtonEl =\n"," document.querySelector('#df-b1b869a0-5298-4ab3-b27c-5f8f5b1b44ca button');\n"," quickchartButtonEl.style.display =\n"," google.colab.kernel.accessAllowed ? 'block' : 'none';\n"," })();\n"," </script>\n","</div>\n","\n"," </div>\n"," </div>\n"]},"metadata":{},"execution_count":112}]},{"cell_type":"markdown","source":["###Additional dashboard"],"metadata":{"id":"ju3KCNCSBA-R"}},{"cell_type":"code","source":["#return variable\n","massage=\"\"\n","\n","\n","Game_name=\"Clock_Challenge\"\n","date_string = \"2023-12-11\" # Assuming the date is in the format \"YYYY-MM-DD\"\n","\n","\n","# Convert the string to a datetime object\n","date_format = \"%Y-%m-%d\" # Define the format of the date string\n","date= datetime.strptime(date_string, date_format)\n","\n","\n","new_df=df[(df[\"game_name\"]==Game_name)]\n","\n","if len(new_df) ==0:\n"," massage=\"This player has not played this game before\"\n","\n","else:\n"," if date in new_df[\"date\"].values:\n"," #preprocess the dataset\n"," new_df[\"success_ratio\"]=(new_df[\"success_count\"] /new_df[\"attempt_count\"])\n"," new_df[\"Success_engagement_time_mins\"]=(new_df[\"success_ratio\"]*new_df[\"engagement_time_mins\"])\n"," new_df[\"engagement_time_mins_Per_attend\"]=(new_df[\"engagement_time_mins\"]/new_df[\"attempt_count\"])\n"," new_df.loc[:, \"date\"] = pd.to_datetime(new_df[\"date\"])#, format=\"%d/%m/%Y\"\n"," new_df=new_df.sort_values(by=\"date\")\n","\n"," #get the unic date for proccess\n"," index_list = new_df.loc[new_df[\"date\"] == date].index\n"," need_date=new_df.loc[index_list[0]]\n","\n"," print(new_df[\"date\"].values)"],"metadata":{"id":"BdBfC04LJdLu"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["##FAstAPI"],"metadata":{"id":"d_F1Z7g5-wyO"}},{"cell_type":"code","source":["!pip install python-multipart\n","!pip install fastapi -q\n","!pip install pyngrok -q\n","!pip install uvicorn -q\n","!pip install pydantic -q\n","!pip install nest-asyncio"],"metadata":{"id":"WvDTDxdS-yb5"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["from fastapi import FastAPI\n","from pydantic import BaseModel\n","import uvicorn\n","from pyngrok import ngrok\n","import nest_asyncio"],"metadata":{"id":"dYFs3zfbApum"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["%%writefile app001.py\n","from fastapi import FastAPI\n","from fastapi import File, UploadFile\n","from typing import List\n","from pydantic import BaseModel\n","\n","import tempfile\n","import os\n","import shutil\n","\n","\n","app=FastAPI(title=\"Learn Joy\",\n"," description=\"FastAPI for Learn_Joy\",\n"," version=\"0.104.1\")\n","\n","@app.get(\"/\")\n","async def root():\n"," return{\"Fast API\":\"Hello World\"}\n","\n","@app.post(\"/function01/self_improvement\")\n","async def function1_self_improvement(player_details:UploadFile =File(...)):\n"," out_put={}\n"," temp_dir = tempfile.mkdtemp()\n","\n"," # Create a temporary file path foe doner file\n"," player_details_path = os.path.join(temp_dir,player_details.filename)\n","\n"," # Write the uploaded file content to the temporary file\n"," with open(player_details_path, \"wb\") as temp_file1:\n"," shutil.copyfileobj(player_details.file, temp_file1)\n","\n"," out_put=function01_main(file_path=player_details_path)\n","\n","\n"," # Clean up: Remove the temporary directory and its contents\n"," shutil.rmtree(temp_dir)\n","\n"," return out_put"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"h9a_yiem-8K_","executionInfo":{"status":"ok","timestamp":1703090160384,"user_tz":-330,"elapsed":17,"user":{"displayName":"Kaushi Gihan","userId":"11214181140146971518"}},"outputId":"accb3a12-f6b8-40d2-f477-1e292e736848"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["Writing app001.py\n"]}]},{"cell_type":"code","source":["ngrok.set_auth_token(\"2YX5IJustLB5zcqU9rbzA9iZLVf_86pZKjHT2kXNELQgLRkyi\")"],"metadata":{"id":"K5y0FioBAPQ1"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["ngrok_tunnel = ngrok.connect(8000)\n","print('Public URL:', ngrok_tunnel.public_url)\n","nest_asyncio.apply()\n","uvicorn.run(app, port=8000)"],"metadata":{"id":"q_f5Ni5WARSh"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["ngrok.disconnect(\"2YX5IJustLB5zcqU9rbzA9iZLVf_86pZKjHT2kXNELQgLRkyi\")"],"metadata":{"id":"fKFyJsqZD7H1"},"execution_count":null,"outputs":[]}]}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment