Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,70 +1,64 @@
|
|
1 |
import os
|
2 |
-
import
|
3 |
-
import
|
4 |
-
import pickle
|
5 |
-
import numpy as np
|
6 |
-
from flask import Flask, render_template, redirect, url_for, session
|
7 |
import firebase_admin
|
8 |
from firebase_admin import credentials, firestore
|
|
|
|
|
|
|
|
|
|
|
9 |
from twilio.rest import Client
|
10 |
|
11 |
# Initialize Flask app
|
12 |
-
app = Flask(__name__)
|
13 |
app.secret_key = os.urandom(24) # For session management
|
14 |
|
15 |
# Firebase Admin SDK initialization
|
16 |
-
|
17 |
-
|
18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
19 |
firebase_admin.initialize_app(cred)
|
20 |
|
21 |
# Firestore client
|
22 |
db = firestore.client()
|
23 |
-
|
24 |
-
# Twilio Configuration
|
25 |
-
ACCOUNT_SID = 'AC97ad50edcf94fdd7d4576be9651bf4bf'
|
26 |
-
AUTH_TOKEN = '6d8b2559ffbbdbc5d06542e545220aaa'
|
27 |
-
FROM_PHONE = '+12708175529'
|
28 |
-
TO_PHONE = '+916382792828'
|
29 |
-
|
30 |
-
# Load model using pickle
|
31 |
with open('model.pkl', 'rb') as f:
|
32 |
loaded_model = pickle.load(f)
|
33 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
34 |
def predict_conc(pdiff):
|
35 |
try:
|
36 |
if pdiff > 3.19:
|
37 |
-
return 0
|
38 |
-
pdiff_value = pdiff # Input for "Average Potential Difference"
|
39 |
-
new_data = np.array([[pdiff_value]])
|
40 |
-
prediction = loaded_model.predict(new_data)
|
41 |
-
concentration = 10**prediction[0] # Reverse log transformation
|
42 |
-
return f"{concentration:.4f}"
|
43 |
-
except Exception as e:
|
44 |
print(f"Error in predict_conc: {e}")
|
45 |
return None
|
46 |
|
|
|
47 |
def send_msg(field1, suggestion):
|
48 |
client = Client(ACCOUNT_SID, AUTH_TOKEN)
|
49 |
try:
|
50 |
-
message = client.messages.create(
|
51 |
-
from_=FROM_PHONE,
|
52 |
-
body=f"""Test Results:\nE.coli Level: {field1} CFU/mL.\nStatus: {'safe' if field1 == 0 else 'unsafe'}\nSuggestions:\n{suggestion}""",
|
53 |
-
to=TO_PHONE
|
54 |
-
)
|
55 |
-
print(f"Message sent successfully! SID: {message.sid}")
|
56 |
except Exception as e:
|
57 |
print(f"Failed to send message: {e}")
|
58 |
|
|
|
59 |
def on_snapshot(doc_snapshot, changes, read_time):
|
60 |
for change in changes:
|
61 |
if change.type.name == 'ADDED':
|
62 |
-
new_data = change.document.to_dict()
|
63 |
-
field1 = new_data.get('field1')
|
64 |
-
if field1 is None:
|
65 |
-
print("field1 is missing in the document.")
|
66 |
-
continue
|
67 |
-
|
68 |
print(f"New data detected: {new_data}")
|
69 |
concentration = predict_conc(float(field1))
|
70 |
if concentration == "0":
|
@@ -72,11 +66,10 @@ def on_snapshot(doc_snapshot, changes, read_time):
|
|
72 |
else:
|
73 |
send_msg(concentration, "You may boil the water to 50\u00b0C to eradicate the bacteria.")
|
74 |
|
|
|
75 |
def start_firestore_listener():
|
76 |
try:
|
77 |
thingspeak_ref = db.collection('thingspeak_data')
|
78 |
-
thingspeak_ref.on_snapshot(on_snapshot)
|
79 |
-
print("Firestore listener started.")
|
80 |
except Exception as e:
|
81 |
print(f"Error starting Firestore listener: {e}")
|
82 |
|
@@ -149,6 +142,7 @@ def fetch_thingspeak_data():
|
|
149 |
return None
|
150 |
|
151 |
def store_data_in_firestore(firestore_client, data):
|
|
|
152 |
"""Store data in Firestore"""
|
153 |
try:
|
154 |
# Validate data
|
@@ -159,7 +153,6 @@ def store_data_in_firestore(firestore_client, data):
|
|
159 |
# Create a document with timestamp
|
160 |
doc_data = {
|
161 |
'field1': data.get('field1'),
|
162 |
-
'field2': data.get('field2'),
|
163 |
'entry_id': data.get('entry_id'),
|
164 |
'timestamp': firestore.SERVER_TIMESTAMP
|
165 |
}
|
@@ -173,9 +166,12 @@ def store_data_in_firestore(firestore_client, data):
|
|
173 |
|
174 |
firestore_client = initialize_firebase()
|
175 |
|
|
|
|
|
176 |
if not firestore_client:
|
177 |
print("Failed to initialize Firestore. Exiting.")
|
178 |
-
|
|
|
179 |
# Main data collection loop
|
180 |
try:
|
181 |
while True:
|
@@ -193,7 +189,30 @@ except KeyboardInterrupt:
|
|
193 |
print("Data collection stopped by user.")
|
194 |
except Exception as e:
|
195 |
print(f"Unexpected error: {e}")
|
196 |
-
|
197 |
if __name__ == '__main__':
|
198 |
-
|
199 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import os
|
2 |
+
import folium
|
3 |
+
from flask import Flask, render_template, jsonify, request, redirect, url_for, session
|
|
|
|
|
|
|
4 |
import firebase_admin
|
5 |
from firebase_admin import credentials, firestore
|
6 |
+
import pickle
|
7 |
+
import numpy as np
|
8 |
+
|
9 |
+
|
10 |
+
|
11 |
from twilio.rest import Client
|
12 |
|
13 |
# Initialize Flask app
|
|
|
14 |
app.secret_key = os.urandom(24) # For session management
|
15 |
|
16 |
# Firebase Admin SDK initialization
|
17 |
+
cred = credentials.Certificate({
|
18 |
+
"type": "service_account",
|
19 |
+
"project_id": "snippetscript-37175",
|
20 |
+
"private_key_id": "7d509b09fd4ba89f490e0d76a6aa69bf12750739",
|
21 |
+
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCcFcmms+X9z6xg\n3HXrTsKzqFtCn05jUij4wSnd1ZqoJclWP2H01jiLAzKWGjJaTi6iBOnPT7uPSo8d\nlKe0GjBn9OstHRv1CzEBP1CW4B7jrcZqBbA5nsx/XCkrzgxjJ2OCLmtyBUf/3s7j\nC2bkAu4aGyToZJwuqw1BleXBgevocjkaSW/RvWGlpSTg9OHsgRaGYALw50WzPqdv\nCio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WCbZcGZtEx0zDHqH2Uus9YlXAFH\nIvYeefNemrtx80eMwn982fC6TNVM5QBh8tykFnykL6GCabWVBt7lIwLY2WM2CDy6\n+XqJrkpWym2rLpnUYThgeRwQ5WkbroPq3UDn1lXzAoGBAJVQ9pe4KCfkFP+lX7eq\n8KXFnBuVB5EQ+VDrob9KyaGRyJ5mxYqMgQc9xgYhUSGmwzkXdB3hdsCRwft5n6rr\nKNerrFH+yUwBQUXaJCY2gSUOGbKUfKGdFjoITTlpZAxnkvojk9OKz8c2HlBdE0yL\nQrbuvPr0goYJXoZj3mbDp9lO\n-----END PRIVATE KEY-----\n",
|
22 |
+
"client_email": "firebase-adminsdk-cf1z8@snippetscript-37175.iam.gserviceaccount.com",
|
23 |
+
"client_id": "103525651848757260255",
|
24 |
+
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
|
25 |
+
"token_uri": "https://oauth2.googleapis.com/token",
|
26 |
+
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
|
27 |
+
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-cf1z8%40snippetscript-37175.iam.gserviceaccount.com",
|
28 |
+
"universe_domain": "googleapis.com"
|
29 |
+
})
|
30 |
firebase_admin.initialize_app(cred)
|
31 |
|
32 |
# Firestore client
|
33 |
db = firestore.client()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
34 |
with open('model.pkl', 'rb') as f:
|
35 |
loaded_model = pickle.load(f)
|
36 |
|
37 |
+
|
38 |
+
|
39 |
+
|
40 |
+
|
41 |
+
|
42 |
+
|
43 |
+
|
44 |
+
|
45 |
def predict_conc(pdiff):
|
46 |
try:
|
47 |
if pdiff > 3.19:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
48 |
print(f"Error in predict_conc: {e}")
|
49 |
return None
|
50 |
|
51 |
+
|
52 |
def send_msg(field1, suggestion):
|
53 |
client = Client(ACCOUNT_SID, AUTH_TOKEN)
|
54 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
55 |
except Exception as e:
|
56 |
print(f"Failed to send message: {e}")
|
57 |
|
58 |
+
|
59 |
def on_snapshot(doc_snapshot, changes, read_time):
|
60 |
for change in changes:
|
61 |
if change.type.name == 'ADDED':
|
|
|
|
|
|
|
|
|
|
|
|
|
62 |
print(f"New data detected: {new_data}")
|
63 |
concentration = predict_conc(float(field1))
|
64 |
if concentration == "0":
|
|
|
66 |
else:
|
67 |
send_msg(concentration, "You may boil the water to 50\u00b0C to eradicate the bacteria.")
|
68 |
|
69 |
+
|
70 |
def start_firestore_listener():
|
71 |
try:
|
72 |
thingspeak_ref = db.collection('thingspeak_data')
|
|
|
|
|
73 |
except Exception as e:
|
74 |
print(f"Error starting Firestore listener: {e}")
|
75 |
|
|
|
142 |
return None
|
143 |
|
144 |
def store_data_in_firestore(firestore_client, data):
|
145 |
+
|
146 |
"""Store data in Firestore"""
|
147 |
try:
|
148 |
# Validate data
|
|
|
153 |
# Create a document with timestamp
|
154 |
doc_data = {
|
155 |
'field1': data.get('field1'),
|
|
|
156 |
'entry_id': data.get('entry_id'),
|
157 |
'timestamp': firestore.SERVER_TIMESTAMP
|
158 |
}
|
|
|
166 |
|
167 |
firestore_client = initialize_firebase()
|
168 |
|
169 |
+
|
170 |
+
|
171 |
if not firestore_client:
|
172 |
print("Failed to initialize Firestore. Exiting.")
|
173 |
+
return
|
174 |
+
|
175 |
# Main data collection loop
|
176 |
try:
|
177 |
while True:
|
|
|
189 |
print("Data collection stopped by user.")
|
190 |
except Exception as e:
|
191 |
print(f"Unexpected error: {e}")
|
192 |
+
|
193 |
if __name__ == '__main__':
|
194 |
+
start_firestore_listener()
|
195 |
+
|
196 |
+
|
197 |
+
|
198 |
+
|
199 |
+
|
200 |
+
|
201 |
+
|
202 |
+
|
203 |
+
|
204 |
+
|
205 |
+
|
206 |
+
|
207 |
+
|
208 |
+
|
209 |
+
|
210 |
+
|
211 |
+
|
212 |
+
|
213 |
+
|
214 |
+
|
215 |
+
|
216 |
+
|
217 |
+
|
218 |
+
app.run(host='0.0.0.0', port=7860, debug=True)
|