arsh1101 commited on
Commit
d0a30a7
·
verified ·
1 Parent(s): 7d3c883

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +140 -0
app.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException
2
+ from pydantic import BaseModel
3
+ import joblib
4
+ import numpy as np
5
+ from sentinelhub import SHConfig, SentinelHubRequest, BBox, CRS, DataCollection, MimeType
6
+ import cv2
7
+ import base64
8
+ from geopy.geocoders import Nominatim
9
+ from fastapi.middleware.cors import CORSMiddleware
10
+ import os
11
+
12
+ app = FastAPI()
13
+
14
+ origins = [
15
+ "http://ecoguard-522e.onrender.com",
16
+ "https://ecoguard-522e.onrender.com",
17
+ "http://localhost:3000",
18
+ "https://localhost:3000",
19
+ "https://eco-guard-ten.vercel.app",
20
+ "http://eco-guard-ten.vercel.app"
21
+ ]
22
+
23
+ app.add_middleware(
24
+ CORSMiddleware,
25
+ allow_origins=origins,
26
+ allow_credentials=True,
27
+ allow_methods=["*"],
28
+ allow_headers=["*"],
29
+ )
30
+
31
+
32
+ clf = joblib.load('./deforestation_percentage_model.joblib')
33
+
34
+
35
+ config = SHConfig()
36
+ config.sh_client_id =os.getenv('SENTINENTAL_ID')
37
+ config.sh_client_secret =os.getenv('SENTINENTAL_PASS')
38
+
39
+
40
+ class DeforestationRequest(BaseModel):
41
+ area_name: str
42
+
43
+
44
+ def geocode_area(area_name):
45
+ geolocator = Nominatim(user_agent="deforestation_app")
46
+ location = geolocator.geocode(area_name)
47
+ if location:
48
+ return location.latitude, location.longitude
49
+ else:
50
+ raise HTTPException(status_code=400, detail="Area not found")
51
+
52
+
53
+ def fetch_satellite_image(latitude, longitude):
54
+ bbox = BBox([longitude - 0.1, latitude - 0.1, longitude + 0.1, latitude + 0.1], CRS.WGS84)
55
+
56
+ evalscript = """
57
+ // Returns true color image (RGB) from Sentinel-2
58
+ return [B04, B03, B02];
59
+ """
60
+ request = SentinelHubRequest(
61
+ evalscript=evalscript,
62
+ input_data=[SentinelHubRequest.input_data(
63
+ data_collection=DataCollection.SENTINEL2_L1C,
64
+ time_interval=('2024-01-01', '2024-01-10'),
65
+ )],
66
+ responses=[SentinelHubRequest.output_response('default', MimeType.PNG)],
67
+ bbox=bbox,
68
+ size=[1024, 1024],
69
+ config=config
70
+ )
71
+
72
+ image = request.get_data()[0]
73
+ return image
74
+
75
+
76
+ def normalize_image(image_array):
77
+ min_val = np.min(image_array)
78
+ max_val = np.max(image_array)
79
+ normalized_image = (image_array - min_val) * (255.0 / (max_val - min_val))
80
+ return normalized_image.astype(np.uint8)
81
+
82
+
83
+ def extract_green_density(image_array):
84
+ hsv = cv2.cvtColor(image_array, cv2.COLOR_RGB2HSV)
85
+ green_channel = hsv[:, :, 0]
86
+ green_channel = green_channel[(green_channel >= 40) & (green_channel <= 80)]
87
+ green_density = np.mean(green_channel) if green_channel.size > 0 else 0
88
+ return green_density
89
+
90
+
91
+ def calculate_deforestation_percentage(image_array):
92
+
93
+ green_density = extract_green_density(image_array)
94
+
95
+
96
+ prediction = clf.predict(np.array([[green_density]]))[0]
97
+
98
+
99
+ return max(0, prediction)
100
+
101
+
102
+ def encode_image(image_array):
103
+ _, buffer = cv2.imencode('.png', image_array)
104
+ return base64.b64encode(buffer).decode('utf-8')
105
+
106
+
107
+ @app.post("/deforestation")
108
+ def predict_deforestation(request: DeforestationRequest):
109
+ try:
110
+
111
+ latitude, longitude = geocode_area(request.area_name)
112
+
113
+
114
+ satellite_image = fetch_satellite_image(latitude, longitude)
115
+
116
+
117
+ satellite_image = normalize_image(satellite_image)
118
+
119
+
120
+ deforestation_percentage = calculate_deforestation_percentage(satellite_image)
121
+
122
+
123
+ encoded_image = encode_image(satellite_image)
124
+
125
+
126
+ if deforestation_percentage > 20:
127
+ return {
128
+ "message": "Deforestation detected",
129
+ "deforestation_percentage": f"{deforestation_percentage:.2f}",
130
+ "satellite_image": f"data:image/png;base64,{encoded_image}"
131
+ }
132
+ else:
133
+ return {
134
+ "message": "No deforestation detected",
135
+ "deforestation_percentage": "0",
136
+ "satellite_image": f"data:image/png;base64,{encoded_image}"
137
+ }
138
+ except Exception as e:
139
+ raise HTTPException(status_code=500, detail=str(e))
140
+