Pavan2k4 commited on
Commit
39c353e
·
verified ·
1 Parent(s): 74b53e1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +4 -70
app.py CHANGED
@@ -9,7 +9,7 @@ import cv2
9
  import numpy as np
10
  from PIL import Image
11
  import torch
12
- from huggingface_hub import hf_hub_download
13
 
14
  sys.path.append('Utils')
15
  sys.path.append('model')
@@ -18,17 +18,7 @@ from model.transform import transforms
18
  from model.unet import UNET
19
  from Utils.area import pixel_to_sqft, process_and_overlay_image
20
  from Utils.convert import read_pansharpened_rgb
21
- from huggingface_hub import HfApi, login
22
-
23
- HF_TOKEN = os.environ.get("HF_TOKEN")
24
- if not HF_TOKEN:
25
- raise ValueError("HF_TOKEN environment variable is not set")
26
-
27
- login(token=HF_TOKEN)
28
- hf_api = HfApi()
29
 
30
- REPO_ID = "Pavan2k4/Building_area"
31
- REPO_TYPE = "space"
32
 
33
  @st.cache_resource
34
  def load_model():
@@ -71,24 +61,7 @@ def refine_mask(mask, blur_kernel=5, threshold_value=127, morph_kernel_size=3, m
71
 
72
 
73
  # save to dir func
74
- def save_to_hf_repo(local_path, repo_path):
75
- if not os.path.isfile(local_path):
76
- st.error(f"File not found at {local_path}")
77
- return
78
-
79
- try:
80
- with open(local_path, 'rb') as f:
81
- hf_api.upload_file(
82
- path_or_fileobj=f,
83
- path_in_repo=repo_path,
84
- repo_id=REPO_ID,
85
- repo_type=REPO_TYPE,
86
- token=HF_TOKEN
87
- )
88
- st.success(f"File uploaded successfully to {repo_path}")
89
- except Exception as e:
90
- st.error(f"Error during upload: {str(e)}")
91
- st.exception(e)
92
 
93
 
94
 
@@ -202,13 +175,12 @@ def log_image_details(image_id, image_filename, mask_filename):
202
 
203
  writer.writerow([sno, date, time, image_id, image_filename, mask_filename])
204
 
 
205
  def upload_page():
206
  if 'file_uploaded' not in st.session_state:
207
  st.session_state.file_uploaded = False
208
-
209
  if 'filename' not in st.session_state:
210
  st.session_state.filename = None
211
-
212
  if 'mask_filename' not in st.session_state:
213
  st.session_state.mask_filename = None
214
 
@@ -217,7 +189,6 @@ def upload_page():
217
  if image is not None and not st.session_state.file_uploaded:
218
  try:
219
  bytes_data = image.getvalue()
220
-
221
  timestamp = int(time.time())
222
  original_filename = image.name
223
  file_extension = os.path.splitext(original_filename)[1].lower()
@@ -235,7 +206,6 @@ def upload_page():
235
  with open(filepath, "wb") as f:
236
  f.write(bytes_data)
237
 
238
- # Check if the uploaded file is a GeoTIFF
239
  if file_extension in ['.tiff', '.tif']:
240
  st.info('Processing GeoTIFF image...')
241
  rgb_image = read_pansharpened_rgb(filepath)
@@ -256,13 +226,10 @@ def upload_page():
256
  st.image(img, caption='Uploaded Image', use_column_width=True)
257
  st.success(f'Image processed and saved as {converted_filename}')
258
 
259
- # Store the full path of the converted image
260
  st.session_state.filename = converted_filename
261
 
262
- # Convert image to numpy array
263
  img_array = np.array(img)
264
 
265
- # Check if image shape is more than 650x650
266
  if img_array.shape[0] > 650 or img_array.shape[1] > 650:
267
  st.info('Large image detected. Using patch-based processing.')
268
  with st.spinner('Analyzing large image...'):
@@ -274,45 +241,12 @@ def upload_page():
274
  prediction = predict(img_transformed)
275
  full_mask = (prediction > 0.5).astype(np.uint8) * 255
276
 
277
- # Save the full mask
278
  full_mask = refine_mask(full_mask)
279
  mask_filename = f"mask_{timestamp}.png"
280
  mask_filepath = os.path.join(MASK_DIR, mask_filename)
281
  cv2.imwrite(mask_filepath, full_mask)
282
  st.session_state.mask_filename = mask_filename
283
 
284
- # Upload to Hugging Face repo
285
- try:
286
- with open(converted_filepath, 'rb') as f:
287
- image_repo_path = f"images/{converted_filename}"
288
- hf_api.upload_file(
289
- path_or_fileobj=f,
290
- path_in_repo=image_repo_path,
291
- repo_id=REPO_ID,
292
- repo_type=REPO_TYPE,
293
- token=HF_TOKEN
294
- )
295
- st.success(f"Image uploaded successfully to {image_repo_path}")
296
- except Exception as e:
297
- st.error(f"Error saving image to Hugging Face repo: {str(e)}")
298
- st.exception(e)
299
-
300
- try:
301
- with open(mask_filepath, 'rb') as f:
302
- mask_repo_path = f"masks/{mask_filename}"
303
- hf_api.upload_file(
304
- path_or_fileobj=f,
305
- path_in_repo=mask_repo_path,
306
- repo_id=REPO_ID,
307
- repo_type=REPO_TYPE,
308
- token=HF_TOKEN
309
- )
310
- st.success(f"Mask uploaded successfully to {mask_repo_path}")
311
- except Exception as e:
312
- st.error(f"Error saving mask to Hugging Face repo: {str(e)}")
313
- st.exception(e)
314
-
315
- # Log image details
316
  log_image_details(timestamp, converted_filename, mask_filename)
317
 
318
  st.session_state.file_uploaded = True
@@ -321,7 +255,7 @@ def upload_page():
321
  except Exception as e:
322
  st.error(f"An error occurred: {str(e)}")
323
  st.error("Please check the logs for more details.")
324
- print(f"Error in upload_page: {str(e)}") # This will appear in the Streamlit logs
325
 
326
  if st.session_state.file_uploaded and st.button('View result'):
327
  if st.session_state.filename is None:
 
9
  import numpy as np
10
  from PIL import Image
11
  import torch
12
+
13
 
14
  sys.path.append('Utils')
15
  sys.path.append('model')
 
18
  from model.unet import UNET
19
  from Utils.area import pixel_to_sqft, process_and_overlay_image
20
  from Utils.convert import read_pansharpened_rgb
 
 
 
 
 
 
 
 
21
 
 
 
22
 
23
  @st.cache_resource
24
  def load_model():
 
61
 
62
 
63
  # save to dir func
64
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
 
66
 
67
 
 
175
 
176
  writer.writerow([sno, date, time, image_id, image_filename, mask_filename])
177
 
178
+
179
  def upload_page():
180
  if 'file_uploaded' not in st.session_state:
181
  st.session_state.file_uploaded = False
 
182
  if 'filename' not in st.session_state:
183
  st.session_state.filename = None
 
184
  if 'mask_filename' not in st.session_state:
185
  st.session_state.mask_filename = None
186
 
 
189
  if image is not None and not st.session_state.file_uploaded:
190
  try:
191
  bytes_data = image.getvalue()
 
192
  timestamp = int(time.time())
193
  original_filename = image.name
194
  file_extension = os.path.splitext(original_filename)[1].lower()
 
206
  with open(filepath, "wb") as f:
207
  f.write(bytes_data)
208
 
 
209
  if file_extension in ['.tiff', '.tif']:
210
  st.info('Processing GeoTIFF image...')
211
  rgb_image = read_pansharpened_rgb(filepath)
 
226
  st.image(img, caption='Uploaded Image', use_column_width=True)
227
  st.success(f'Image processed and saved as {converted_filename}')
228
 
 
229
  st.session_state.filename = converted_filename
230
 
 
231
  img_array = np.array(img)
232
 
 
233
  if img_array.shape[0] > 650 or img_array.shape[1] > 650:
234
  st.info('Large image detected. Using patch-based processing.')
235
  with st.spinner('Analyzing large image...'):
 
241
  prediction = predict(img_transformed)
242
  full_mask = (prediction > 0.5).astype(np.uint8) * 255
243
 
 
244
  full_mask = refine_mask(full_mask)
245
  mask_filename = f"mask_{timestamp}.png"
246
  mask_filepath = os.path.join(MASK_DIR, mask_filename)
247
  cv2.imwrite(mask_filepath, full_mask)
248
  st.session_state.mask_filename = mask_filename
249
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
250
  log_image_details(timestamp, converted_filename, mask_filename)
251
 
252
  st.session_state.file_uploaded = True
 
255
  except Exception as e:
256
  st.error(f"An error occurred: {str(e)}")
257
  st.error("Please check the logs for more details.")
258
+ print(f"Error in upload_page: {str(e)}")
259
 
260
  if st.session_state.file_uploaded and st.button('View result'):
261
  if st.session_state.filename is None: