Gordon Li commited on
Commit
0f8b245
·
1 Parent(s): 46e8dfb

Add loading of image for traffic analysis

Browse files
Files changed (4) hide show
  1. AirbnbMapVisualiser.py +1 -1
  2. TrafficSpot.py +77 -10
  3. app.py +1 -1
  4. requirements.txt +2 -1
AirbnbMapVisualiser.py CHANGED
@@ -27,7 +27,7 @@ class AirbnbMapVisualiser:
27
  try:
28
  self.neighborhoods = self.get_all_neighborhoods()
29
  self.cached_listings = {}
30
- self.cached_listings["Sha Tin"] = self.get_neighborhood_listings("Sha Tin")
31
  except Exception as e:
32
  print(f"Initialization error: {str(e)}")
33
  self.neighborhoods = []
 
27
  try:
28
  self.neighborhoods = self.get_all_neighborhoods()
29
  self.cached_listings = {}
30
+ self.cached_listings["Southern"] = self.get_neighborhood_listings("Southern")
31
  except Exception as e:
32
  print(f"Initialization error: {str(e)}")
33
  self.neighborhoods = []
TrafficSpot.py CHANGED
@@ -1,23 +1,62 @@
1
- import oracledb
 
2
  from html import escape
3
  import folium
 
 
 
 
4
 
5
  class TrafficSpot:
6
- def __init__(self, key, latitude, longitude):
7
  self.key = key
8
  self.latitude = float(latitude) if latitude is not None else None
9
  self.longitude = float(longitude) if longitude is not None else None
 
10
 
11
  def is_valid(self):
12
  return self.latitude is not None and self.longitude is not None
13
 
14
  def create_popup_content(self):
15
- return f"""
16
  <div style='min-width: 150px; padding: 10px;'>
17
- <p style='margin: 5px 0;'><strong>Traffic Camera ID:</strong> {escape(str(self.key))}</p>
18
- </div>
19
  """
20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  def add_to_map(self, folium_map):
22
  if self.is_valid():
