didi25abdillah commited on
Commit
4d22646
·
verified ·
1 Parent(s): e5590a6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -37
app.py CHANGED
@@ -7,28 +7,20 @@ import pickle
7
  import os
8
  import folium
9
  from folium import Rectangle
 
10
 
11
- # Disable GPU (optional)
12
- os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
13
-
14
- # === Load model ===
15
  model = tf.keras.models.load_model("model_resnet50_jakarta_100epoch_240p_1088Grid_320train_80val_squared.h5")
16
-
17
- # === Load label encoder ===
18
  with open("label_encoder_resnet50_jakarta_100epoch_240p_1088Grid_320train_80val_squared.pkl", "rb") as f:
19
  label_encoder = pickle.load(f)
20
-
21
- # === Load class names ===
22
  class_names = label_encoder.classes_.tolist()
23
 
24
- # === Load BBOX Data ===
25
  bbox_df = pd.read_csv("bbox_grid.csv")
26
-
27
  bbox_dict = {row['grid_id']: (row['min_lat'], row['min_lon'], row['max_lat'], row['max_lon']) for _, row in bbox_df.iterrows()}
28
 
29
  IMG_SIZE = (240, 240)
30
 
31
- # === Fungsi crop square ===
32
  def center_crop_square(img):
33
  h, w = img.shape[:2]
34
  min_dim = min(h, w)
@@ -36,7 +28,6 @@ def center_crop_square(img):
36
  start_y = h // 2 - min_dim // 2
37
  return img[start_y:start_y+min_dim, start_x:start_x+min_dim]
38
 
39
- # === Fungsi prediksi + generate peta ===
40
  def predict_and_map(image):
41
  image_cropped = center_crop_square(image)
42
  image_resized = cv2.resize(image_cropped, IMG_SIZE)
@@ -48,47 +39,42 @@ def predict_and_map(image):
48
  label = class_names[class_index]
49
  confidence = pred_probs[class_index]
50
 
51
- # Ambil BBOX
52
- if label in bbox_dict:
53
- min_lat, min_lon, max_lat, max_lon = bbox_dict[label]
54
- else:
55
- return "Grid tidak ditemukan!", None
56
 
57
- # Buat peta
58
  center_lat = (min_lat + max_lat) / 2
59
  center_lon = (min_lon + max_lon) / 2
60
- m = folium.Map(location=[center_lat, center_lon], zoom_start=15)
61
 
62
- Rectangle(
63
- bounds=[[min_lat, min_lon], [max_lat, max_lon]],
64
- color="blue",
65
- fill=True,
66
- fill_opacity=0.4,
67
- ).add_to(m)
68
 
69
- # Render HTML folium map
70
- map_html = m.get_root().render()
 
71
 
72
- # Bungkus iframe
73
  iframe_html = f"""
74
- <iframe srcdoc="{map_html.replace('"', '&quot;')}"
75
  style="width: 100%; height: 60vh; border: none;">
76
  </iframe>
77
  """
78
 
79
- return f"Prediksi Grid: {label}\nConfidence: {confidence:.2%}", iframe_html
80
 
81
- # === Gradio UI ===
82
- with gr.Blocks() as interface:
83
  with gr.Row():
84
  with gr.Column(scale=1):
85
  image_input = gr.Image(type="numpy", label="Upload Gambar Street View")
86
  with gr.Column(scale=2):
87
  text_output = gr.Textbox(label="Hasil Prediksi Grid", interactive=False)
88
- map_output = gr.HTML(label="Peta Grid Prediksi")
 
89
 
90
- # Event handling
91
- image_input.change(fn=predict_and_map, inputs=image_input, outputs=[text_output, map_output])
92
 
93
- # Launch interface
94
- interface.launch()
 
7
  import os
8
  import folium
9
  from folium import Rectangle
10
+ import uuid
11
 
12
+ # Load model dan label encoder
 
 
 
13
  model = tf.keras.models.load_model("model_resnet50_jakarta_100epoch_240p_1088Grid_320train_80val_squared.h5")
 
 
14
  with open("label_encoder_resnet50_jakarta_100epoch_240p_1088Grid_320train_80val_squared.pkl", "rb") as f:
15
  label_encoder = pickle.load(f)
 
 
16
  class_names = label_encoder.classes_.tolist()
17
 
18
+ # Load bounding box
19
  bbox_df = pd.read_csv("bbox_grid.csv")
 
20
  bbox_dict = {row['grid_id']: (row['min_lat'], row['min_lon'], row['max_lat'], row['max_lon']) for _, row in bbox_df.iterrows()}
21
 
22
  IMG_SIZE = (240, 240)
23
 
 
24
  def center_crop_square(img):
25
  h, w = img.shape[:2]
26
  min_dim = min(h, w)
 
28
  start_y = h // 2 - min_dim // 2
29
  return img[start_y:start_y+min_dim, start_x:start_x+min_dim]
30
 
 
31
  def predict_and_map(image):
32
  image_cropped = center_crop_square(image)
33
  image_resized = cv2.resize(image_cropped, IMG_SIZE)
 
39
  label = class_names[class_index]
40
  confidence = pred_probs[class_index]
41
 
42
+ if label not in bbox_dict:
43
+ return "Grid tidak ditemukan!", None, None
 
 
 
44
 
45
+ min_lat, min_lon, max_lat, max_lon = bbox_dict[label]
46
  center_lat = (min_lat + max_lat) / 2
47
  center_lon = (min_lon + max_lon) / 2
 
48
 
49
+ # Buat peta
50
+ m = folium.Map(location=[center_lat, center_lon], zoom_start=15)
51
+ Rectangle([[min_lat, min_lon], [max_lat, max_lon]],
52
+ color="blue", fill=True, fill_opacity=0.4).add_to(m)
 
 
53
 
54
+ # Simpan ke /tmp agar bisa diunduh di Spaces
55
+ filename = f"/tmp/map_{uuid.uuid4().hex}.html"
56
+ m.save(filename)
57
 
58
+ # Buat iframe preview
59
  iframe_html = f"""
60
+ <iframe srcdoc="{m.get_root().render().replace('"', '&quot;')}"
61
  style="width: 100%; height: 60vh; border: none;">
62
  </iframe>
63
  """
64
 
65
+ return f"Prediksi Grid: {label}\nConfidence: {confidence:.2%}", iframe_html, filename
66
 
67
+ # UI Gradio
68
+ with gr.Blocks() as demo:
69
  with gr.Row():
70
  with gr.Column(scale=1):
71
  image_input = gr.Image(type="numpy", label="Upload Gambar Street View")
72
  with gr.Column(scale=2):
73
  text_output = gr.Textbox(label="Hasil Prediksi Grid", interactive=False)
74
+ map_output = gr.HTML(label="Peta Grid")
75
+ download_link = gr.File(label="Unduh Peta HTML")
76
 
77
+ image_input.change(fn=predict_and_map, inputs=image_input,
78
+ outputs=[text_output, map_output, download_link])
79
 
80
+ demo.launch()