-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
142 lines (119 loc) · 4 KB
/
main.py
File metadata and controls
142 lines (119 loc) · 4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
import os
import atexit
import numpy as np
import json, requests
from PIL import Image
import tensorflow as tf
from pathlib import Path
from pydantic import BaseModel
from starlette.responses import RedirectResponse
from database import update_data_field, cleanup
from fastapi import FastAPI, UploadFile, HTTPException, Security, Depends
from fastapi.security import APIKeyHeader
from constants import example_data
DRISHTI_AUTH_KEY = os.environ.get("DRISHTI_AUTH_KEY")
DRISHTI_AUTH_KEY_NAME = os.environ.get("DRISHTI_AUTH_KEY_NAME")
if not DRISHTI_AUTH_KEY:
raise ValueError("DRISHTI_AUTH_KEY environment variable must be set")
class Item(BaseModel):
uuid: str
time: str
humidity: str
temperature: str
soil_moisture: str
api_key_header = APIKeyHeader(name=DRISHTI_AUTH_KEY_NAME, auto_error=True)
async def verify_api_key(api_key: str = Security(api_key_header)):
if api_key != DRISHTI_AUTH_KEY:
raise HTTPException(
status_code=403,
detail="Invalid API key",
)
return api_key
mongo_string = os.environ.get("MONGO_STRING")
app = FastAPI(title="Dristhi Backend", description="APIs for Dristhi", version="1.0")
def load_model():
model_path = (
Path(__file__).resolve().parent.parent
/ "weights"
/ "plant_disease_classifier.h5"
)
model = tf.keras.models.load_model(model_path)
return model
@app.get("/")
async def display() -> str:
# response = RedirectResponse(url='https://github.com/epicshi')
response = "Welcome to Dristhi Backend"
return response
@app.post("/predict")
async def predict(
file: UploadFile,
api_key: str = Depends(verify_api_key)
) -> str:
model = load_model()
original_image = Image.open(file.file).convert("RGB")
preprocessed_image = original_image.resize((256, 256))
preprocessed_image = np.array(preprocessed_image)[:, :, :3] / 255.0
preds = model.predict(np.expand_dims(preprocessed_image, axis=0))
labels = ["Healthy", "Powdery", "Rust"]
preds_class = np.argmax(preds)
preds_label = labels[preds_class]
return preds_label
@app.post("/update-data")
async def update_data(
item: Item,
api_key: str = Depends(verify_api_key)
) -> str:
if (
item.humidity.lower() == "nan"
or item.temperature.lower() == "nan"
or item.soil_moisture.lower() == "nan"
):
return "Invalid data"
return update_data_field(
str(item.uuid),
{
"timestamp": int(item.time),
"humidity": float(item.humidity),
"temperature": float(item.temperature),
"soil_moisture": float(item.soil_moisture),
},
)
@app.get("/fetch-news")
async def fetch_news(
api_key: str = Depends(verify_api_key)
):
news_api_key = os.environ.get("NEWS_API_KEY")
if not news_api_key:
raise HTTPException(
status_code=500,
detail="News API key not configured"
)
response = requests.get(
'https://newsapi.org/v2/everything',
params={
'q': '(farmer OR agriculture OR "rural development" OR "farm laws" OR kisaan OR kisan) AND (India OR Maharashtra OR Punjab OR Karnataka OR "Uttar Pradesh")',
'language': 'en',
'sortBy': 'publishedAt',
'apiKey': news_api_key
}
)
if response.status_code != 200:
# print(response.content)
# raise HTTPException(
# status_code=500,
# detail="News API request failed"
# )
return example_data
return json.loads(response.content)
@app.get("/last-data")
async def last_data(
api_key: str = Depends(verify_api_key)
):
return "returns last 10 data"
if __name__ == "__main__":
import uvicorn
try:
uvicorn.run("main:app", host="0.0.0.0", port=7860, reload=True)
finally:
cleanup()
atexit.register(cleanup)