Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -4,14 +4,14 @@ from flask import Flask, render_template, jsonify, request, redirect, url_for, s
|
|
4 |
import firebase_admin
|
5 |
from firebase_admin import credentials, firestore
|
6 |
import pickle
|
|
|
|
|
|
|
7 |
# Initialize Flask app
|
8 |
app = Flask(__name__)
|
9 |
app.secret_key = os.urandom(24) # For session management
|
10 |
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
cred = credentials.Certificate({
|
16 |
"type": "service_account",
|
17 |
"project_id": "snippetscript-37175",
|
@@ -27,181 +27,77 @@ cred = credentials.Certificate({
|
|
27 |
})
|
28 |
firebase_admin.initialize_app(cred)
|
29 |
|
|
|
30 |
db = firestore.client()
|
31 |
|
32 |
-
@app.route('/')
|
33 |
-
def index():
|
34 |
-
return render_template('index.html')
|
35 |
-
|
36 |
-
@app.route('/user-dashboard.html')
|
37 |
-
def user_dashboard():
|
38 |
-
return render_template('user-dashboard.html')
|
39 |
-
|
40 |
-
@app.route('/get-previous-results', methods=['GET'])
|
41 |
-
def get_previous_results():
|
42 |
-
try:
|
43 |
-
# Simulating a ThingSpeak API call or shared data
|
44 |
-
# response = requests.get("https://api.thingspeak.com/...", params=...)
|
45 |
-
# thingspeak_data = response.json()
|
46 |
-
|
47 |
-
# Returning shared data for all users
|
48 |
-
return jsonify({"status": "success", "data": thingspeak_data})
|
49 |
-
except Exception as e:
|
50 |
-
return jsonify({"status": "error", "message": str(e)})
|
51 |
-
|
52 |
-
# @app.route('/login', methods=['POST'])
|
53 |
-
# def login():
|
54 |
-
# phone = request.form['loginPhone']
|
55 |
-
# password = request.form['loginPassword']
|
56 |
-
|
57 |
-
# # Query Firestore to find user
|
58 |
-
# users_ref = db.collection('users')
|
59 |
-
# query = users_ref.where('phone', '==', phone).where('password', '==', password)
|
60 |
-
|
61 |
-
# try:
|
62 |
-
# users = query.stream()
|
63 |
-
# user_list = list(users)
|
64 |
-
|
65 |
-
# if len(user_list) > 0:
|
66 |
-
# # User found, start session
|
67 |
-
# session['user_phone'] = phone
|
68 |
-
# return redirect(url_for('user_dashboard'))
|
69 |
-
# else:
|
70 |
-
# return "Invalid credentials", 401
|
71 |
-
|
72 |
-
# except Exception as e:
|
73 |
-
# return str(e), 500
|
74 |
-
|
75 |
-
# @app.route('/dashboard')
|
76 |
-
# def user_dashboard():
|
77 |
-
# if 'user_phone' not in session:
|
78 |
-
# return redirect(url_for('index'))
|
79 |
-
|
80 |
-
# # Fetch user details from Firestore
|
81 |
-
# user_ref = db.collection('users').document(session['user_phone'])
|
82 |
-
# user = user_ref.get()
|
83 |
-
|
84 |
-
# if user.exists:
|
85 |
-
# user_data = user.to_dict()
|
86 |
-
# return render_template('user-dashboard.html', user=user_data)
|
87 |
-
# else:
|
88 |
-
# return "User not found", 404
|
89 |
-
|
90 |
-
# @app.route('/admin.html')
|
91 |
-
# def admin():
|
92 |
-
# return render_template('admin.html')
|
93 |
-
@app.route('/admin.html')
|
94 |
-
def admin():
|
95 |
-
# Create a map centered on Delhi
|
96 |
-
delhi_coordinates = [28.6139, 77.2090]
|
97 |
-
folium_map = folium.Map(location=delhi_coordinates, zoom_start=12)
|
98 |
-
|
99 |
-
# Add predefined markers in Delhi
|
100 |
-
markers = [
|
101 |
-
{"name": "India Gate", "coordinates": [28.6129, 77.2295]},
|
102 |
-
{"name": "Red Fort", "coordinates": [28.6562, 77.2410]},
|
103 |
-
{"name": "Qutub Minar", "coordinates": [28.5245, 77.1855]},
|
104 |
-
]
|
105 |
-
|
106 |
-
# Add markers to the map
|
107 |
-
for marker in markers:
|
108 |
-
folium.Marker(
|
109 |
-
location=marker["coordinates"],
|
110 |
-
popup=marker["name"],
|
111 |
-
icon=folium.Icon(color="blue", icon="info-sign"),
|
112 |
-
).add_to(folium_map)
|
113 |
-
|
114 |
-
# Use a valid Folium tile layer
|
115 |
-
folium.TileLayer('OpenStreetMap').add_to(folium_map)
|
116 |
-
|
117 |
-
# Add Layer Control for toggling between tile layers
|
118 |
-
folium.LayerControl().add_to(folium_map)
|
119 |
-
|
120 |
-
# Generate the map HTML
|
121 |
-
map_html = folium_map._repr_html_()
|
122 |
-
|
123 |
-
# Render the template with the map
|
124 |
-
return render_template('admin.html', map=map_html)
|
125 |
-
|
126 |
-
@app.route('/logout')
|
127 |
-
def logout():
|
128 |
-
# Remove the user's phone number from the session
|
129 |
-
session.pop('user_phone', None)
|
130 |
-
|
131 |
-
# Redirect to the index route (function name, not the file name)
|
132 |
-
return redirect(url_for('index'))
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
from twilio.rest import Client
|
137 |
-
import firebase_admin
|
138 |
-
from firebase_admin import credentials, firestore
|
139 |
-
|
140 |
# Twilio Configuration
|
141 |
ACCOUNT_SID = 'AC97ad50edcf94fdd7d4576be9651bf4bf'
|
142 |
AUTH_TOKEN = '6d8b2559ffbbdbc5d06542e545220aaa'
|
143 |
FROM_PHONE = '+12708175529'
|
144 |
TO_PHONE = '+916382792828'
|
145 |
-
import numpy as np
|
146 |
-
import joblib
|
147 |
-
# Save model using joblib
|
148 |
|
149 |
-
# Load model using
|
150 |
-
with open('model.pkl','rb') as f:
|
151 |
-
|
152 |
-
def predict_conc(pdiff):
|
153 |
-
if pdiff>3.19:
|
154 |
-
return 0
|
155 |
-
pdiff_value = pdiff # Replace 1.5 with your input value for "Average Potential Difference"
|
156 |
-
new_data = np.array([[pdiff_value]])
|
157 |
-
prediction = loaded_model.predict(new_data)
|
158 |
-
concentration = 10**prediction[0] # Reverse log transformation
|
159 |
-
return f"{concentration:.4f}"
|
160 |
|
161 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
162 |
|
163 |
-
|
164 |
-
def send_msg(field1,suggestion):
|
165 |
-
# if field;1
|
166 |
-
|
167 |
client = Client(ACCOUNT_SID, AUTH_TOKEN)
|
168 |
try:
|
169 |
message = client.messages.create(
|
170 |
from_=FROM_PHONE,
|
171 |
-
body=f"""Test Results:\nE.coli Level: {field1} CFU/mL
|
172 |
-
Status: safe
|
173 |
-
Suggestions:\n
|
174 |
-
{suggestion}""",
|
175 |
to=TO_PHONE
|
176 |
)
|
177 |
print(f"Message sent successfully! SID: {message.sid}")
|
178 |
except Exception as e:
|
179 |
print(f"Failed to send message: {e}")
|
180 |
|
181 |
-
# Firestore Listener for new data in the 'thingspeak_data' collection
|
182 |
def on_snapshot(doc_snapshot, changes, read_time):
|
183 |
for change in changes:
|
184 |
-
if change.type.name == 'ADDED':
|
185 |
new_data = change.document.to_dict()
|
186 |
-
field1 = new_data.get('field1'
|
|
|
|
|
|
|
|
|
187 |
print(f"New data detected: {new_data}")
|
188 |
-
concentration=predict_conc(field1)
|
189 |
-
if concentration==0:
|
190 |
-
send_msg(0,"The water is safe for use!!")
|
191 |
-
|
192 |
else:
|
193 |
-
send_msg(concentration,"You may boil the water to 50
|
194 |
-
|
195 |
-
# Trigger the Twilio SMS function
|
196 |
|
197 |
-
# Initialize Firestore Listener
|
198 |
def start_firestore_listener():
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
|
|
|
|
203 |
|
|
|
|
|
|
|
204 |
|
|
|
|
|
|
|
|
|
205 |
|
206 |
if __name__ == '__main__':
|
207 |
-
|
|
|
|
4 |
import firebase_admin
|
5 |
from firebase_admin import credentials, firestore
|
6 |
import pickle
|
7 |
+
import numpy as np
|
8 |
+
from twilio.rest import Client
|
9 |
+
|
10 |
# Initialize Flask app
|
11 |
app = Flask(__name__)
|
12 |
app.secret_key = os.urandom(24) # For session management
|
13 |
|
14 |
+
# Firebase Admin SDK initialization
|
|
|
|
|
|
|
15 |
cred = credentials.Certificate({
|
16 |
"type": "service_account",
|
17 |
"project_id": "snippetscript-37175",
|
|
|
27 |
})
|
28 |
firebase_admin.initialize_app(cred)
|
29 |
|
30 |
+
# Firestore client
|
31 |
db = firestore.client()
|
32 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
33 |
# Twilio Configuration
|
34 |
ACCOUNT_SID = 'AC97ad50edcf94fdd7d4576be9651bf4bf'
|
35 |
AUTH_TOKEN = '6d8b2559ffbbdbc5d06542e545220aaa'
|
36 |
FROM_PHONE = '+12708175529'
|
37 |
TO_PHONE = '+916382792828'
|
|
|
|
|
|
|
38 |
|
39 |
+
# Load model using pickle
|
40 |
+
with open('model.pkl', 'rb') as f:
|
41 |
+
loaded_model = pickle.load(f)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
42 |
|
43 |
+
def predict_conc(pdiff):
|
44 |
+
try:
|
45 |
+
if pdiff > 3.19:
|
46 |
+
return 0
|
47 |
+
pdiff_value = pdiff # Input for "Average Potential Difference"
|
48 |
+
new_data = np.array([[pdiff_value]])
|
49 |
+
prediction = loaded_model.predict(new_data)
|
50 |
+
concentration = 10**prediction[0] # Reverse log transformation
|
51 |
+
return f"{concentration:.4f}"
|
52 |
+
except Exception as e:
|
53 |
+
print(f"Error in predict_conc: {e}")
|
54 |
+
return None
|
55 |
|
56 |
+
def send_msg(field1, suggestion):
|
|
|
|
|
|
|
57 |
client = Client(ACCOUNT_SID, AUTH_TOKEN)
|
58 |
try:
|
59 |
message = client.messages.create(
|
60 |
from_=FROM_PHONE,
|
61 |
+
body=f"""Test Results:\nE.coli Level: {field1} CFU/mL.\nStatus: {'safe' if field1 == 0 else 'unsafe'}\nSuggestions:\n{suggestion}""",
|
|
|
|
|
|
|
62 |
to=TO_PHONE
|
63 |
)
|
64 |
print(f"Message sent successfully! SID: {message.sid}")
|
65 |
except Exception as e:
|
66 |
print(f"Failed to send message: {e}")
|
67 |
|
|
|
68 |
def on_snapshot(doc_snapshot, changes, read_time):
|
69 |
for change in changes:
|
70 |
+
if change.type.name == 'ADDED':
|
71 |
new_data = change.document.to_dict()
|
72 |
+
field1 = new_data.get('field1')
|
73 |
+
if field1 is None:
|
74 |
+
print("field1 is missing in the document.")
|
75 |
+
continue
|
76 |
+
|
77 |
print(f"New data detected: {new_data}")
|
78 |
+
concentration = predict_conc(float(field1))
|
79 |
+
if concentration == "0":
|
80 |
+
send_msg(0, "The water is safe for use!!")
|
|
|
81 |
else:
|
82 |
+
send_msg(concentration, "You may boil the water to 50\u00b0C to eradicate the bacteria.")
|
|
|
|
|
83 |
|
|
|
84 |
def start_firestore_listener():
|
85 |
+
try:
|
86 |
+
thingspeak_ref = db.collection('thingspeak_data')
|
87 |
+
thingspeak_ref.on_snapshot(on_snapshot)
|
88 |
+
print("Firestore listener started.")
|
89 |
+
except Exception as e:
|
90 |
+
print(f"Error starting Firestore listener: {e}")
|
91 |
|
92 |
+
@app.route('/')
|
93 |
+
def index():
|
94 |
+
return render_template('index.html')
|
95 |
|
96 |
+
@app.route('/logout')
|
97 |
+
def logout():
|
98 |
+
session.pop('user_phone', None)
|
99 |
+
return redirect(url_for('index'))
|
100 |
|
101 |
if __name__ == '__main__':
|
102 |
+
start_firestore_listener()
|
103 |
+
app.run(host='0.0.0.0', port=7860, debug=True)
|