42Cummer commited on
Commit
92b9e92
·
verified ·
1 Parent(s): d3b5137

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -20
app.py CHANGED
@@ -6,7 +6,6 @@ import requests
6
  from bs4 import BeautifulSoup
7
  import tempfile
8
  import os
9
- import sys
10
 
11
  app = Flask(__name__)
12
  CORS(app)
@@ -64,9 +63,7 @@ def get_vehicle_locations_and_occupancy(vehicle_numbers):
64
  })
65
  return results
66
 
67
- def get_vehicle_destinations(route, stopcall):
68
- print(f"DEBUG: Fetching vehicle destinations for route: {route}, stopcall: {stopcall}")
69
-
70
  url = f'https://www.transsee.ca/predict?s=ttc.{route}.{stopcall}'
71
  headers = {
72
  'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36',
@@ -81,9 +78,7 @@ def get_vehicle_destinations(route, stopcall):
81
  try:
82
  response = requests.get(url, headers=headers, timeout=10)
83
  response.raise_for_status()
84
- print("DEBUG: Successfully fetched data from Transsee.")
85
  except Exception as e:
86
- print(f"ERROR: Failed to fetch vehicle data: {e}")
87
  return jsonify({"error": f"Failed to fetch vehicle data: {e}"}), 500
88
 
89
  soup = BeautifulSoup(response.text, 'html.parser')
@@ -94,21 +89,17 @@ def get_vehicle_destinations(route, stopcall):
94
  dest_par = soup.find('p', id=pattern)
95
 
96
  if dest_par:
97
- print(f"DEBUG: Found destination paragraph with id: {dest_par['id']}", file=sys.stderr)
98
  contents = dest_par.contents
99
- print(f"DEBUG: Contents: {contents}", file=sys.stderr)
100
  if len(contents) > 1 and "going" in contents[1]:
101
  stuff = contents[1].strip().split(" ")
102
- branch = False
103
  if len(stuff) > 1: branch = stuff[1]
104
  destination_text = dest_par.contents[3].strip()
105
  # Remove directional prefixes
106
- destination_text = re.sub(r'^(North|South|East|West) to\s+', '', destination_text, flags=re.IGNORECASE)
107
  if branch:
108
  vehicle_info['destination'] = branch + " " + destination_text
109
  else:
110
  vehicle_info['destination'] = destination_text
111
- print(f"DEBUG: Extracted destination text: {destination_text}", file=sys.stderr)
112
  else:
113
  vehicle_info['destination'] = []
114
  new_pattern = re.compile(rf'^{route}_{stopcall}\d*_\d*$')
@@ -118,14 +109,12 @@ def get_vehicle_destinations(route, stopcall):
118
  vehicle_link = p_tag.find('a', href="#MapMain")
119
  if vehicle_link and vehicle_link.text.strip().isdigit():
120
  vehicle_data['vehicle_number'] = vehicle_link.text.strip()
121
- print(f"DEBUG: Found vehicle number: {vehicle_data['vehicle_number']}")
122
  else:
123
  # Case 2: Vehicle number is in plain text like "Vehicle 3417 Load"
124
  text = p_tag.get_text()
125
  match = re.search(r'Vehicle\s+(\d+)', text)
126
  if match:
127
  vehicle_data['vehicle_number'] = match.group(1)
128
- print(f"DEBUG: Extracted vehicle number: {vehicle_data['vehicle_number']}")
129
  span_element = p_tag.find('span', class_='tsfont')
130
  if span_element:
131
  destination_text = span_element.next_sibling.strip()
@@ -133,13 +122,39 @@ def get_vehicle_destinations(route, stopcall):
133
  # Remove directional prefixes
134
  destination_text = re.sub(r'^(North|South|East|West)\s+', '', destination_text, flags=re.IGNORECASE)
135
  vehicle_data['destination'] = branch + " " + destination_text
136
- print(f"DEBUG: Extracted destination: {vehicle_data['destination']}")
137
- vehicle_info['destination'].append(vehicle_data)
138
- else:
139
- print("WARNING: No destination paragraph found.")
140
 
141
  return vehicle_info
142
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
  @app.route('/', methods=['GET'])
144
  def health_check():
145
  return 'Backend is running!', 200
@@ -315,10 +330,30 @@ def destinations():
315
  info = get_vehicle_destinations(route, stopCall)
316
  return info
317
 
318
- @app.route('/test_destinations')
319
- def test_destinations():
320
- return jsonify(get_vehicle_destinations('167', '6653'))
 
 
 
 
 
 
 
 
 
 
 
 
321
 
 
 
 
 
 
 
 
 
322
 
323
  if __name__ == '__main__':
324
  app.run(debug=True, port=5000)
 
6
  from bs4 import BeautifulSoup
7
  import tempfile
8
  import os
 
9
 
10
  app = Flask(__name__)
11
  CORS(app)
 
63
  })
64
  return results
65
 
