vumichien commited on
Commit
ce41917
·
1 Parent(s): 737ad85
Files changed (4) hide show
  1. app.py +72 -74
  2. database.db +0 -0
  3. requirements.txt +2 -1
  4. wifi_signals.csv +2 -0
app.py CHANGED
@@ -1,110 +1,102 @@
1
- from fastapi import FastAPI, HTTPException, Depends, Request
2
  from fastapi.responses import HTMLResponse
3
  from fastapi.templating import Jinja2Templates
4
- from sqlalchemy.orm import Session
5
- from sqlalchemy import create_engine, Column, Integer, Float, String, DateTime
6
- from sqlalchemy.ext.declarative import declarative_base
7
- from sqlalchemy.orm import sessionmaker
8
  from datetime import datetime, timedelta
9
  import random
10
  import folium
11
  from folium.plugins import MarkerCluster
 
12
  import os
13
 
14
- # Sử dụng thư mục /tmp để lưu trữ cơ sở dữ liệu SQLite
15
- DATABASE_URL = "sqlite:///./database.db"
16
-
17
- engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})
18
- SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
19
-
20
- Base = declarative_base()
21
-
22
- class WifiSignal(Base):
23
- __tablename__ = "wifi_signal"
24
- id = Column(Integer, primary_key=True, index=True)
25
- latitude = Column(Float, index=True)
26
- longitude = Column(Float, index=True)
27
- timestamp = Column(DateTime, index=True)
28
- signal_strength = Column(Integer)
29
-
30
- # Tạo tất cả các bảng
31
- if not os.path.exists('/app/database.db'):
32
- Base.metadata.create_all(bind=engine)
33
-
34
  app = FastAPI()
35
  templates = Jinja2Templates(directory="templates")
36
 
37
- def get_db():
38
- db = SessionLocal()
39
- try:
40
- yield db
41
- finally:
42
- db.close()
43
 
44
  @app.post("/api/generate-data")
45
- def generate_data(db: Session = Depends(get_db)):
46
  base_latitude = 35.6837
47
  base_longitude = 139.6805
48
  start_date = datetime(2024, 8, 1)
49
  end_date = datetime(2024, 8, 7)
50
  delta = end_date - start_date
51
 
52
- for _ in range(100):
53
- random_days = random.randint(0, delta.days)
54
- random_seconds = random.randint(0, 86400)
55
- random_time = start_date + timedelta(days=random_days, seconds=random_seconds)
56
 
57
- random_latitude = base_latitude + random.uniform(-0.01, 0.01)
58
- random_longitude = base_longitude + random.uniform(-0.01, 0.01)
59
- random_signal_strength = random.randint(10, 50)
 
60
 
61
- wifi_signal = WifiSignal(
62
- latitude=random_latitude,
63
- longitude=random_longitude,
64
- timestamp=random_time,
65
- signal_strength=random_signal_strength
66
- )
67
 
68
- db.add(wifi_signal)
 
 
 
 
 
69
 
70
- db.commit()
71
  return {"message": "Demo data generated successfully"}
72
 
73
  @app.delete("/api/delete-data")
74
- def delete_data(db: Session = Depends(get_db)):
75
  try:
76
- num_rows_deleted = db.query(WifiSignal).delete()
77
- db.commit()
78
- return {"message": f"Deleted {num_rows_deleted} rows from the database."}
 
 
 
 
 
 
79
  except Exception as e:
80
- db.rollback()
81
  raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")
82
 
83
  @app.post("/api/upload")
84
- def upload_data(request: Request, db: Session = Depends(get_db)):
85
- data = request.json()
86
- latitude = data.get('latitude')
87
- longitude = data.get('longitude')
88
- timestamp = datetime.strptime(data.get('timestamp'), '%Y-%m-%d %H:%M:%S')
89
- signal_strength = data.get('signal_strength')
90
-
91
- wifi_signal = WifiSignal(latitude=latitude, longitude=longitude, timestamp=timestamp, signal_strength=signal_strength)
92
- db.add(wifi_signal)
93
- db.commit()
94
-
95
- return {"message": "Data uploaded successfully"}
 
 
 
 
 
 
 
96
 
97
  @app.get("/", response_class=HTMLResponse)
98
- def show_map(request: Request, start_date: str = None, end_date: str = None, db: Session = Depends(get_db)):
99
- query = db.query(WifiSignal)
100
-
101
- if start_date and end_date:
102
- start_datetime = datetime.strptime(start_date, '%Y-%m-%d')
103
- end_datetime = datetime.strptime(end_date, '%Y-%m-%d')
104
- query = query.filter(WifiSignal.timestamp >= start_datetime, WifiSignal.timestamp <= end_datetime)
105
-
106
- signals = query.all()
107
- signal_data = [(signal.latitude, signal.longitude, signal.signal_strength) for signal in signals]
 
 
 
 
 
 
 
108
 
109
  if signal_data:
110
  min_signal = min(s[2] for s in signal_data)
