Neurolingua commited on
Commit
bd088af
·
verified ·
1 Parent(s): 59a0e31

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +96 -164
app.py CHANGED
@@ -1,218 +1,150 @@
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\nCioW8ioN8IGAM4TIZtsHSayBkruC3PbW+9krnevcx08f3hPi0I2OB51GxKsOGRj8\nVGxb+LUaUaAauCqV9LaCwK9qwtBZopXx2QwbR/vZGgsXk3BvAVsopbmxeyqtj/a4\nc2x7wL17AgMBAAECggEARqXH9afkuGqo09jFmOG31/iigfe4U9VKzTklOY7m5yff\nRyX+MQNLaYRjf7RQyTYs/lGqAJdOxk9RkuqHs8nM0ij1z6Am2NWdczqUwA2mfZhY\nwAFeH96EIjt1OSoUykZ4UGKxaFUCn0paq0KsahT3b6KMpJFxbeAnamGuMlWbkUR4\n1kb1vWVe/XjBMlrDVoOMYvclo/dn7oPmYMtbufrMsdn9eb4JQf1PRfAno6JdE1RB\nHZs5/kkZv8sKXc0lw+RpD35Syl3MTxIAr/PDK8cgnytS5BInZxV2iEcdvNN3/JsC\n7hJPrqb6JOZHl0WnOxXDWvBI8jREoiNTMBqT9JVcCQKBgQDUATBaeLf4ydMOtgLt\nIVuSGto6lSt3hpi85MMYeqRr/MSbltdAEVis8opCTTCBFCQgqdiqXyIKbOvKyn47\n9PLoWciyhK3TJq8u3Oaxfk1wfGdr+Q6/d8LVZQSw1X0wrTOWAdQL9Em78mhpJrvr\nSuwOKjBlP3FgilabeDrfwjFFOQKBgQC8edtC4smOaOU1ovgWFhHumcryrNtCPv9K\nb8A3687+lawzETkQ68xBpuzxRbnW7gFJfk4iVjUErdP21LLvD9hu4e2gmQfVhNQ6\nGT7eBB41l/KVPjSghgMf5fcThBeHCK1C9V9Y56nyqZoQUvbi41cJeXDbK6urtn5L\no7p2gm2sUwKBgQCoV+lVbdZoL5rwa4cXVQ2pjrkLG7hQSQivtddVcM1vEl/sTHLP\n5PZNHqq6yyBg3uVxKm1pm/Ej5im19eUXJwJbji/X0ZNVv7oLtE1bU7eaQq69Bh+3\n2hlT6cs3v86RAHed/gWrGGgUXgCavq8pv2yCMu4K973HsxHiki3tz/3fwQKBgHvr\nHocmduDEBNe0E6rpzdZzlWTi07IFm3IEcXwS9WCbZcGZtEx0zDHqH2Uus9YlXAFH\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":
65
- send_msg(0, "The water is safe for use!!")
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
-
76
- @app.route('/')
77
- def index():
78
- return render_template('index.html')
79
-
80
- @app.route('/logout')
81
- def logout():
82
- session.pop('user_phone', None)
83
- return redirect(url_for('index'))
84
-
85
-
86
-
87
- import requests
88
- import firebase_admin
89
- from firebase_admin import credentials, firestore
90
- import time
91
 
92
- # Replace with your actual credentials
 
93
  THINGSPEAK_API_KEY = "P54KXM40TA3CB6W4"
94
  CHANNEL_ID = "2784385"
95
- FIREBASE_CREDENTIALS_PATH = r"snippetscript-37175-firebase-adminsdk-cf1z8-7d509b09fd.json"
96
 
97
- # Global variable to track the last entry ID
 
 
 
 
 
 
98
  last_entry_id = None
99
 