66
+ def get_vehicle_destinations(route, stopcall):
 
 
67
  url = f'https://www.transsee.ca/predict?s=ttc.{route}.{stopcall}'
68
  headers = {
69
  'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36',
 
78
  try:
79
  response = requests.get(url, headers=headers, timeout=10)
80
  response.raise_for_status()
 
81
  except Exception as e:
 
82
  return jsonify({"error": f"Failed to fetch vehicle data: {e}"}), 500
83
 
84
  soup = BeautifulSoup(response.text, 'html.parser')
 
89
  dest_par = soup.find('p', id=pattern)
90
 
91
  if dest_par:
 
92
  contents = dest_par.contents
 
93
  if len(contents) > 1 and "going" in contents[1]:
94
  stuff = contents[1].strip().split(" ")
 
95
  if len(stuff) > 1: branch = stuff[1]
96
  destination_text = dest_par.contents[3].strip()
97
  # Remove directional prefixes
98
+ destination_text = re.sub(r'^(North|South|East|West)\s+', '', destination_text, flags=re.IGNORECASE)
99
  if branch:
100
  vehicle_info['destination'] = branch + " " + destination_text
101
  else:
102
  vehicle_info['destination'] = destination_text
 
103
  else:
104
  vehicle_info['destination'] = []
105
  new_pattern = re.compile(rf'^{route}_{stopcall}\d*_\d*$')
 
109
  vehicle_link = p_tag.find('a', href="#MapMain")
110
  if vehicle_link and vehicle_link.text.strip().isdigit():
111
  vehicle_data['vehicle_number'] = vehicle_link.text.strip()
 
112
  else:
113
  # Case 2: Vehicle number is in plain text like "Vehicle 3417 Load"
114
  text = p_tag.get_text()
115
  match = re.search(r'Vehicle\s+(\d+)', text)
116
  if match:
117
  vehicle_data['vehicle_number'] = match.group(1)
 
118
  span_element = p_tag.find('span', class_='tsfont')
119
  if span_element:
120
  destination_text = span_element.next_sibling.strip()
 
122
  # Remove directional prefixes
123
  destination_text = re.sub(r'^(North|South|East|West)\s+', '', destination_text, flags=re.IGNORECASE)
124
  vehicle_data['destination'] = branch + " " + destination_text
125
+ vehicle_info['destination'].append(vehicle_data)
 
 
 
126
 
127
  return vehicle_info
128
 
129
+ def get_vehicle_delay(vehicle_number):
130
+ url = f"https://www.transsee.ca/fleetfind?a=ttc&findtrack=1&q={vehicle_number}&Go=Go"
131
+ headers = {
132
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36',
133
+ 'Referer': 'https://www.transsee.ca/',
134
+ 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
135
+ 'Accept-Language': 'en-US,en;q=0.9',
136
+ 'DNT': '1', # Do Not Track
137
+ 'Connection': 'keep-alive',
138
+ 'Upgrade-Insecure-Requests': '1'
139
+ }
140
+ try:
141
+ response = requests.get(url, headers=headers, timeout=10)
142
+ response.raise_for_status()
143
+ except Exception as e:
144
+ return jsonify({"error": f"Failed to fetch vehicle data: {e}"}), 500
145
+
146
+ soup = BeautifulSoup(response.text, 'html.parser')
147
+ delay_par = soup.find('p', id=f"{vehicle_number}")
148
+ if delay_par:
149
+ for span in delay_par.find_all('span', style=True):
150
+ if 'color: light-dark' in span['style']:
151
+ delay_span = span
152
+ break
153
+ if delay_span:
154
+ delay_text = delay_span.get_text(strip=True)
155
+ return delay_text if delay_text else "0"
156
+
157
+
158
  @app.route('/', methods=['GET'])
159
  def health_check():
160
  return 'Backend is running!', 200
 
330
  info = get_vehicle_destinations(route, stopCall)
331
  return info
332
 
333
+ @app.route('/vehicleinfo', methods=['POST'])
334
+ def vehicleinfo():
335
+ if not request.is_json:
336
+ return jsonify({'error': 'Request must be JSON'}), 400
337
+ data = request.get_json()
338
+ vehicle_number = data.get('vehicle_number')
339
+ if not vehicle_number:
340
+ return jsonify({'error': 'vehicle_number is required'}), 400
341
+
342
+ location = get_vehicle_locations_and_occupancy(vehicle_number)[0]
343
+ delay = get_vehicle_delay(vehicle_number)
344
+ return jsonify({
345
+ 'location': location,
346
+ 'delay': delay
347
+ })
348
 
349
+ #@app.route('/beta_testing')
350
+ #def beta_testing():
351
+ # location = get_vehicle_locations_and_occupancy(['3166'])[0]
352
+ # delay = get_vehicle_delay('3166')
353
+ # return jsonify({
354
+ # 'location': location,
355
+ # 'delay': delay
356
+ # })
357
 
358
  if __name__ == '__main__':
359
  app.run(debug=True, port=5000)