Neurolingua commited on
Commit
09a71ce
·
verified ·
1 Parent(s): 8226f54

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -87
app.py CHANGED
@@ -1,10 +1,11 @@
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
  from twilio.rest import Client
9
 
10
  # Initialize Flask app
@@ -12,20 +13,10 @@ 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",
18
- "private_key_id": "7d509b09fd4ba89f490e0d76a6aa69bf12750739",
19
- "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/dn7oPmYMtbufrMsdn9eb4JQf1PR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-37175.iam.gserviceaccount.com",
21
- "client_id": "103525651848757260255",
22
- "auth_uri": "https://accounts.google.com/o/oauth2/auth",
23
- "token_uri": "https://oauth2.googleapis.com/token",
24
- "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
25
- "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-cf1z8%40snippetscript-37175.iam.gserviceaccount.com",
26
- "universe_domain": "googleapis.com"
27
- })
28
- firebase_admin.initialize_app(cred)
29
 
30
  # Firestore client
31
  db = firestore.client()
@@ -40,6 +31,14 @@ TO_PHONE = '+916382792828'
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:
@@ -53,6 +52,7 @@ def predict_conc(pdiff):
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:
@@ -65,6 +65,7 @@ def send_msg(field1, suggestion):
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':
@@ -77,10 +78,11 @@ def on_snapshot(doc_snapshot, changes, read_time):
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')
@@ -89,82 +91,47 @@ def start_firestore_listener():
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
-
102
-
103
- import requests
104
- import firebase_admin
105
- from firebase_admin import credentials, firestore
106
- import time
107
-
108
- # Replace with your actual credentials
109
- THINGSPEAK_API_KEY = "P54KXM40TA3CB6W4"
110
- CHANNEL_ID = "2784385"
111
- FIREBASE_CREDENTIALS_PATH = r"snippetscript-37175-firebase-adminsdk-cf1z8-7d509b09fd.json"
112
-
113
- # Global variable to track the last entry ID
114
- last_entry_id = None
115
-
116
- def initialize_firebase():
117
- """Initialize Firebase connection"""
118
- try:
119
- # Initialize Firebase app (only once)
120
- cred = credentials.Certificate(FIREBASE_CREDENTIALS_PATH)
121
- firebase_admin.initialize_app(cred)
122
-
123
- # Create Firestore client
124
- return firestore.client()
125
- except Exception as e:
126
- print(f"Firebase initialization error: {e}")
127
- return None
128
 
129
  def fetch_thingspeak_data():
130
  """Fetch data from ThingSpeak"""
131
  global last_entry_id
132
  try:
133
- url = f"https://api.thingspeak.com/channels/2784385/feeds.json?api_key=P54KXM40TA3CB6W4"
134
  response = requests.get(url)
135
  response.raise_for_status() # Raise an exception for bad responses
136
  data = response.json()
137
-
138
  # Check if there are feeds
139
  if not data.get('feeds'):
140
  print("No new feeds found.")
141
  return None
142
-
143
  # Get the latest feed
144
  latest_feed = data['feeds'][-1]
145
-
146
  # Check if this is a new entry
147
  current_entry_id = latest_feed.get('entry_id')
148
-
149
  if current_entry_id != last_entry_id:
150
  last_entry_id = current_entry_id
151
  return latest_feed
152
-
153
  print("No new entries since last check.")
154
  return None
155
-
156
  except requests.RequestException as e:
157
  print(f"ThingSpeak data fetch error: {e}")
158
  return None
159
 
160
- def store_data_in_firestore(firestore_client, data):
 
161
  """Store data in Firestore"""
162
  try:
163
  # Validate data
164
  if not data:
165
  print("No data to store.")
166
  return
167
-
168
  # Create a document with timestamp
169
  doc_data = {
170
  'field1': data.get('field1'),
@@ -172,38 +139,48 @@ def store_data_in_firestore(firestore_client, data):
172
  'entry_id': data.get('entry_id'),
173
  'timestamp': firestore.SERVER_TIMESTAMP
174
  }
175
-
176
  # Add to Firestore collection
177
- firestore_client.collection('thingspeak_data').add(doc_data)
178
  print("New data successfully stored in Firestore")
179
  except Exception as e:
180
  print(f"Firestore storage error: {e}")
181
 
182
 
183
- firestore_client = initialize_firebase()
 
 
184
 
185
- if not firestore_client:
186
- print("Failed to initialize Firestore. Exiting.")
187
- return
188
 
189
- # Main data collection loop
190
- try:
191
- while True:
192
- # Fetch data from ThingSpeak
193
- thingspeak_data = fetch_thingspeak_data()
194
-
195
- if thingspeak_data:
196
- # Store data in Firestore only if there's a new entry
197
- store_data_in_firestore(firestore_client, thingspeak_data)
198
-
199
- # Wait before next iteration
200
- time.sleep(5) # Adjust interval as needed
201
 
202
- except KeyboardInterrupt:
203
- print("Data collection stopped by user.")
204
- except Exception as e:
205
- print(f"Unexpected error: {e}")
206
 
207
  if __name__ == '__main__':
208
- start_firestore_listener()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
209
  app.run(host='0.0.0.0', port=7860, debug=True)
 
