{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "ename": "", "evalue": "", "output_type": "error", "traceback": [ "\u001b[1;31mThe kernel failed to start as '_psutil_linux' could not be imported from 'most likely due to a circular import'.\n", "\u001b[1;31mClick here for more info." ] } ], "source": [ "import requests\n", "import pandas as pd\n", "from datetime import datetime\n", "import json\n", "\n", "\n", "def get_all_feilds_data(UID):\n", " endpointUrl = (\n", " \"https://us-central1-farmbase-b2f7e.cloudfunctions.net/getAllFarmersData\"\n", " )\n", " bodyObj = {\n", " \"UID\": UID,\n", " }\n", "\n", " response = requests.post(endpointUrl, json=bodyObj)\n", "\n", " print(\"Status code: \", response.status_code)\n", "\n", "\n", " return response\n", "\n", "\n", "def get_single_field_data(UID, FieldID):\n", " endpointUrl = \"https://us-central1-farmbase-b2f7e.cloudfunctions.net/getFarmerData\"\n", " bodyObj = {\"UID\": UID, \"FieldID\": FieldID}\n", "\n", " response = requests.post(endpointUrl, json=bodyObj)\n", "\n", " # print(\"Status code: \", response.status_code)\n", "\n", " return response\n", "\n", "\n", "def get_sesnsed_days(UID, FieldID):\n", " endpointUrl = \"https://us-central1-farmbase-b2f7e.cloudfunctions.net/getSensedDays\"\n", " bodyObj = {\n", " # \"PolygonID\" : \"1668483636222\",\n", " \"UID\": UID,\n", " \"FieldID\": FieldID,\n", " }\n", "\n", " response = requests.post(endpointUrl, json=bodyObj)\n", "\n", " # print(\"Status code: \", response.status_code)\n", "\n", " return response\n", "\n", "\n", "def get_sat_image(UID, fieldId, SensedDay, ImageType):\n", "\n", " endpointUrl = \"https://us-central1-farmbase-b2f7e.cloudfunctions.net/getFieldImage\"\n", " bodyObj = {\n", " \"UID\": UID,\n", " \"FieldID\": fieldId,\n", " \"ImageType\": ImageType,\n", " \"SensedDay\": SensedDay,\n", " \"Colormap\": \"1\",\n", " }\n", "\n", " response = requests.post(endpointUrl, json=bodyObj)\n", "\n", "\n", " return response.json()[\"url\"]\n", "\n", "\n", "def calculate_pixel_count(image_url):\n", " from PIL import Image\n", " import numpy as np\n", " import requests\n", " from io import BytesIO\n", "\n", " # Function to download image from URL\n", "\n", " def download_image_from_url(url):\n", " response = requests.get(url)\n", " if response.status_code == 200:\n", " image = Image.open(BytesIO(response.content))\n", " return image\n", " else:\n", " print(\"Failed to download image\")\n", " return None\n", "\n", " # Open the image\n", " # image = Image.open(image_url)\n", " image = download_image_from_url(image_url)\n", "\n", " # Convert the image to a numpy array\n", " image_array = np.array(image)\n", "\n", " # Define the color palette\n", " colors = {\n", " (255, 255, 255, 255): \"White\",\n", " (0, 0, 0, 0): \"EmptyColor\",\n", " (17, 167, 95, 255): \"Green\", # #11a75f\n", " (145, 16, 44, 255): \"Red\", # #91102c\n", " (234, 79, 59, 255): \"Orange\", # #ea4f3b\n", " (60, 19, 97, 255): \"Purple\", # #3c1361\n", " }\n", "\n", " # Count pixels for each color\n", " color_counts = {}\n", " total_pixels = 0 # Initialize total pixel count\n", " for color, name in colors.items():\n", " if name != \"EmptyColor\": # Exclude \"EmptyColor\"\n", " count = np.sum(np.all(image_array == color, axis=-1))\n", " total_pixels += count # Increment total_pixels\n", " color_counts[name] = count\n", "\n", " # Calculate percentage for each color\n", " color_percentages = {}\n", " for name, count in color_counts.items():\n", " percentage = (count / total_pixels) * 100\n", " color_percentages[name] = percentage\n", "\n", " return color_percentages\n", "\n", "\n", "\n", " \n", "def get_last_sensed_day(UID, FieldID):\n", " \n", " sensed_days = get_sesnsed_days(UID, FieldID)\n", " \n", " try:\n", " sensed_days_json = sensed_days.json()\n", " except json.JSONDecodeError:\n", " return None\n", "\n", " if sensed_days_json:\n", " # Convert the keys to datetime objects\n", " sensed_days_dates = [\n", " datetime.strptime(key, \"%Y%m%d\") for key in sensed_days_json.keys()\n", " ]\n", "\n", " # Find the maximum datetime object\n", " latest_sensed_day = max(sensed_days_dates)\n", "\n", " # Convert the maximum datetime object back to a string representation\n", " latest_sensed_day_str = latest_sensed_day.strftime(\"%Y%m%d\")\n", " \n", " \n", " return latest_sensed_day_str\n" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Status code: 200\n" ] } ], "source": [ "UID = \"CFv7IjeJR8ZKFWSXb95qzgvymCv1\" # Kapil farmonaut\n", "UID = \"ipRHhCOFIDV2pxgg7Nfz1ufZBmV2\" \n", "# UID = \"lnR1AGuLgmPWk5ZzEtFS3FlGRj42\" \n", "\n", "\n", "\n", "all_fields_data = get_all_feilds_data(UID)\n", "\n", "\n", "data_all_Field = []\n", "\n", "for fieldId, fieldDetails in all_fields_data.json().items():\n", " lat_lon_pairs = []\n", " \n", " \n", " if \"Coordinates\" in fieldDetails:\n", " for point, coordinates in fieldDetails[\"Coordinates\"].items():\n", " latitude = float(coordinates[\"Latitude\"])\n", " longitude = float(coordinates[\"Longitude\"])\n", " lat_lon_pairs.append([latitude, longitude])\n", " \n", " if lat_lon_pairs:\n", " lat_lon_pairs.append(lat_lon_pairs[0])\n", "\n", " data_all_Field.append(\n", " {\n", " \"FieldID\": fieldId,\n", " \"FieldAddress\": fieldDetails.get(\"FieldAddress\", fieldDetails.get(\"FieldDescription\", fieldDetails.get(\"Name\", fieldDetails.get(\"Phone\", \"\")))), ##fieldDetails[\"FieldAddress\"],\n", " \"FieldArea\": fieldDetails[\"FieldArea\"],\n", " \"FieldMaxLat\": fieldDetails[\"FieldMaxLat\"],\n", " \"FieldMaxLong\": fieldDetails[\"FieldMaxLong\"],\n", " \"FieldMinLat\": fieldDetails[\"FieldMinLat\"],\n", " \"FieldMinLong\": fieldDetails[\"FieldMinLong\"],\n", " # \"hUnits\": fieldDetails[\"hUnits\"],\n", " \"coodfinates\": lat_lon_pairs,\n", " }\n", "\n", " )\n", " else:\n", " continue\n", "\n", "df_field_data = pd.DataFrame(data_all_Field)\n", "\n", "\n", "\n", "# Initialize an empty list to store dictionaries\n", "data_list = []\n", "\n", "# Iterate over each row in the DataFrame\n", "for index, row in df_field_data.iterrows():\n", " # Extract data from the DataFrame row\n", " maxLat = row[\"FieldMaxLat\"]\n", " maxLon = row[\"FieldMaxLong\"]\n", " minLat = row[\"FieldMinLat\"]\n", " minLon = row[\"FieldMinLong\"]\n", " fieldName = row[\"FieldAddress\"]\n", " fieldArea = \"{:,} sq m\".format(row[\"FieldArea\"])\n", " \n", " coordinates = row[\"coodfinates\"]\n", " fieldId = row[\"FieldID\"]\n", "\n", "\n", " lastSatelliteVisit = get_last_sensed_day(UID, fieldId) ##row[\"latest_satellite_visit\"]\n", " \n", " \n", " if lastSatelliteVisit is None:\n", " ## skip\n", " continue\n", "\n", "\n", " # Generate image URL\n", " ImageType = \"hybrid\"\n", " image_url = get_sat_image(UID, fieldId, lastSatelliteVisit, ImageType)\n", "\n", " # Calculate pixel count\n", " percentage_data = calculate_pixel_count(image_url)\n", " \n", " lastSatelliteVisit = datetime.strptime(lastSatelliteVisit, \"%Y%m%d\").strftime(\"%d %B %Y\")\n", "\n", " # Construct the dictionary for this row\n", " row_dict = {\n", " \"url\": image_url,\n", " \"maxLat\": maxLat,\n", " \"maxLon\": maxLon,\n", " \"minLat\": minLat,\n", " \"minLon\": minLon,\n", " \"fieldName\": fieldName,\n", " \"fieldArea\": fieldArea,\n", " \"lastSatelliteVisit\": lastSatelliteVisit,\n", " \"Satellite_Data\": {\n", " \"white\":\"{:.2f}%\".format(float(percentage_data[\"White\"])),\n", " \"green\": \"{:.2f}%\".format(float(percentage_data[\"Green\"])),\n", " \"orange\": \"{:.2f}%\".format(float(percentage_data[\"Orange\"])),\n", " \"purple\": \"{:.2f}%\".format(float(percentage_data[\"Purple\"])),\n", " \"red\": \"{:.2f}%\".format(float(percentage_data[\"Red\"])),\n", " },\n", " \"coordinates\": coordinates,\n", " }\n", "\n", " # Append the dictionary to the list\n", " data_list.append(row_dict)\n", " \n", " \n", "\n", "# Convert the list of dictionaries to a JSON string\n", "json_data = json.dumps(data_list, indent=2)\n", "\n", "# Read the content of the HTML file\n", "\n", "template_file_name = \"report_template_interactive.html\"\n", "file_name = datetime.today().strftime(\"%Y%m%d\") + \"_\" + UID[:5] + \".html\"\n", "\n", "with open(template_file_name, \"r\", encoding=\"utf-8\") as file:\n", " content_str = file.read()\n", " \n", "\n", "content_str = content_str.replace(\"DATA_TO_REPLACE\", json_data) ## Report Data\n", "content_str = content_str.replace(\"DATE_TO_REPLACE\", datetime.today().strftime(\"%d %B %Y\")) ## Report Date\n", "\n", "\n", "# Save the modified HTML content\n", "with open(file_name, \"w\") as f:\n", " f.write(content_str)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3.8.0 64-bit", "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.8.0" }, "vscode": { "interpreter": { "hash": "df0893f56f349688326838aaeea0de204df53a132722cbd565e54b24a8fec5f6" } } }, "nbformat": 4, "nbformat_minor": 2 }