100
- def initialize_firebase():
101
- """Initialize Firebase connection"""
102
- try:
103
- # Initialize Firebase app (only once)
104
- cred = credentials.Certificate(FIREBASE_CREDENTIALS_PATH)
105
- firebase_admin.initialize_app(cred)
106
-
107
- # Create Firestore client
108
- return firestore.client()
109
- except Exception as e:
110
- print(f"Firebase initialization error: {e}")
111
- return None
112
 
 
 
113
  def fetch_thingspeak_data():
114
- """Fetch data from ThingSpeak"""
115
  global last_entry_id
116
  try:
117
- url = f"https://api.thingspeak.com/channels/2784385/feeds.json?api_key=P54KXM40TA3CB6W4"
118
  response = requests.get(url)
119
- response.raise_for_status() # Raise an exception for bad responses
120
  data = response.json()
121
-
122
- # Check if there are feeds
123
- if not data.get('feeds'):
124
  print("No new feeds found.")
125
  return None
126
-
127
- # Get the latest feed
128
- latest_feed = data['feeds'][-1]
129
-
130
- # Check if this is a new entry
131
- current_entry_id = latest_feed.get('entry_id')
132
-
133
  if current_entry_id != last_entry_id:
134
  last_entry_id = current_entry_id
135
  return latest_feed
136
-
137
  print("No new entries since last check.")
138
  return None
139
-
140
  except requests.RequestException as e:
141
  print(f"ThingSpeak data fetch error: {e}")
142
  return None
143
 
144
- def store_data_in_firestore(firestore_client, data):
145
 
146
- """Store data in Firestore"""
 
147
  try:
148
- # Validate data
149
  if not data:
150
  print("No data to store.")
151
  return
152
-
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
  }
159
-
160
- # Add to Firestore collection
161
- firestore_client.collection('thingspeak_data').add(doc_data)
162
  print("New data successfully stored in Firestore")
163
  except Exception as e:
164
  print(f"Firestore storage error: {e}")
165
 
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:
178
- # Fetch data from ThingSpeak
179
- thingspeak_data = fetch_thingspeak_data()
180
-
181
- if thingspeak_data:
182
- # Store data in Firestore only if there's a new entry
183
- store_data_in_firestore(firestore_client, thingspeak_data)
184
-
185
- # Wait before next iteration
186
- time.sleep(5) # Adjust interval as needed
187
-
188
- except KeyboardInterrupt:
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)
 
 
1
  import os
2
+ import time
3
+ import requests
4
  import firebase_admin
5
  from firebase_admin import credentials, firestore
6
+ from flask import Flask, render_template
 
 
 
 
7
  from twilio.rest import Client
8
 
9
+ # Flask App Initialization
10
+ app = Flask(__name__)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
+ # Firebase Configuration
13
+ FIREBASE_CREDENTIALS_PATH = "snippetscript-37175-firebase-adminsdk-cf1z8-7d509b09fd.json"
14
  THINGSPEAK_API_KEY = "P54KXM40TA3CB6W4"
15
  CHANNEL_ID = "2784385"
 
16
 
17
+ # Twilio Configuration
18
+ ACCOUNT_SID = "AC97ad50edcf94fdd7d4576be9651bf4bf"
19
+ AUTH_TOKEN = "6d8b2559ffbbdbc5d06542e545220aaa"
20
+ FROM_PHONE = "+12708175529"
21
+ TO_PHONE = "+916382792828"
22
+
23
+ # Global Variable
24
  last_entry_id = None
25
 
26
+ # Firebase Initialization
27
+ cred = credentials.Certificate(FIREBASE_CREDENTIALS_PATH)
28
+ firebase_admin.initialize_app(cred)
29
+ db = firestore.client()
 
 
 
 
 
 
 
 
30
 
31
+
32
+ # Function to Fetch Data from ThingSpeak
33
  def fetch_thingspeak_data():
 
34
  global last_entry_id
35
  try:
36
+ url = f"https://api.thingspeak.com/channels/{CHANNEL_ID}/feeds.json?api_key={THINGSPEAK_API_KEY}"
37
  response = requests.get(url)
