Pavan2k4 commited on
Commit
83f3406
·
verified ·
1 Parent(s): 99c5651

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +102 -91
app.py CHANGED
@@ -20,15 +20,18 @@ from Utils.area import pixel_to_sqft, process_and_overlay_image
20
  from split_merge import split, merge
21
  from Utils.convert import read_pansharpened_rgb
22
 
23
- # Define directories for Hugging Face Spaces
24
- UPLOAD_DIR = "/tmp/uploaded_images/"
25
- MASK_DIR = "/tmp/generated_masks/"
26
- patches_folder = "/tmp/Patches/"
27
- pred_patches = "/tmp/Patch_pred/"
28
- CSV_LOG_PATH = "outputs/image_log.csv"
 
 
 
29
 
30
  # Create directories
31
- for directory in [UPLOAD_DIR, MASK_DIR, patches_folder, pred_patches, "outputs"]:
32
  os.makedirs(directory, exist_ok=True)
33
 
34
  # Load model
@@ -81,89 +84,97 @@ def upload_page():
81
  image = st.file_uploader('Choose a satellite image', type=['jpg', 'png', 'jpeg', 'tiff', 'tif'])
82
 
83
  if image is not None and not st.session_state.file_uploaded:
84
- bytes_data = image.getvalue()
85
-
86
- timestamp = int(time.time())
87
- original_filename = image.name
88
- file_extension = os.path.splitext(original_filename)[1].lower()
89
-
90
- if file_extension in ['.tiff', '.tif']:
91
- filename = f"image_{timestamp}.tif"
92
- converted_filename = f"image_{timestamp}_converted.png"
93
- else:
94
- filename = f"image_{timestamp}.png"
95
- converted_filename = filename
96
-
97
- filepath = os.path.join(UPLOAD_DIR, filename)
98
- converted_filepath = os.path.join(UPLOAD_DIR, converted_filename)
99
-
100
- with open(filepath, "wb") as f:
101
- f.write(bytes_data)
102
-
103
- # Check if the uploaded file is a GeoTIFF
104
- if file_extension in ['.tiff', '.tif']:
105
- st.info('Processing GeoTIFF image...')
106
- rgb_image = read_pansharpened_rgb(filepath)
107
- cv2.imwrite(converted_filepath, cv2.cvtColor(rgb_image, cv2.COLOR_RGB2BGR))
108
- st.success(f'GeoTIFF converted to 8-bit image and saved as {converted_filename}')
109
- img = Image.open(converted_filepath)
110
- else:
111
- img = Image.open(filepath)
112
-
113
- st.image(img, caption='Uploaded Image', use_column_width=True)
114
- st.success(f'Image saved as {converted_filename}')
115
-
116
- # Store the full path of the converted image
117
- st.session_state.filename = converted_filename
118
-
119
- # Convert image to numpy array
120
- img_array = np.array(img)
121
-
122
- # Check if image shape is more than 650x650
123
- if img_array.shape[0] > 650 or img_array.shape[1] > 650:
124
- # Split image into patches
125
- split(converted_filepath, patch_size=512)
126
-
127
- # Display buffer while analyzing
128
- with st.spinner('Analyzing...'):
129
- # Predict on each patch
130
- for patch_filename in os.listdir(patches_folder):
131
- if patch_filename.endswith(".png"):
132
- patch_path = os.path.join(patches_folder, patch_filename)
133
- patch_img = Image.open(patch_path)
134
- patch_tr_img = transforms(patch_img)
135
- prediction = predict(patch_tr_img)
136
- mask = (prediction > 0.5).astype(np.uint8) * 255
137
- mask_filename = f"mask_{patch_filename}"
138
- mask_filepath = os.path.join(pred_patches, mask_filename)
139
- Image.fromarray(mask).save(mask_filepath)
140
-
141
- # Merge predicted patches
142
- merged_mask_filename = f"mask_{timestamp}.png"
143
- merged_mask_path = os.path.join(MASK_DIR, merged_mask_filename)
144
- merge(pred_patches, merged_mask_path, img_array.shape)
145
-
146
- # Save merged mask
147
- st.session_state.mask_filename = merged_mask_filename
148
-
149
- # Clean up temporary patch files
150
- st.info('Cleaning up temporary files...')
151
- shutil.rmtree(patches_folder)
152
- shutil.rmtree(pred_patches)
153
- os.makedirs(patches_folder) # Recreate empty folders
154
- os.makedirs(pred_patches)
155
- st.success('Temporary files cleaned up')
156
- else:
157
- # Predict on whole image
158
- st.session_state.tr_img = transforms(img)
159
- prediction = predict(st.session_state.tr_img)
160
- mask = (prediction > 0.5).astype(np.uint8) * 255
161
- mask_filename = f"mask_{timestamp}.png"
162
- mask_filepath = os.path.join(MASK_DIR, mask_filename)
163
- Image.fromarray(mask).save(mask_filepath)
164
- st.session_state.mask_filename = mask_filename
 
 
 