23
  folium.Marker(
@@ -35,21 +74,49 @@ class TrafficSpotManager:
35
 
36
  def load_traffic_spots(self):
37
  try:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  with oracledb.connect(**self.connection_params) as conn:
39
  cursor = conn.cursor()
40
- cursor.execute("""
41
  SELECT KEY, LATITUDE, LONGITUDE
42
  FROM TD_TRAFFIC_CAMERA_LOCATION
43
- WHERE LATITUDE IS NOT NULL
 
44
  AND LONGITUDE IS NOT NULL
45
- """)
 
 
46
  spots = cursor.fetchall()
 
47
  self.traffic_spots = [
48
- TrafficSpot(spot[0], spot[1], spot[2])
 
 
 
 
 
49
  for spot in spots
50
  ]
 
 
 
 
51
  except Exception as e:
52
- print(f"Database error loading traffic spots: {str(e)}")
53
  self.traffic_spots = []
54
 
55
  def add_spots_to_map(self, folium_map):
 
1
+ import logging
2
+ from datetime import datetime
3
  from html import escape
4
  import folium
5
+ import oracledb
6
+ from datasets import load_dataset
7
+ import base64 # Add this import for base64 encoding
8
+
9
 
10
  class TrafficSpot:
11
+ def __init__(self, key, latitude, longitude, dataset_rows=None):
12
  self.key = key
13
  self.latitude = float(latitude) if latitude is not None else None
14
  self.longitude = float(longitude) if longitude is not None else None
15
+ self.dataset_rows = dataset_rows or [] # List of matching dataset rows (up to 5)
16
 
17
  def is_valid(self):
18
  return self.latitude is not None and self.longitude is not None
19
 
20
  def create_popup_content(self):
21
+ html = f"""
22
  <div style='min-width: 150px; padding: 10px;'>
23
+ <p style='margin: 5px 0;'><strong>Location ID:</strong> {escape(str(self.key))}</p>
 
24
  """
25
 
26
+ if self.dataset_rows:
27
+ html += "<h4>Recent Records:</h4>"
28
+ for row in self.dataset_rows:
29
+ # Convert binary processed_image to base64
30
+ image_data = row.get('processed_image')
31
+ image_html = ""
32
+ if image_data:
33
+ try:
34
+ # Encode binary data to base64
35
+ base64_encoded = base64.b64encode(image_data).decode('utf-8')
36
+ # Create img tag with base64 data
37
+ image_html = f"""
38
+ <img src='data:image/jpeg;base64,{base64_encoded}'
39
+ style='max-width: 100px; max-height: 100px; margin: 5px 0;'
40
+ alt='Processed Image'>
41
+ """
42
+ except Exception as e:
43
+ logging.error(f"Error encoding image for {self.key}: {str(e)}")
44
+ image_html = "<p>Image load failed</p>"
45
+
46
+ html += f"""
47
+ <div style='border-top: 1px solid #ccc; padding: 5px 0;'>
48
+ <p style='margin: 2px 0;'><strong>Time:</strong> {escape(str(row['capture_time']))}</p>
49
+ <p style='margin: 2px 0;'><strong>Vehicles:</strong> {escape(str(row['vehicle_count']))}</p>
50
+ <p style='margin: 2px 0;'><strong>Confidence:</strong> {escape(str(row['confidence_score']))}</p>
51
+ {image_html}
52
+ </div>
53
+ """
54
+ else:
55
+ html += "<p>No recent records available</p>"
56
+
57
+ html += "</div>"
58
+ return html
59
+
60
  def add_to_map(self, folium_map):
61
  if self.is_valid():
62
  folium.Marker(
 
74
 
75
  def load_traffic_spots(self):
76
  try:
77
+ dataset = load_dataset("slliac/traffic-analysis", split="train")
78
+ dataset_list = [row for row in dataset]
79
+ dataset_list.sort(key=lambda x: x['capture_time'], reverse=True)
80
+
81
+ dataset_dict = {}
82
+ for row in dataset_list:
83
+ loc_id = row['location_id']
84
+ if loc_id not in dataset_dict:
85
+ dataset_dict[loc_id] = []
86
+ if len(dataset_dict[loc_id]) < 2:
87
+ dataset_dict[loc_id].append(row)
88
+
89
+ unique_locations = list(dataset_dict.keys())
90
+ location_ids = tuple(unique_locations) if unique_locations else ('',)
91
+
92
  with oracledb.connect(**self.connection_params) as conn:
93
  cursor = conn.cursor()
94
+ query = """
95
  SELECT KEY, LATITUDE, LONGITUDE
96
  FROM TD_TRAFFIC_CAMERA_LOCATION
97
+ WHERE KEY IN ({})
98
+ AND LATITUDE IS NOT NULL
99
  AND LONGITUDE IS NOT NULL
100
+ """.format(','.join([':' + str(i + 1) for i in range(len(location_ids))]))
101
+
102
+ cursor.execute(query, location_ids)
103
  spots = cursor.fetchall()
104
+
105
  self.traffic_spots = [
106
+ TrafficSpot(
107
+ spot[0],
108
+ spot[1],
109
+ spot[2],
110
+ dataset_dict.get(spot[0])
111
+ )
112
  for spot in spots
113
  ]
114
+
115
+ conn.commit()
116
+ logging.info(f"Loaded {len(self.traffic_spots)} traffic spots")
117
+
118
  except Exception as e:
119
+ logging.error(f"Error loading traffic spots: {str(e)}")
120
  self.traffic_spots = []
121
 
122
  def add_spots_to_map(self, folium_map):
app.py CHANGED
@@ -129,7 +129,7 @@ def main():
129
  neighborhood = st.selectbox(
130
  "Select Neighborhood",
131
  options=visualizer.neighborhoods,
132
- index=visualizer.neighborhoods.index("Sha Tin") if "Sha Tin" in visualizer.neighborhoods else 0
133
  )
134
  show_traffic = st.checkbox("Show Traffic Cameras", value=True)
135
 
 
129
  neighborhood = st.selectbox(
130
  "Select Neighborhood",
131
  options=visualizer.neighborhoods,
132
+ index=visualizer.neighborhoods.index("Southern") if "Southern" in visualizer.neighborhoods else 0
133
  )
134
  show_traffic = st.checkbox("Show Traffic Cameras", value=True)
135
 
requirements.txt CHANGED
@@ -15,4 +15,5 @@ requests~=2.32.3
15
  oracledb~=2.5.1
16
  pillow~=10.4.0
17
  timm~=1.0.14
18
- streamlit_folium~=0.24.0
 
 
15
  oracledb~=2.5.1
16
  pillow~=10.4.0
17
  timm~=1.0.14
18
+ streamlit_folium~=0.24.0
19
+ watchdog