Fzina commited on
Commit
77d9a80
·
verified ·
1 Parent(s): 427af89

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -11
app.py CHANGED
@@ -1,6 +1,6 @@
1
- import requests
2
  import os
3
  import logging
 
4
  from geopy.geocoders import Nominatim
5
  from stable_baselines3 import PPO
6
  from stable_baselines3.common.vec_env import DummyVecEnv
@@ -8,9 +8,10 @@ import gymnasium as gym
8
  from gymnasium import spaces
9
  import numpy as np
10
  from PIL import Image
 
11
 
12
  # Environment Variables
13
- FASTAPI_API_URL = os.getenv("FASTAPI_API_URL") # FastAPI Traffic Analysis API URL
14
  WEATHER_API_KEY = os.getenv("WEATHER_API_KEY") # OpenWeatherMap API key
15
 
16
  # Logging setup
@@ -19,21 +20,30 @@ logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(
19
  # OpenStreetMap Geocoder Setup
20
  geolocator = Nominatim(user_agent="traffic_management_system")
21
 
 
22
  def analyze_traffic(image_path):
23
  """
24
- Sends the traffic image to the FastAPI Traffic Analysis API.
25
  """
26
  try:
27
  with open(image_path, "rb") as image_file:
28
- response = requests.post(f"{FASTAPI_API_URL}/analyze", files={"file": image_file})
29
- response.raise_for_status()
 
 
30
  result = response.json()
31
- return result["vehicle_count"], result["congestion_level"], result["flow_rate"]
 
 
 
 
 
 
32
  except Exception as e:
33
- logging.error(f"Error analyzing traffic via FastAPI API: {e}")
34
  return 0, "Error", "Error"
35
 
36
- # Reinforcement Learning-based Signal Optimization
37
  class TrafficSimEnv(gym.Env):
38
  def __init__(self, congestion_level):
39
  super(TrafficSimEnv, self).__init__()
@@ -94,14 +104,40 @@ def optimize_signal_rl(congestion_level):
94
  logging.error(f"Error optimizing signal with RL: {e}")
95
  return "Error in RL Optimization"
96
 
97
- def process_traffic_image(image_path):
 
 
 
 
 
 
 
 
98
  vehicle_count, congestion_level, flow_rate = analyze_traffic(image_path)
99
  signal_timing = optimize_signal_rl(congestion_level)
 
 
100
  return (f"Detected Vehicles: {vehicle_count}\n"
101
  f"Congestion Level: {congestion_level}\n"
102
  f"Traffic Flow: {flow_rate}\n"
103
  f"Signal Timing Suggestion: {signal_timing}")
104
 
 
 
 
 
 
 
 
105
  if __name__ == "__main__":
106
- image_path = "test_image.jpg" # Replace with actual image path
107
- print(process_traffic_image(image_path))
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
  import logging
3
+ import requests
4
  from geopy.geocoders import Nominatim
5
  from stable_baselines3 import PPO
6
  from stable_baselines3.common.vec_env import DummyVecEnv
 
8
  from gymnasium import spaces
9
  import numpy as np
10
  from PIL import Image
11
+ import gradio as gr
12
 
13
  # Environment Variables
14
+ HOSTED_API_URL = os.getenv("HOSTED_API_URL") # FastAPI backend URL
15
  WEATHER_API_KEY = os.getenv("WEATHER_API_KEY") # OpenWeatherMap API key
16
 
17
  # Logging setup
 
20
  # OpenStreetMap Geocoder Setup
21
  geolocator = Nominatim(user_agent="traffic_management_system")
22
 
23
+ # Analyze Traffic using FastAPI
24
  def analyze_traffic(image_path):
25
  """
26
+ Sends the traffic image to the FastAPI backend for analysis.
27
  """
28
  try:
29
  with open(image_path, "rb") as image_file:
30
+ files = {"file": image_file}
31
+ response = requests.post(f"{HOSTED_API_URL}/analyze_traffic/", files=files)
32
+
33
+ if response.status_code == 200:
34
  result = response.json()
35
+ vehicle_count = result.get("vehicle_count", 0)
36
+ congestion_level = result.get("congestion_level", "Unknown")
37
+ flow_rate = result.get("flow_rate", "Unknown")
38
+ return vehicle_count, congestion_level, flow_rate
39
+ else:
40
+ logging.error(f"Error analyzing traffic: {response.text}")
41
+ return 0, "Error", "Error"
42
  except Exception as e:
43
+ logging.error(f"Error analyzing traffic: {e}")
44
  return 0, "Error", "Error"
45
 
46
+ # RL Optimization Class and Methods (unchanged)
47
  class TrafficSimEnv(gym.Env):
48
  def __init__(self, congestion_level):
49
  super(TrafficSimEnv, self).__init__()
 
104
  logging.error(f"Error optimizing signal with RL: {e}")
105
  return "Error in RL Optimization"
106
 
107
+ def process_traffic_image(image):
108
+ """
109
+ Orchestrates the traffic analysis workflow.
110
+ """
111
+ # Save the uploaded image temporarily
112
+ image_path = "temp_traffic_image.jpg"
113
+ image.save(image_path)
114
+
115
+ # Analyze traffic and optimize signal timing
116
  vehicle_count, congestion_level, flow_rate = analyze_traffic(image_path)
117
  signal_timing = optimize_signal_rl(congestion_level)
118
+ os.remove(image_path) # Clean up the temporary image
119
+
120
  return (f"Detected Vehicles: {vehicle_count}\n"
121
  f"Congestion Level: {congestion_level}\n"
122
  f"Traffic Flow: {flow_rate}\n"
123
  f"Signal Timing Suggestion: {signal_timing}")
124
 
125
+ # Gradio Interface
126
+ def gradio_interface(image):
127
+ """
128
+ Wrapper for Gradio to handle input/output for traffic analysis.
129
+ """
130
+ return process_traffic_image(image)
131
+
132
  if __name__ == "__main__":
133
+ # Gradio UI
134
+ interface = gr.Interface(
135
+ fn=gradio_interface,
136
+ inputs=gr.Image(type="pil", label="Upload Traffic Image"),
137
+ outputs=gr.Textbox(label="Traffic Analysis Results"),
138
+ title="Traffic Management System",
139
+ description="Upload a traffic image to analyze congestion and get signal timing suggestions."
140
+ )
141
+
142
+ # Launch Gradio app
143
+ interface.launch()