38
+ response.raise_for_status()
39
  data = response.json()
40
+
41
+ if not data.get("feeds"):
 
42
  print("No new feeds found.")
43
  return None
44
+
45
+ latest_feed = data["feeds"][-1]
46
+ current_entry_id = latest_feed.get("entry_id")
47
+
 
 
 
48
  if current_entry_id != last_entry_id:
49
  last_entry_id = current_entry_id
50
  return latest_feed
51
+
52
  print("No new entries since last check.")
53
  return None
 
54
  except requests.RequestException as e:
55
  print(f"ThingSpeak data fetch error: {e}")
56
  return None
57
 
 
58
 
59
+ # Function to Store Data in Firestore
60
+ def store_data_in_firestore(data):
61
  try:
 
62
  if not data:
63
  print("No data to store.")
64
  return
65
+
 
66
  doc_data = {
67
+ "field1": data.get("field1"),
68
+ "field2": data.get("field2"),
69
+ "entry_id": data.get("entry_id"),
70
+ "timestamp": firestore.SERVER_TIMESTAMP,
71
  }
72
+
73
+ db.collection("thingspeak_data").add(doc_data)
 
74
  print("New data successfully stored in Firestore")
75
  except Exception as e:
76
  print(f"Firestore storage error: {e}")
77
 
78
 
79
+ # Function to Send SMS via Twilio
80
+ def send_sms(field1, suggestion):
81
+ client = Client(ACCOUNT_SID, AUTH_TOKEN)
82
+ try:
83
+ message = client.messages.create(
84
+ from_=FROM_PHONE,
85
+ body=f"""Test Results:
86
+ E.coli Level: {field1} CFU/mL
87
+ Status: {"Safe" if float(field1) <= 0 else "Unsafe"}
88
+ Suggestions: {suggestion}""",
89
+ to=TO_PHONE,
90
+ )
91
+ print(f"Message sent successfully! SID: {message.sid}")
92
+ except Exception as e:
93
+ print(f"Twilio message send error: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
 
95
 
96
+ # Firestore Listener
97
+ def on_firestore_snapshot(doc_snapshot, changes, read_time):
98
+ for change in changes:
99
+ if change.type.name == "ADDED":
100
+ new_data = change.document.to_dict()
101
+ field1 = new_data.get("field1")
102
+ if field1 is None:
103
+ print("field1 is missing in the document.")
104
+ continue
105
+
106
+ print(f"New Firestore Data: {new_data}")
107
+
108
+ # Logic for sending SMS based on field1 value
109
+ if float(field1) <= 0:
110
+ send_sms(field1, "The water is safe for use.")
111
+ else:
112
+ send_sms(
113
+ field1,
114
+ "You may boil the water to 50°C to eradicate bacteria.",
115
+ )
116
 
117
 
118
+ # Start Firestore Listener
119
+ def start_firestore_listener():
120
+ thingspeak_ref = db.collection("thingspeak_data")
121
+ thingspeak_ref.on_snapshot(on_firestore_snapshot)
122
 
123
 
124
+ @app.route("/")
125
+ def index():
126
+ return render_template("index.html")
127
 
128
 
129
+ @app.route("/admin")
130
+ def admin():
131
+ return render_template("admin.html")
132
 
133
 
134
+ # Background Loop for ThingSpeak Data Fetch
135
+ def fetch_and_store_thingspeak_data():
136
+ global last_entry_id
137
 
138
+ while True:
139
+ thingspeak_data = fetch_thingspeak_data()
140
+ if thingspeak_data:
141
+ store_data_in_firestore(thingspeak_data)
142
+ time.sleep(5) # Fetch data every 5 seconds
143
 
144
 
145
+ if __name__ == "__main__":
146
+ # Start Firestore Listener in a Background Thread
147
+ start_firestore_listener()
148
 
149
+ # Start Flask App
150
+ app.run(host="0.0.0.0", port=7860, debug=True)