165
 
166
- st.session_state.file_uploaded = True
 
 
 
 
 
167
 
168
  if st.session_state.file_uploaded and st.button('View result'):
169
  if st.session_state.filename is None:
@@ -226,8 +237,8 @@ def result_page():
226
  st.error("Image or mask file not found for overlay.")
227
 
228
  if st.button('Back to Upload'):
229
- shutil.rmtree(patches_folder)
230
- shutil.rmtree(pred_patches)
231
  st.session_state.page = 'upload'
232
  st.session_state.file_uploaded = False
233
  st.session_state.filename = None
 
20
  from split_merge import split, merge
21
  from Utils.convert import read_pansharpened_rgb
22
 
23
+ # Define base directory for Hugging Face Spaces
24
+ BASE_DIR = "/home/user"
25
+
26
+ # Define subdirectories
27
+ UPLOAD_DIR = os.path.join(BASE_DIR, "uploaded_images")
28
+ MASK_DIR = os.path.join(BASE_DIR, "generated_masks")
29
+ PATCHES_DIR = os.path.join(BASE_DIR, "patches")
30
+ PRED_PATCHES_DIR = os.path.join(BASE_DIR, "pred_patches")
31
+ CSV_LOG_PATH = os.path.join(BASE_DIR, "image_log.csv")
32
 
33
  # Create directories
34
+ for directory in [UPLOAD_DIR, MASK_DIR, PATCHES_DIR, PRED_PATCHES_DIR]:
35
  os.makedirs(directory, exist_ok=True)
36
 
37
  # Load model
 
84
  image = st.file_uploader('Choose a satellite image', type=['jpg', 'png', 'jpeg', 'tiff', 'tif'])
85
 
86
  if image is not None and not st.session_state.file_uploaded:
