Rakshitjan commited on
Commit
6581e5a
·
verified ·
1 Parent(s): ece9c01

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +47 -113
main.py CHANGED
@@ -1,130 +1,64 @@
1
  from fastapi import FastAPI, HTTPException
2
  from fastapi.middleware.cors import CORSMiddleware
 
3
  from fastapi.responses import JSONResponse
4
- import firebase_admin
5
- from firebase_admin import credentials, firestore
6
- import os
7
- from pydantic import BaseModel
8
- from typing import Optional
9
- import datetime
10
 
11
- # Initialize FastAPI app
12
- app = FastAPI(title="IoT Data API", description="API for retrieving IoT device data from Firebase")
 
 
 
 
 
 
 
13
 
14
- # Add CORS middleware to allow cross-origin requests
 
 
 
15
  app.add_middleware(
16
  CORSMiddleware,
17
- allow_origins=["*"], # Allows all origins
18
  allow_credentials=True,
19
- allow_methods=["*"], # Allows all methods
20
- allow_headers=["*"], # Allows all headers
21
  )
22
 
23
- # Firebase configuration
24
- firebase_config = {
25
- "apiKey": "AIzaSyAPgYJabQqcaKKCn6rob3AZd54s4hAnaAs",
26
- "authDomain": "sareesite-4aef4.firebaseapp.com",
27
- "projectId": "sareesite-4aef4",
28
- "storageBucket": "sareesite-4aef4.firebasestorage.app",
29
- "messagingSenderId": "504565105645",
30
- "appId": "1:504565105645:web:466ed0fc5267dc6550dde4"
31
- }
32
-
33
- # Initialize Firebase
34
- try:
35
- # For Firebase Admin SDK with configuration
36
- firebase_admin.initialize_app(options={
37
- 'projectId': firebase_config['projectId'],
38
- })
39
- db = firestore.client()
40
- print("Firebase connection established successfully")
41
- except Exception as e:
42
- print(f"Error initializing Firebase: {e}")
43
-
44
- # Define the IoT data model
45
- class IoTData(BaseModel):
46
- device_id: Optional[str] = None
47
- timestamp: Optional[str] = None
48
- detected_count: Optional[int] = None
49
- has_detections: Optional[bool] = None
50
- image_name: Optional[str] = None
51
- imagebase64: Optional[str] = None
52
 
53
  @app.get("/")
54
- def read_root():
55
- return {"message": "IoT Data API is running"}
56
 
57
- @app.get("/api/latest", response_model=IoTData)
58
- async def get_latest_data():
59
- """
60
- Get the latest IoT data based on timestamp
61
- """
62
  try:
63
- # Query the IOT collection, order by timestamp in descending order, and limit to 1 document
64
- iot_ref = db.collection("IOT")
65
- query = iot_ref.order_by("timestamp", direction=firestore.Query.DESCENDING).limit(1)
66
- docs = query.get()
67
-
68
- if not docs:
69
- raise HTTPException(status_code=404, detail="No IoT data found")
70
-
71
- # Get the first (and only) document from the query result
72
- latest_doc = docs[0]
73
- data = latest_doc.to_dict()
74
-
75
- # Return the data as JSON
76
- return JSONResponse(content=data)
77
-
78
- except Exception as e:
79
- raise HTTPException(status_code=500, detail=f"Error retrieving data: {str(e)}")
80
 
