Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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)
|