87
+ try:
88
+ bytes_data = image.getvalue()
89
+
90
+ timestamp = int(time.time())
91
+ original_filename = image.name
92
+ file_extension = os.path.splitext(original_filename)[1].lower()
93
+
94
+ if file_extension in ['.tiff', '.tif']:
95
+ filename = f"image_{timestamp}.tif"
96
+ converted_filename = f"image_{timestamp}_converted.png"
97
+ else:
98
+ filename = f"image_{timestamp}.png"
99
+ converted_filename = filename
100
+
101
+ filepath = os.path.join(UPLOAD_DIR, filename)
102
+ converted_filepath = os.path.join(UPLOAD_DIR, converted_filename)
103
+
104
+ with open(filepath, "wb") as f:
105
+ f.write(bytes_data)
106
+
107
+ st.success(f"Image saved to {filepath}")
108
+
109
+ # Check if the uploaded file is a GeoTIFF
110
+ if file_extension in ['.tiff', '.tif']:
111
+ st.info('Processing GeoTIFF image...')
112
+ rgb_image = read_pansharpened_rgb(filepath)
113
+ cv2.imwrite(converted_filepath, cv2.cvtColor(rgb_image, cv2.COLOR_RGB2BGR))
114
+ st.success(f'GeoTIFF converted to 8-bit image and saved as {converted_filename}')
115
+ img = Image.open(converted_filepath)
116
+ else:
117
+ img = Image.open(filepath)
118
+
119
+ st.image(img, caption='Uploaded Image', use_column_width=True)
120
+ st.success(f'Image processed and saved as {converted_filename}')
121
+
122
+ # Store the full path of the converted image
123
+ st.session_state.filename = converted_filename
124
+
125
+ # Convert image to numpy array
126
+ img_array = np.array(img)
127
+
128
+ # Check if image shape is more than 650x650
129
+ if img_array.shape[0] > 650 or img_array.shape[1] > 650:
130
+ # Split image into patches
131
+ split(converted_filepath, patch_size=512)
132
+
133
+ # Display buffer while analyzing
134
+ with st.spinner('Analyzing...'):
135
+ # Predict on each patch
136
+ for patch_filename in os.listdir(PATCHES_DIR):
137
+ if patch_filename.endswith(".png"):
138
+ patch_path = os.path.join(PATCHES_DIR, patch_filename)
139
+ patch_img = Image.open(patch_path)
140
+ patch_tr_img = transforms(patch_img)
141
+ prediction = predict(patch_tr_img)
142
+ mask = (prediction > 0.5).astype(np.uint8) * 255
143
+ mask_filename = f"mask_{patch_filename}"
144
+ mask_filepath = os.path.join(PRED_PATCHES_DIR, mask_filename)
145
+ Image.fromarray(mask).save(mask_filepath)
146
+
147
+ # Merge predicted patches
148
+ merged_mask_filename = f"mask_{timestamp}.png"
149
+ merged_mask_path = os.path.join(MASK_DIR, merged_mask_filename)
150
+ merge(PRED_PATCHES_DIR, merged_mask_path, img_array.shape)
151
+
152
+ # Save merged mask
153
+ st.session_state.mask_filename = merged_mask_filename
154
+
155
+ # Clean up temporary patch files
156
+ st.info('Cleaning up temporary files...')
157
+ shutil.rmtree(PATCHES_DIR)
158
+ shutil.rmtree(PRED_PATCHES_DIR)
159
+ os.makedirs(PATCHES_DIR) # Recreate empty folders
160
+ os.makedirs(PRED_PATCHES_DIR)
161
+ st.success('Temporary files cleaned up')
162
+ else:
163
+ # Predict on whole image
164
+ st.session_state.tr_img = transforms(img)
165
+ prediction = predict(st.session_state.tr_img)
166
+ mask = (prediction > 0.5).astype(np.uint8) * 255
167
+ mask_filename = f"mask_{timestamp}.png"
168
+ mask_filepath = os.path.join(MASK_DIR, mask_filename)
169
+ Image.fromarray(mask).save(mask_filepath)
170
+ st.session_state.mask_filename = mask_filename
171
 
172
+ st.session_state.file_uploaded = True
173
+
174
+ except Exception as e:
175
+ st.error(f"An error occurred: {str(e)}")
176
+ st.error("Please check the logs for more details.")
177
+ print(f"Error in upload_page: {str(e)}") # This will appear in the Streamlit logs
178
 
179
  if st.session_state.file_uploaded and st.button('View result'):
180
  if st.session_state.filename is None:
 
237
  st.error("Image or mask file not found for overlay.")
238
 
239
  if st.button('Back to Upload'):
240
+ shutil.rmtree(PATCHES_DIR)
241
+ shutil.rmtree(PRED_PATCHES_DIR)
242
  st.session_state.page = 'upload'
243
  st.session_state.file_uploaded = False
244
  st.session_state.filename = None