import requests import pandas as pd from datetime import datetime import json import traceback def get_all_feilds_data(UID): endpointUrl = ( "https://us-central1-farmbase-b2f7e.cloudfunctions.net/getAllFarmersData" ) bodyObj = { "UID": UID, } response = requests.post(endpointUrl, json=bodyObj) print("Status code: ", response.status_code) return response def get_single_field_data(UID, FieldID): endpointUrl = "https://us-central1-farmbase-b2f7e.cloudfunctions.net/getFarmerData" bodyObj = {"UID": UID, "FieldID": FieldID} response = requests.post(endpointUrl, json=bodyObj) # print("Status code: ", response.status_code) return response def get_sesnsed_days(UID, FieldID): endpointUrl = "https://us-central1-farmbase-b2f7e.cloudfunctions.net/getSensedDays" bodyObj = { # "PolygonID" : "1668483636222", "UID": UID, "FieldID": FieldID, } response = requests.post(endpointUrl, json=bodyObj) # print("Status code: ", response.status_code) return response def get_sat_image(UID, fieldId, SensedDay, ImageType): endpointUrl = "https://us-central1-farmbase-b2f7e.cloudfunctions.net/getFieldImage" bodyObj = { "UID": UID, "FieldID": fieldId, "ImageType": ImageType, "SensedDay": SensedDay, "Colormap": "1", } response = requests.post(endpointUrl, json=bodyObj) return response.json()["url"] def calculate_pixel_count(image_url): from PIL import Image import numpy as np import requests from io import BytesIO # Function to download image from URL def download_image_from_url(url): response = requests.get(url) if response.status_code == 200: image = Image.open(BytesIO(response.content)) return image else: print("Failed to download image") return None # Open the image # image = Image.open(image_url) image = download_image_from_url(image_url) # Convert the image to a numpy array image_array = np.array(image) # Define the color palette colors = { (255, 255, 255, 255): "White", (0, 0, 0, 0): "EmptyColor", (17, 167, 95, 255): "Green", # #11a75f (145, 16, 44, 255): "Red", # #91102c (234, 79, 59, 255): "Orange", # #ea4f3b (60, 19, 97, 255): "Purple", # #3c1361 } # Count pixels for each color color_counts = {} total_pixels = 0 # Initialize total pixel count for color, name in colors.items(): if name != "EmptyColor": # Exclude "EmptyColor" count = np.sum(np.all(image_array == color, axis=-1)) total_pixels += count # Increment total_pixels color_counts[name] = count # Calculate percentage for each color color_percentages = {} for name, count in color_counts.items(): percentage = (count / total_pixels) * 100 color_percentages[name] = percentage return color_percentages def get_last_sensed_day(UID, FieldID): sensed_days = get_sesnsed_days(UID, FieldID) try: sensed_days_json = sensed_days.json() except:# json.JSONDecodeError: #print(traceback.format_exc()) sensed_days_json = None #return None if sensed_days_json is not None: # Convert the keys to datetime objects sensed_days_dates = [ datetime.strptime(key, "%Y%m%d") for key in sensed_days_json.keys() ] # Find the maximum datetime object latest_sensed_day = max(sensed_days_dates) # Convert the maximum datetime object back to a string representation latest_sensed_day_str = latest_sensed_day.strftime("%Y%m%d") return latest_sensed_day_str #UID = "CFv7IjeJR8ZKFWSXb95qzgvymCv1" # Kapil farmonaut #UID = "ipRHhCOFIDV2pxgg7Nfz1ufZBmV2" # UID = "lnR1AGuLgmPWk5ZzEtFS3FlGRj42" def make_interactive_html_report(UID): all_fields_data = get_all_feilds_data(UID) data_all_Field = [] for fieldId, fieldDetails in all_fields_data.json().items(): lat_lon_pairs = [] if "Coordinates" in fieldDetails: # Define custom sorting order def custom_sort(key): if key == "a": return 0 elif key.startswith("P_"): return int(key[2:]) else: return float("inf") # Place any other keys at the end # Sort the keys of the Coordinates dictionary using the custom sorting function sorted_coordinates = sorted( fieldDetails["Coordinates"].keys(), key=custom_sort, ) # Iterate over the sorted keys for point in sorted_coordinates: coordinates = fieldDetails["Coordinates"][point] latitude = float(coordinates["Latitude"]) longitude = float(coordinates["Longitude"]) lat_lon_pairs.append([latitude, longitude]) # for point, coordinates in fieldDetails["Coordinates"].items(): # latitude = float(coordinates["Latitude"]) # longitude = float(coordinates["Longitude"]) # lat_lon_pairs.append([latitude, longitude]) if lat_lon_pairs: lat_lon_pairs.append(lat_lon_pairs[0]) data_all_Field.append( { "FieldID": fieldId, "FieldAddress": fieldDetails.get("FieldAddress", fieldDetails.get("FieldDescription", fieldDetails.get("Name", fieldDetails.get("Phone", "")))), ##fieldDetails["FieldAddress"], "FieldArea": fieldDetails["FieldArea"], "FieldMaxLat": fieldDetails["FieldMaxLat"], "FieldMaxLong": fieldDetails["FieldMaxLong"], "FieldMinLat": fieldDetails["FieldMinLat"], "FieldMinLong": fieldDetails["FieldMinLong"], # "hUnits": fieldDetails["hUnits"], "coodfinates": lat_lon_pairs, } ) else: continue df_field_data = pd.DataFrame(data_all_Field) # Initialize an empty list to store dictionaries data_list = [] # Iterate over each row in the DataFrame i = 0 for index, row in df_field_data.iterrows(): # Extract data from the DataFrame row maxLat = row["FieldMaxLat"] maxLon = row["FieldMaxLong"] minLat = row["FieldMinLat"] minLon = row["FieldMinLong"] fieldName = row["FieldAddress"] fieldArea = "{:,} sq m".format(row["FieldArea"]) coordinates = row["coodfinates"] fieldId = row["FieldID"] lastSatelliteVisit = get_last_sensed_day(UID, fieldId) ##row["latest_satellite_visit"] if lastSatelliteVisit is None: ## skip continue # Generate image URL ImageType = "hybrid" image_url = get_sat_image(UID, fieldId, lastSatelliteVisit, ImageType) # Calculate pixel count percentage_data = calculate_pixel_count(image_url) lastSatelliteVisit = datetime.strptime(lastSatelliteVisit, "%Y%m%d").strftime("%d %B %Y") # Construct the dictionary for this row row_dict = { "url": image_url, "maxLat": maxLat, "maxLon": maxLon, "minLat": minLat, "minLon": minLon, "fieldName": fieldName, "fieldArea": fieldArea, "lastSatelliteVisit": lastSatelliteVisit, "Satellite_Data": { "white":"{:.2f}%".format(float(percentage_data["White"])), "green": "{:.2f}%".format(float(percentage_data["Green"])), "orange": "{:.2f}%".format(float(percentage_data["Orange"])), "purple": "{:.2f}%".format(float(percentage_data["Purple"])), "red": "{:.2f}%".format(float(percentage_data["Red"])), }, "coordinates": coordinates, } # Append the dictionary to the list data_list.append(row_dict) if ((i%50) == 0): print(i) i = i+1 # Convert the list of dictionaries to a JSON string json_data = json.dumps(data_list, indent=2) # Read the content of the HTML file template_file_name = "report_template_interactive.html" file_name = datetime.today().strftime("%Y%m%d") + "_" + UID[:5] + ".html" file_name = UID + "/interactive_report.html" with open(template_file_name, "r", encoding="utf-8") as file: content_str = file.read() content_str = content_str.replace("DATA_TO_REPLACE", json_data) ## Report Data content_str = content_str.replace("DATE_TO_REPLACE", datetime.today().strftime("%d %B %Y")) ## Report Date # Save the modified HTML content with open(file_name, "w") as f: f.write(content_str)