from itertools import zip_longest from tempfile import tempdir import firebase_admin from firebase_admin import credentials from firebase_admin import db from find_s1_image import find_img_value import pandas as pd from sklearn.metrics import classification_report, confusion_matrix, accuracy_score import statsmodels.api as sm import seaborn as sns sns.set() from zipfile import ZipFile 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 find_study_area_values import find_study_area_values from find_study_area_values3 import find_study_area_values3 from make_area_estimate_image import make_area_estimate_image from make_egypt_estimate_image import make_egypt_estimate_image from sentinelhub import WebFeatureService, BBox, CRS, MimeType, CRS, BBox, WmsRequest,DataCollection import traceback from firebase_admin import firestore from PIL import Image import numpy as np from google.cloud import storage import os from firebase_admin import db from get_mask import get_mask import cv2 import scipy.ndimage from google.oauth2 import service_account import datetime from datetime import date from segment_sample import get_main_segment import requests import traceback from ftplib import FTP import paramiko import pysftp storage_client = storage.Client.from_service_account_json("servicekey.json"); bucket_name = 'farmbase-b2f7e.appspot.com' cred = service_account.Credentials.from_service_account_file('servicekey.json') #cred = credentials.Certificate('servicekey.json') bucket = storage_client.bucket(bucket_name) try: firebase_admin.initialize_app(credentials.Certificate('servicekey.json'), {'databaseURL': 'https://farmbase-b2f7e-31c0c.firebaseio.com/'}) except: print('fire running') db_firestore = firestore.client() from sentinelhub import SHConfig, MimeType, BBox, SentinelHubRequest, SentinelHubDownloadClient, DataCollection, geo_utils def upload_image(): def detect_deforestation(bbox, time_interval, output_dir, config=None): if config is None: # Configure SentinelHub with your credentials config = SHConfig() config.sh_client_id = '3e9277b3-aa11-4f98-a160-3bf006130cc7' config.sh_client_secret = 'CY>imU7J,97EniGj5jyRtz:l13@XL2*gfY+pvqRw' # Define the SentinelHub request parameters evalscript = """ // Import Sentinel-2 bands return [B02, B03, B04, B08]; """ request = SentinelHubRequest( evalscript=evalscript, input_data=[ SentinelHubRequest.input_data( data_collection=DataCollection.SENTINEL2_L1C, time_interval=time_interval, maxcc=0.2 ) ], responses=[ SentinelHubRequest.output_response('default', MimeType.TIFF), ], bbox=bbox, config=config, ) # Fetch Sentinel imagery sentinel_data = request.get_data() sentinel_data = np.array(sentinel_data[0]) # Calculate the NDVI (Normalized Difference Vegetation Index) nir = sentinel_data[:, :, 3] red = sentinel_data[:, :, 2] ndvi = (nir - red) / (nir + red) # Apply a threshold to identify deforested areas threshold = 0.2 deforestation_mask = (ndvi < threshold) # Create a color-coded PNG image deforestation_image = np.zeros_like(sentinel_data) deforestation_image[deforestation_mask] = [0, 0, 255, 255] # Red color for deforestation # Save the PNG image png_path = f"{output_dir}/deforestation.png" cv2.imwrite(png_path, deforestation_image) return png_path#, geojson_path # Example usage: def main(): #storage_client = storage.Client() # req_obj = {} # req_obj["IsReportRequested"] = 1 # db_firestore.collection('ReportZipRequests').document('XSzwRsmzu4OeCm8UvllGn7xsnOk1').set(req_obj) zip_requests_obj = db_firestore.collection(u'SegmentRequests').where('Processed','==',0).get() for temp_d in zip_requests_obj: time_stamp = temp_d.id time_stamp = str(time_stamp) print(temp_d.id) print(temp_d.to_dict()) temp_main_obj = temp_d.to_dict() uid = temp_main_obj["UID"] coords = temp_main_obj["Point"] new_coords = coords.split(",") lat = float(new_coords[0]) lng = float(new_coords[1]) found_coordinates = get_main_segment(lat,lng,uid, "sample") temp_main_obj["Processed"] = 1 temp_main_obj["Points"] = str(found_coordinates) db_firestore.collection(u'SegmentRequests').document(time_stamp).set(temp_main_obj) #upload_file_ftp(hostname, username, password, local_file_path, remote_directory) #upload_file_ftp(hostname, username, password, local_file_path, remote_directory) i = 0 while i == 0: process_segments() time.sleep(60) longitude_min, latitude_min, longitude_max, latitude_max =-50.768464422847735,-7.073172070815588,-50.33313117089461,-6.653230308928273 bbox = BBox([longitude_min, latitude_min, longitude_max, latitude_max], crs="EPSG:4326") time_interval = ('2022-01-01', '2023-07-31') output_directory = 'SFTP' result = detect_deforestation(bbox, time_interval, output_directory) print(result)