LapStore commited on
Commit
9d72a91
·
1 Parent(s): 18ef0d3

diving into adding connection to database ,simple test

Browse files
Files changed (2) hide show
  1. app.py +67 -66
  2. requirements.txt +1 -0
app.py CHANGED
@@ -1,25 +1,46 @@
1
- from fastapi import FastAPI
2
- import ast
3
- from typing import List,Union
4
  import requests
 
5
 
6
- app = FastAPI()
 
7
 
8
- @app.get("/")
9
- def read_root():
10
- return {"message": "Hello from FastAPI on Hugging Face Spaces!"}
 
11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  def get_rectangle_container(coordinates):
13
  lons = [i for i, _ in coordinates]
14
  lats = [i for _, i in coordinates]
15
-
16
  min_lat, max_lat = min(lats), max(lats)
17
  min_lon, max_lon = min(lons), max(lons)
18
- return (min_lat,max_lat,min_lon,max_lon)
19
-
20
 
21
  def get_traffic_in_container(coordinates):
22
- (min_lat,max_lat,min_lon,max_lon)= get_rectangle_container(coordinates)
23
  overpass_url = "http://overpass-api.de/api/interpreter"
24
  query = f"""
25
  [out:json];
@@ -28,67 +49,47 @@ def get_traffic_in_container(coordinates):
28
  """
29
  response = requests.get(overpass_url, params={'data': query})
30
  data = response.json()
31
- traffic_lights = [(el['lat'], el['lon']) for el in data['elements']]
32
- return traffic_lights
33
 
34
- import asyncio
35
- async def fetch_data():
36
- await asyncio.sleep(1) # Simulate an asynchronous operation
37
- return {"data": "Fetched data"}
38
-
39
- @app.post("/tmp/")
40
- async def read_root(s:str):
41
- data = await fetch_data()
42
- return {"data": data}
43
 
44
  @app.post("/send-coordinates")
45
  def receive_coordinates(coords: Union[str, List[float]]):
46
- """
47
- Receive a list of coordinates from the mobile app.
48
- Pass these coordinates to a function that checks which traffic signals exist in these areas.
49
- """
50
- if isinstance(coords,str):
51
- coords = ast.literal_eval(coords)
52
- traffic_lights = get_traffic_in_container(coords)
53
- tl_id = check_signals(traffic_lights)
54
-
55
- if tl_id:
56
- return {"message": f"Coordinates {traffic_lights}"}
57
- else:
58
- return {"Error": "No Traffic Light found"}
59
-
60
-
61
-
62
- # -----------------------
63
- # 2. Check traffic signals
64
- # -----------------------
65
-
66
- def check_signals(coords):
67
- """
68
- Check which coordinates have traffic signals by querying the database.
69
- Call a function to verify if it's allowed to open the signal.
70
- """
71
- return "6082411793"
72
-
73
-
74
- # -----------------------
75
- # 3. Verify signal status
76
- # -----------------------
77
-
78
- def can_open_signal(signal_data):
79
- """
80
- Determine whether the signal can be opened based on returned data.
81
- If yes, call the IoT function to open the signal.
82
- """
83
- pass
84
 
 
 
85
 
86
- # -----------------------
87
- # 4. IoT trigger
88
- # -----------------------
 
89
 
90
- def trigger_iot_open(signal_id: str):
 
 
 
91
  """
92
- Send a GET request to the IoT system to open the signal with the given ID.
 
93
  """
94
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException
2
+ from typing import List, Union
 
3
  import requests
4
+ import ast
5
 
6
+ from sqlalchemy import create_engine, text
7
+ from sqlalchemy.orm import sessionmaker, Session
8
 
9
+ # -------------------------
10
+ # App Initialization
11
+ # -------------------------
12
+ app = FastAPI()
13
 
14
+ # -------------------------
15
+ # Database Setup (SQLAlchemy + PyMySQL)
16
+ # -------------------------
17
+ DB_URL = (
18
+ "mysql+pymysql://avnadmin:AVNS_aT0RGFafs6_34WFegSF"
19
+ "@mysql-19285eb2-tahaelshrif1-7999.h.aivencloud.com:11520/trafficManagerSignals"
20
+ )
21
+
22
+ engine = create_engine(DB_URL, pool_size=10, max_overflow=20, pool_pre_ping=True)
23
+ SessionLocal = sessionmaker(bind=engine)
24
+
25
+ def get_db():
26
+ db = SessionLocal()
27
+ try:
28
+ yield db
29
+ finally:
30
+ db.close()
31
+
32
+ # -------------------------
33
+ # Utilities
34
+ # -------------------------
35
  def get_rectangle_container(coordinates):
36
  lons = [i for i, _ in coordinates]
37
  lats = [i for _, i in coordinates]
 
38
  min_lat, max_lat = min(lats), max(lats)
39
  min_lon, max_lon = min(lons), max(lons)
40
+ return min_lat, max_lat, min_lon, max_lon
 
41
 
42
  def get_traffic_in_container(coordinates):
43
+ (min_lat, max_lat, min_lon, max_lon) = get_rectangle_container(coordinates)
44
  overpass_url = "http://overpass-api.de/api/interpreter"
45
  query = f"""
46
  [out:json];
 
49
  """
50
  response = requests.get(overpass_url, params={'data': query})
51
  data = response.json()
52
+ return [(el['lat'], el['lon']) for el in data['elements']]
 
53
 
54
+ # -------------------------
55
+ # Routes
56
+ # -------------------------
57
+ @app.get("/")
58
+ def read_root():
59
+ return {"message": "Hello from FastAPI on Hugging Face Spaces!"}
 
 
 
60
 
61
  @app.post("/send-coordinates")
62
  def receive_coordinates(coords: Union[str, List[float]]):
63
+ if isinstance(coords, str):
64
+ coords = ast.literal_eval(coords)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
 
66
+ traffic_lights = get_traffic_in_container(coords)
67
+ tl_ids = check_signals(traffic_lights)
68
 
69
+ if tl_ids:
70
+ return {"found_signals": tl_ids}
71
+ else:
72
+ return {"error": "No traffic signals found in database"}
73
 
74
+ # -------------------------
75
+ # Signal Database Check
76
+ # -------------------------
77
+ def check_signals(coords, db: Session = next(get_db())):
78
  """
79
+ Check if lat/lon exists in traffic_signals DB table.
80
+ Returns list of tl_id_sumo.
81
  """
82
+ found_signals = []
83
+ for lat, lon in coords:
84
+ result = db.execute(
85
+ text("""
86
+ SELECT tl_id_sumo FROM traffic_signals
87
+ WHERE lat = :lat AND lon = :lon
88
+ """),
89
+ {"lat": lat, "lon": lon}
90
+ ).fetchone()
91
+
92
+ if result:
93
+ found_signals.append(result.tl_id_sumo)
94
+
95
+ return found_signals
requirements.txt CHANGED
@@ -1,3 +1,4 @@
1
  fastapi
2
  uvicorn[standard]
3
  requests
 
 
1
  fastapi
2
  uvicorn[standard]
3
  requests
4
+ pymysql