@@ -131,3 +123,9 @@ def show_map(request: Request, start_date: str = None, end_date: str = None, db:
131
 
132
  map_html = m._repr_html_()
133
  return templates.TemplateResponse("map.html", {"request": request, "map_html": map_html, "start_date": start_date, "end_date": end_date})
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException, Request, Form
2
  from fastapi.responses import HTMLResponse
3
  from fastapi.templating import Jinja2Templates
 
 
 
 
4
  from datetime import datetime, timedelta
5
  import random
6
  import folium
7
  from folium.plugins import MarkerCluster
8
+ import csv
9
  import os
10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  app = FastAPI()
12
  templates = Jinja2Templates(directory="templates")
13
 
14
+ CSV_FILE = "wifi_signals.csv"
 
 
 
 
 
15
 
16
  @app.post("/api/generate-data")
17
+ def generate_data():
18
  base_latitude = 35.6837
19
  base_longitude = 139.6805
20
  start_date = datetime(2024, 8, 1)
21
  end_date = datetime(2024, 8, 7)
22
  delta = end_date - start_date
23
 
24
+ with open(CSV_FILE, mode='w', newline='') as file:
25
+ writer = csv.writer(file)
26
+ writer.writerow(['latitude', 'longitude', 'timestamp', 'signal_strength'])
 
27
 
28
+ for _ in range(100):
29
+ random_days = random.randint(0, delta.days)
30
+ random_seconds = random.randint(0, 86400)
31
+ random_time = start_date + timedelta(days=random_days, seconds=random_seconds)
32
 
33
+ random_latitude = base_latitude + random.uniform(-0.01, 0.01)
34
+ random_longitude = base_longitude + random.uniform(-0.01, 0.01)
35
+ random_signal_strength = random.randint(0, 4)
 
 
 
36
 
37
+ writer.writerow([
38
+ random_latitude,
39
+ random_longitude,
40
+ random_time.strftime('%Y-%m-%d %H:%M:%S'),
41
+ random_signal_strength
42
+ ])
43
 
 
44
  return {"message": "Demo data generated successfully"}
45
 
46
  @app.delete("/api/delete-data")
47
+ def delete_data():
48
  try:
49
+ if os.path.exists(CSV_FILE):
50
+ os.remove(CSV_FILE)
51
+
52
+ # Create a new empty CSV file with headers
53
+ with open(CSV_FILE, mode='w', newline='') as file:
54
+ writer = csv.writer(file)
55
+ writer.writerow(['latitude', 'longitude', 'timestamp', 'signal_strength'])
56
+
57
+ return {"message": "Data file deleted and reset successfully"}
58
  except Exception as e:
 
59
  raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")
60
 
61
  @app.post("/api/upload")
62
+ async def upload_data(
63
+ latitude: float = Form(...),
64
+ longitude: float = Form(...),
65
+ timestamp: str = Form(...),
66
+ signal_strength: int = Form(...)
67
+ ):
68
+ try:
69
+ # Validate timestamp format
70
+ datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S')
71
+
72
+ with open(CSV_FILE, mode='a', newline='') as file:
73
+ writer = csv.writer(file)
74
+ writer.writerow([latitude, longitude, timestamp, signal_strength])
75
+
76
+ return {"message": "Data uploaded successfully"}
77
+ except ValueError:
78
+ raise HTTPException(status_code=400, detail="Invalid timestamp format. Use 'YYYY-MM-DD HH:MM:SS'")
79
+ except Exception as e:
80
+ raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")
81
 
82
  @app.get("/", response_class=HTMLResponse)
83
+ def show_map(request: Request, start_date: str = None, end_date: str = None):
84
+ signal_data = []
85
+
86
+ if os.path.exists(CSV_FILE):
87
+ with open(CSV_FILE, mode='r') as file:
88
+ reader = csv.reader(file)
89
+ next(reader) # Skip header row
90
+ for row in reader:
91
+ lat, lon, timestamp, strength = row
92
+ timestamp = datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S')
93
+ if start_date and end_date:
94
+ start_datetime = datetime.strptime(start_date, '%Y-%m-%d')
95
+ end_datetime = datetime.strptime(end_date, '%Y-%m-%d')
96
+ if start_datetime <= timestamp <= end_datetime:
97
+ signal_data.append((float(lat), float(lon), int(strength)))
98
+ else:
99
+ signal_data.append((float(lat), float(lon), int(strength)))
100
 
101
  if signal_data:
102
  min_signal = min(s[2] for s in signal_data)
 
123
 
124
  map_html = m._repr_html_()
125
  return templates.TemplateResponse("map.html", {"request": request, "map_html": map_html, "start_date": start_date, "end_date": end_date})
126
+
127
+
128
+ if __name__ == "__main__":
129
+ import uvicorn
130
+ uvicorn.run(app, host="0.0.0.0", port=5000)
131
+
database.db CHANGED
Binary files a/database.db and b/database.db differ
 
requirements.txt CHANGED
@@ -1,5 +1,6 @@
1
  fastapi==0.95.1
2
  uvicorn==0.22.0
3
- sqlalchemy==1.4.22
4
  folium==0.13.0
5
  jinja2==3.1.2
 
 
1
  fastapi==0.95.1
2
  uvicorn==0.22.0
3
+ sqlalchemy==2.0.16
4
  folium==0.13.0
5
  jinja2==3.1.2
6
+ python-multipart
wifi_signals.csv ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ latitude,longitude,timestamp,signal_strength
2
+ 35.6895,139.6917,2024-08-29 14:30:00,4