from tempfile import tempdir import firebase_admin from firebase_admin import credentials from firebase_admin import db from find_s1_image2 import find_img_value import pandas as pdf from sklearn.metrics import classification_report, confusion_matrix, accuracy_score import statsmodels.api as sm import seaborn as sns sns.set() import traceback from sklearn.ensemble import RandomForestRegressor from sklearn.model_selection import train_test_split import csv import time import json from find_modis_ndvi import find_modis_ndvi import numpy as np from sklearn.cluster import KMeans from sentinelhub import WebFeatureService, BBox, CRS, MimeType, CRS, BBox, WmsRequest,DataCollection import traceback from get_mask import get_mask from PIL import Image import numpy as np from google.cloud import storage import requests from simplify_coordinates import simplify_coordinates cred = credentials.Certificate('servicekey.json') x = 0.0003 y = 0.0003 fromdate = '20220701' todate = '20220715' s1_images = ['IW-VH-DB'] s2_images = [] # s1_images = ["B02", "B03", "B04", "B05"] #s2_images = ["RVI-NEW"] try: firebase_admin.initialize_app(cred, {'databaseURL': 'https://farmbase-b2f7e-31c0c.firebaseio.com/'}) except: print('fire running') #get all non_gt farms #uid = 'lnR1AGuLgmPWk5ZzEtFS3FlGRj42' # field_ids = [1679967002882, 1679966729923, 1679564467926, 1676093083960, 1676092753184, 1676092238980, 1676092127138, 1676092080769, 1675836972336, 1675836874915, 1675836770812, 1675836706947, 1675224126040, 1675223688824, 1675223584847, 1675222777316, 1675222680174, 1675220202897, 1675219711420, 1675219573442, 1675219344911] # for fieldid in field_ids: # fieldid = str(fieldid) # field_obj = db.reference('PaidMonitoredFields').child('PMF').child(uid).child(fieldid).child('SensedDays').delete() # time.sleep(0.1) #uid = 'qL4tgUcl1ggqLRFFgxTNbTgP3uk1' uid = 'M53J9SImW9My4vghlCaaWLYxsc22' #uid ='3slpdq65yYXR6M9zDU2I3Ng6kRD2' uid = 'sAiJIWRbNOR5grDmRabVxW5BXp03' uid = '4bsSM4efIGhVVmOUyJv8DshNxYG3' uid = 'ENLgcB9pl2fH7MjsEH7oc72YBRh2' uid = 'b0oOOCM3jFUHMy9CsL2RYENMAHC3' uid = 'cO3iCeT1cYfPpmq35RYVE9nWTFz1' uid = 'hbPx8Vep5OTxnouajuHKkg0PXvw2' uid = 'XSzwRsmzu4OeCm8UvllGn7xsnOk1' uid = 'D4xU2QGhooXfK6qiEeHdAlp0wk53' from math import radians, sin, cos, atan2, sqrt def haversine(lat1, lon1, lat2, lon2): """ Calculate the haversine distance between two points on the sphere. Parameters: - lat1, lon1: Latitude and longitude of the first point in degrees. - lat2, lon2: Latitude and longitude of the second point in degrees. Returns: - distance: Haversine distance in meters. """ R = 6371000.0 # Radius of the Earth in meters dlat = radians(lat2 - lat1) dlon = radians(lon2 - lon1) a = sin(dlat / 2) ** 2 + cos(radians(lat1)) * cos(radians(lat2)) * sin(dlon / 2) ** 2 c = 2 * atan2(sqrt(a), sqrt(1 - a)) distance = R * c return distance def calculate_polygon_area(coords): """ Calculate the area of a polygon defined by latitude and longitude coordinates. Parameters: - coords: List of coordinate pairs in the format [[longitude1, latitude1], [longitude2, latitude2], ...] Returns: - area: Area of the polygon in square meters. """ if len(coords) < 3: raise ValueError("Polygon must have at least 3 vertices.") # Convert coordinates to radians coords_rad = [(radians(lat), radians(lon)) for lon, lat in coords] # Calculate the haversine distances distances = [haversine(lat1, lon1, lat2, lon2) for (lat1, lon1), (lat2, lon2) in zip(coords_rad, coords_rad[1:] + [coords_rad[0]])] # Calculate the area using the shoelace formula area = 0.5 * sum(distances) return area def make_coords_array(coords_obj): p_num = 0 coords_arr = [] for key,val in coords_obj.items(): #print(val) if p_num == 0: coords_arr.append([float(coords_obj["a"]["Longitude"]), float(coords_obj["a"]["Latitude"])]) else: coords_arr.append([float(coords_obj[("P_"+str(p_num))]["Longitude"]), float(coords_obj[("P_"+str(p_num))]["Latitude"])]) p_num = p_num +1 coords_arr.append([float(coords_obj["a"]["Longitude"]), float(coords_obj["a"]["Latitude"])]) #print(coords_arr) return coords_arr # Example usage #coordinates = [[80.79032187811988, 27.700518612355072], [80.79072902097701, 27.700518612355072], [80.79087366383416, 27.70043798013237], [80.79087098526273, 27.699932841616832], [80.7904825924056, 27.69993047006898], [80.79028437811989, 27.700044304307212], [80.79032187811988, 27.700518612355072]] #print(f"The area of the polygon is approximately {area:.2f} square meters.") #test_uid = 'MtO6G7AvlnPgQxAajMP6NtLS8fN2' uid = 'lnR1AGuLgmPWk5ZzEtFS3FlGRj42' all_uids_obj = db.reference('PaidMonitoredFields').child('PMF').get(False,True) current_field_ids = [] total_units = 0 unit_cost = 250 total_cost = 0 main_arr = [] for (uid, val) in all_uids_obj.items(): kisanwala_obj = db.reference('PaidMonitoredFields').child('PMF').child(uid).get() for (fieldid, fieldObj) in kisanwala_obj.items(): try: area = fieldObj["FieldArea"] # Replace the URL with the actual endpoint you want to send the POST request to url = "https://us-central1-farmbase-b2f7e.cloudfunctions.net/getFieldAreaByBoundaryPoints" # Replace this dictionary with your JSON data data = { "UID": "BpkwnSJdwHTjKhdm8ZWKJBO1HUn2", "Points": fieldObj["Coordinates"] } # Convert the dictionary to a JSON string json_data = json.dumps(data) # Set the headers to indicate that you are sending JSON data headers = { "Content-Type": "application/json", } # Make the POST request response = requests.post(url, data=json_data, headers=headers) res_obj = response.json() # print(response.text) field_area = res_obj.get("FieldArea") print(fieldid, area, field_area) db.reference('PaidMonitoredFields').child('PMF').child(uid).child(fieldid).child('FieldArea').set(field_area) time.sleep(1) # area2 = calculate_polygon_area(make_coords_array(fieldObj["Coordinates"])) # print(fieldid,area, round(area2,0)) # db.reference('PaidMonitoredFields').child('PMF').child(uid) # paymentType = fieldObj["PaymentType"] # #if int(area) < 1000*10000: # # total_units = total_units + int(area) # sensed_days = fieldObj.get("SensedDays",None) # prev_days = fieldObj.get("PreviousDataRequests",None) # sensed_num = 0 # prev_num = 0 # if prev_days is not None: # for(k,v) in prev_days.items(): # prev_num = prev_num + 1 # if sensed_days is not None: # for(k,v) in sensed_days.items(): # sensed_num = sensed_num + 1 # prev_num = 0 #sensed_num = 0 # cost = round((1+(prev_num+sensed_num)/6)*int(area)*1*unit_cost/(100*10000),0) # #cost = round((prev_num+sensed_num)/6,0)*round((int(area)*2*unit_cost/(100*10000)),0) # #cost = round((int(paymentType)*int(area)*2*unit_cost/(100*10000)),0) # if int(area) < 2000*10000: # total_units = total_units + int(area) # total_cost = cost + total_cost # #print(fieldid,round((int(area)/10000),2), round((sensed_num+prev_num)/6,0),cost,total_cost,sensed_num, prev_num) # #ior single_field in fields_arr: # # fields_obj[single_field[1]] = single_field[0] # main_arr.append([str(fieldid),round((int(area)/10000),2), round((1+(sensed_num+prev_num)/6),0),cost]) except: print(traceback.format_exc()) csv_file_path = 'trst.csv' # Open the CSV file in write mode with open(csv_file_path, 'w', newline='') as csv_file: # Create a CSV writer object csv_writer = csv.writer(csv_file) # Write the rows from the array to the CSV file csv_writer.writerows(main_arr) #points_obj = fieldObj["Coordinates"] #points_num =0 #for (key, val) in points_obj.items(): # points_num = points_num + 1 #if points_num > 15: # points_arr = [] # for i in range (0, points_num): # if i == 0: # points_arr.append([float(points_obj["a"]["Latitude"]), float(points_obj["a"]["Longitude"])]) # else: # points_arr.append([float(points_obj[("P_"+str(i))]["Latitude"]), float(points_obj[("P_"+str(i))]["Longitude"])]) # tolerance = 0.00005 # print(points_arr) # found_coordinates = simplify_coordinates(points_arr, tolerance) # new_points_obj = {} # for i in range (0, len(found_coordinates)): # temp_point = {} # temp_point["Latitude"] = found_coordinates[i][0] # temp_point["Longitude"] = found_coordinates[i][1] # if i == 0: # new_points_obj["a"] = temp_point # else: # new_points_obj[("P_"+str(i))] = temp_point # fieldObj["Coordinates"] = new_points_obj # fieldid = str(fieldid) # print(fieldid) # db.reference('PaidMonitoredFields').child('PMF').child(uid).child(fieldid).set(fieldObj) # break # db.reference('PaidMonitoredFields').child('PMF').child(uid).child(fieldid).child('Expired').delete() # db.reference('PaidMonitoredFields').child('PMF').child(uid).child(fieldid).child('Expiring').delete() # db.reference('PaidMonitoredFields').child('PMF').child(uid).child(fieldid).child('Paused').set('no') # db.reference('PaidMonitoredFields').child('PMF').child(uid).child(fieldid).child('PaymentType').set('8') # fd = db.reference('PaidMonitoredFields').child('PMF').child(uid).child(fieldid).child('SensedDays').get() # area_sq = db.reference('PaidMonitoredFields').child('PMF').child(uid).child(fieldid).child('FieldArea').get() # area_ha = round(int(area_sq)/10000) # if area_ha < 1: # area_ha = 1 # day_count = 0 # for(p,q) in fd.items(): # day_count = day_count+1 # n_months = round(day_count/6) # if n_months < 1: # n_months = 1 # this_units = n_months*area_ha*6 # print([n_months, area_ha, this_units]) # total_units = total_units + this_units # orgData = fieldObj["OrgData"] # villageName = orgData["OrgVillageName"] # if villageName != "LONI" and villageName != "ANJHI ADAMPUR": # fd = db.reference('PaidMonitoredFields').child('PMF').child(uid).child(fieldid).child('SensedDays').get() # days_arr = [] # for(p,q) in fd.items(): # days_arr.append(int(p)) # max_d = str(max(days_arr)) # db.reference('PaidMonitoredFields').child('PMF').child(uid).child(fieldid).child('SensedDays').child(max_d).delete() # print(max_d) # except: # print(traceback.format_exc()) #db.reference('PaidMonitoredFields').child('PMF').child(uid).child(fieldid).child('FieldAddress').set(fd) # try: # coordinates = fieldObj["Coordinates"] # temp_obj = {} # temp_obj["UID"] = uid # temp_obj["Points"] = coordinates # r = requests.post('https://us-central1-farmbase-b2f7e.cloudfunctions.net/getFieldAreaByBoundaryPoints', json = temp_obj) # t_obj = r.text # new_obj = json.loads(t_obj) # new_area = str(new_obj["FieldArea"]) # print(new_area) # db.reference('PaidMonitoredFields').child('PMF').child(uid).child(fieldid).child("FieldArea").set(new_area) # time.sleep(0.1) # except: # print(traceback.format_exc())