1
  import os
2
+ import time
3
+ import requests
 
 
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
 
13
  app.secret_key = os.urandom(24) # For session management
14
 
15
  # Firebase Admin SDK initialization
16
+ FIREBASE_CREDENTIALS_PATH = r"snippetscript-37175-firebase-adminsdk-cf1z8-7d509b09fd.json"
17
+ if not firebase_admin._apps:
18
+ cred = credentials.Certificate(FIREBASE_CREDENTIALS_PATH)
19
+ firebase_admin.initialize_app(cred)
 
 
 
 
 
 
 
 
 
 
20
 
21
  # Firestore client
22
  db = firestore.client()
 
31
  with open('model.pkl', 'rb') as f:
32
  loaded_model = pickle.load(f)
33
 
34
+ # ThingSpeak Configuration
35
+ THINGSPEAK_API_KEY = "P54KXM40TA3CB6W4"
36
+ CHANNEL_ID = "2784385"
37
+
38
+ # Global variable to track the last entry ID
39
+ last_entry_id = None
40
+
41
+
42
  def predict_conc(pdiff):
43
  try:
44
  if pdiff > 3.19:
 
52
  print(f"Error in predict_conc: {e}")
53
  return None
54
 
55
+
56
  def send_msg(field1, suggestion):
57
  client = Client(ACCOUNT_SID, AUTH_TOKEN)
58
  try:
 
65
  except Exception as e:
66
  print(f"Failed to send message: {e}")
67
 
68
+
69
  def on_snapshot(doc_snapshot, changes, read_time):
70
  for change in changes:
71
  if change.type.name == 'ADDED':
 
78
  print(f"New data detected: {new_data}")
79
  concentration = predict_conc(float(field1))
80
  if concentration == "0":
81
+ send_msg(0, "The water is safe for use!")
82
  else:
83
  send_msg(concentration, "You may boil the water to 50\u00b0C to eradicate the bacteria.")
84
 
85
+
86
  def start_firestore_listener():
87
  try:
88
  thingspeak_ref = db.collection('thingspeak_data')
 
91
  except Exception as e:
92
  print(f"Error starting Firestore listener: {e}")
93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
 
95
  def fetch_thingspeak_data():
96
  """Fetch data from ThingSpeak"""
97
  global last_entry_id
98
  try:
99
+ url = f"https://api.thingspeak.com/channels/{CHANNEL_ID}/feeds.json?api_key={THINGSPEAK_API_KEY}"
100
  response = requests.get(url)
101
  response.raise_for_status() # Raise an exception for bad responses
102
  data = response.json()
103
+
104
  # Check if there are feeds
105
  if not data.get('feeds'):
106
  print("No new feeds found.")
107
  return None
108
+
109
  # Get the latest feed
110
  latest_feed = data['feeds'][-1]
111
+
112
  # Check if this is a new entry
113
  current_entry_id = latest_feed.get('entry_id')
114
+
115
  if current_entry_id != last_entry_id:
116
  last_entry_id = current_entry_id
117
  return latest_feed
118
+
119
  print("No new entries since last check.")
120
  return None
121
+
122
  except requests.RequestException as e:
123
  print(f"ThingSpeak data fetch error: {e}")
124
  return None
125
 
126
+
127
+ def store_data_in_firestore(data):
128
  """Store data in Firestore"""
129
  try:
130
  # Validate data
131
  if not data:
132
  print("No data to store.")
133
  return
134
+
135
  # Create a document with timestamp
136
  doc_data = {
137
  'field1': data.get('field1'),
 
139
  'entry_id': data.get('entry_id'),
140
  'timestamp': firestore.SERVER_TIMESTAMP
141
  }
142
+
143
  # Add to Firestore collection
144
+ db.collection('thingspeak_data').add(doc_data)
145
  print("New data successfully stored in Firestore")
146
  except Exception as e:
147
  print(f"Firestore storage error: {e}")
148
 
149
 
150
+ @app.route('/')
151
+ def index():
152
+ return render_template('index.html')
153
 
 
 
 
154
 
155
+ @app.route('/logout')
156
+ def logout():
157
+ session.pop('user_phone', None)
158
+ return redirect(url_for('index'))
 
 
 
 
 
 
 
 
159
 
 
 
 
 
160
 
161
  if __name__ == '__main__':
162
+ # Start the Firestore listener in a separate thread
163
+ import threading
164
+ listener_thread = threading.Thread(target=start_firestore_listener)
165
+ listener_thread.start()
166
+
167
+ # Main data collection loop
168
+ try:
169
+ while True:
170
+ # Fetch data from ThingSpeak
171
+ thingspeak_data = fetch_thingspeak_data()
172
+
173
+ if thingspeak_data:
174
+ # Store data in Firestore only if there's a new entry
175
+ store_data_in_firestore(thingspeak_data)
176
+
177
+ # Wait before next iteration
178
+ time.sleep(5) # Adjust interval as needed
179
+
180
+ except KeyboardInterrupt:
181
+ print("Data collection stopped by user.")
182
+ except Exception as e:
183
+ print(f"Unexpected error: {e}")
184
+
185
+ # Run Flask app
186
  app.run(host='0.0.0.0', port=7860, debug=True)