81
- @app.get("/api/traffic-status")
82
- async def get_traffic_status():
83
- """
84
- Get traffic status based on the latest detected count
85
- """
86
- try:
87
- # Query the latest document
88
- iot_ref = db.collection("IOT")
89
- query = iot_ref.order_by("timestamp", direction=firestore.Query.DESCENDING).limit(1)
90
- docs = query.get()
91
-
92
- if not docs:
93
- raise HTTPException(status_code=404, detail="No IoT data found")
94
-
95
- # Get detected count from the latest document
96
- latest_doc = docs[0]
97
- data = latest_doc.to_dict()
98
- detected_count = data.get("detected_count")
99
-
100
- if detected_count is None:
101
- return {"status": "UNKNOWN", "count": None}
102
-
103
- # Determine traffic status based on detected count
104
- if detected_count < 4:
105
- status = "LIGHT TRAFFIC"
106
- elif detected_count < 7:
107
- status = "MEDIUM TRAFFIC"
108
- else:
109
- status = "HEAVY TRAFFIC"
110
-
111
- return {"status": status, "count": detected_count}
112
-
113
- except Exception as e:
114
- raise HTTPException(status_code=500, detail=f"Error retrieving traffic status: {str(e)}")
115
 
116
- @app.get("/api/health")
117
- async def health_check():
118
- """
119
- Health check endpoint to verify API is running
120
- """
121
- return {
122
- "status": "healthy",
123
- "timestamp": datetime.datetime.now().isoformat()
124
- }
125
 
126
- # Hugging Face Spaces typically expects this port
127
- if __name__ == "__main__":
128
- import uvicorn
129
- port = int(os.environ.get("PORT", 7860))
130
- uvicorn.run("main:app", host="0.0.0.0", port=port, reload=True)
 
 
 
 
 
 
 
 
 
 
 
1
  from fastapi import FastAPI, HTTPException
2
  from fastapi.middleware.cors import CORSMiddleware
3
+ import pyrebase
4
  from fastapi.responses import JSONResponse
 
 
 
 
 
 
5
 
6
+ # Firebase config (client SDK)
7
+ const firebaseConfig = {
8
+ apiKey: "AIzaSyAPgYJabQqcaKKCn6rob3AZd54s4hAnaAs",
9
+ authDomain: "sareesite-4aef4.firebaseapp.com",
10
+ projectId: "sareesite-4aef4",
11
+ storageBucket: "sareesite-4aef4.firebasestorage.app",
12
+ messagingSenderId: "504565105645",
13
+ appId: "1:504565105645:web:466ed0fc5267dc6550dde4"
14
+ };
15
 
16
+ # Initialize app
17
+ app = FastAPI()
18
+
19
+ # CORS
20
  app.add_middleware(
21
  CORSMiddleware,
22
+ allow_origins=["*"],
23
  allow_credentials=True,
24
+ allow_methods=["*"],
25
+ allow_headers=["*"],
26
  )
27
 
28
+ # Initialize pyrebase
29
+ firebase = pyrebase.initialize_app(firebase_config)
30
+ auth = firebase.auth()
31
+ firestore = firebase.database() # Note: this works only for Realtime DB, not Firestore
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
  @app.get("/")
34
+ def root():
35
+ return {"message": "API is working"}
36
 
37
+ @app.get("/api/latest")
38
+ def get_latest():
 
 
 
39
  try:
40
+ # Firestore REST API call (simulate client behavior)
41
+ import requests
42
+ url = f"https://firestore.googleapis.com/v1/projects/{firebase_config['projectId']}/databases/(default)/documents/IOT?pageSize=1&orderBy=timestamp desc"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
+ res = requests.get(url)
45
+ if res.status_code != 200:
46
+ raise HTTPException(status_code=500, detail="Failed to fetch from Firestore")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
+ data = res.json()
 
 
 
 
 
 
 
 
49
 
50
+ if "documents" not in data or len(data["documents"]) == 0:
51
+ raise HTTPException(status_code=404, detail="No data found")
52
+
53
+ doc = data["documents"][0]
54
+ fields = doc["fields"]
55
+
56
+ # Convert Firestore field types to Python types
57
+ def parse_value(field):
58
+ return list(field.values())[0]
59
+
60
+ result = {k: parse_value(v) for k, v in fields.items()}
61
+ return JSONResponse(content=result)
62
+
63
+ except Exception as e:
64
+ raise HTTPException(status_code=500, detail=f"Error: {str(e)}")