Spaces:
Sleeping
Sleeping
import os | |
import time | |
import requests | |
import pickle | |
import numpy as np | |
from flask import Flask, render_template, redirect, url_for, session | |
import firebase_admin | |
from firebase_admin import credentials, firestore | |
from twilio.rest import Client | |
# Initialize Flask app | |
app = Flask(__name__) | |
app.secret_key = os.urandom(24) # For session management | |
# Firebase Admin SDK initialization | |
FIREBASE_CREDENTIALS_PATH = r"snippetscript-37175-firebase-adminsdk-cf1z8-7d509b09fd.json" | |
cred = credentials.Certificate("snippetscript-37175-firebase-adminsdk-cf1z8-7d509b09fd.json") | |
firebase_admin.initialize_app(cred) | |
# Firestore client | |
db = firestore.client() | |
# Twilio Configuration | |
ACCOUNT_SID = 'AC97ad50edcf94fdd7d4576be9651bf4bf' | |
AUTH_TOKEN = '6d8b2559ffbbdbc5d06542e545220aaa' | |
FROM_PHONE = '+12708175529' | |
TO_PHONE = '+916382792828' | |
# Load model using pickle | |
with open('model.pkl', 'rb') as f: | |
loaded_model = pickle.load(f) | |
def predict_conc(pdiff): | |
try: | |
if pdiff > 3.19: | |
return 0 | |
pdiff_value = pdiff # Input for "Average Potential Difference" | |
new_data = np.array([[pdiff_value]]) | |
prediction = loaded_model.predict(new_data) | |
concentration = 10**prediction[0] # Reverse log transformation | |
return f"{concentration:.4f}" | |
except Exception as e: | |
print(f"Error in predict_conc: {e}") | |
return None | |
def send_msg(field1, suggestion): | |
client = Client(ACCOUNT_SID, AUTH_TOKEN) | |
try: | |
message = client.messages.create( | |
from_=FROM_PHONE, | |
body=f"""Test Results:\nE.coli Level: {field1} CFU/mL.\nStatus: {'safe' if field1 == 0 else 'unsafe'}\nSuggestions:\n{suggestion}""", | |
to=TO_PHONE | |
) | |
print(f"Message sent successfully! SID: {message.sid}") | |
except Exception as e: | |
print(f"Failed to send message: {e}") | |
def on_snapshot(doc_snapshot, changes, read_time): | |
for change in changes: | |
if change.type.name == 'ADDED': | |
new_data = change.document.to_dict() | |
field1 = new_data.get('field1') | |
if field1 is None: | |
print("field1 is missing in the document.") | |
continue | |
print(f"New data detected: {new_data}") | |
concentration = predict_conc(float(field1)) | |
if concentration == "0": | |
send_msg(0, "The water is safe for use!!") | |
else: | |
send_msg(concentration, "You may boil the water to 50\u00b0C to eradicate the bacteria.") | |
def start_firestore_listener(): | |
try: | |
thingspeak_ref = db.collection('thingspeak_data') | |
thingspeak_ref.on_snapshot(on_snapshot) | |
print("Firestore listener started.") | |
except Exception as e: | |
print(f"Error starting Firestore listener: {e}") | |
def index(): | |
return render_template('index.html') | |
def logout(): | |
session.pop('user_phone', None) | |
return redirect(url_for('index')) | |
import requests | |
import firebase_admin | |
from firebase_admin import credentials, firestore | |
import time | |
# Replace with your actual credentials | |
THINGSPEAK_API_KEY = "P54KXM40TA3CB6W4" | |
CHANNEL_ID = "2784385" | |
FIREBASE_CREDENTIALS_PATH = r"snippetscript-37175-firebase-adminsdk-cf1z8-7d509b09fd.json" | |
# Global variable to track the last entry ID | |
last_entry_id = None | |
def initialize_firebase(): | |
"""Initialize Firebase connection""" | |
try: | |
# Initialize Firebase app (only once) | |
cred = credentials.Certificate(FIREBASE_CREDENTIALS_PATH) | |
firebase_admin.initialize_app(cred) | |
# Create Firestore client | |
return firestore.client() | |
except Exception as e: | |
print(f"Firebase initialization error: {e}") | |
return None | |
def fetch_thingspeak_data(): | |
"""Fetch data from ThingSpeak""" | |
global last_entry_id | |
try: | |
url = f"https://api.thingspeak.com/channels/2784385/feeds.json?api_key=P54KXM40TA3CB6W4" | |
response = requests.get(url) | |
response.raise_for_status() # Raise an exception for bad responses | |
data = response.json() | |
# Check if there are feeds | |
if not data.get('feeds'): | |
print("No new feeds found.") | |
return None | |
# Get the latest feed | |
latest_feed = data['feeds'][-1] | |
# Check if this is a new entry | |
current_entry_id = latest_feed.get('entry_id') | |
if current_entry_id != last_entry_id: | |
last_entry_id = current_entry_id | |
return latest_feed | |
print("No new entries since last check.") | |
return None | |
except requests.RequestException as e: | |
print(f"ThingSpeak data fetch error: {e}") | |
return None | |
def store_data_in_firestore(firestore_client, data): | |
"""Store data in Firestore""" | |
try: | |
# Validate data | |
if not data: | |
print("No data to store.") | |
return | |
# Create a document with timestamp | |
doc_data = { | |
'field1': data.get('field1'), | |
'field2': data.get('field2'), | |
'entry_id': data.get('entry_id'), | |
'timestamp': firestore.SERVER_TIMESTAMP | |
} | |
# Add to Firestore collection | |
firestore_client.collection('thingspeak_data').add(doc_data) | |
print("New data successfully stored in Firestore") | |
except Exception as e: | |
print(f"Firestore storage error: {e}") | |
firestore_client = initialize_firebase() | |
if not firestore_client: | |
print("Failed to initialize Firestore. Exiting.") | |
# Main data collection loop | |
try: | |
while True: | |
# Fetch data from ThingSpeak | |
thingspeak_data = fetch_thingspeak_data() | |
if thingspeak_data: | |
# Store data in Firestore only if there's a new entry | |
store_data_in_firestore(firestore_client, thingspeak_data) | |
# Wait before next iteration | |
time.sleep(5) # Adjust interval as needed | |
except KeyboardInterrupt: | |
print("Data collection stopped by user.") | |
except Exception as e: | |
print(f"Unexpected error: {e}") | |
start_firestore_listener() | |
if __name__ == '__main__': | |
app.run(host='0.0.0.0', port=7860, debug=True) | |