import os import folium from flask import Flask, render_template, jsonify, request, redirect, url_for, session import firebase_admin from firebase_admin import credentials, firestore import pickle # Initialize Flask app app = Flask(__name__) app.secret_key = os.urandom(24) # For session management cred = credentials.Certificate({ "type": "service_account", "project_id": "snippetscript-37175", "private_key_id": "7d509b09fd4ba89f490e0d76a6aa69bf12750739", "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", "client_email": "firebase-adminsdk-cf1z8@snippetscript-37175.iam.gserviceaccount.com", "client_id": "103525651848757260255", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-cf1z8%40snippetscript-37175.iam.gserviceaccount.com", "universe_domain": "googleapis.com" }) firebase_admin.initialize_app(cred) db = firestore.client() @app.route('/') def index(): return render_template('index.html') @app.route('/user-dashboard.html') def user_dashboard(): return render_template('user-dashboard.html') @app.route('/get-previous-results', methods=['GET']) def get_previous_results(): try: # Simulating a ThingSpeak API call or shared data # response = requests.get("https://api.thingspeak.com/...", params=...) # thingspeak_data = response.json() # Returning shared data for all users return jsonify({"status": "success", "data": thingspeak_data}) except Exception as e: return jsonify({"status": "error", "message": str(e)}) # @app.route('/login', methods=['POST']) # def login(): # phone = request.form['loginPhone'] # password = request.form['loginPassword'] # # Query Firestore to find user # users_ref = db.collection('users') # query = users_ref.where('phone', '==', phone).where('password', '==', password) # try: # users = query.stream() # user_list = list(users) # if len(user_list) > 0: # # User found, start session # session['user_phone'] = phone # return redirect(url_for('user_dashboard')) # else: # return "Invalid credentials", 401 # except Exception as e: # return str(e), 500 # @app.route('/dashboard') # def user_dashboard(): # if 'user_phone' not in session: # return redirect(url_for('index')) # # Fetch user details from Firestore # user_ref = db.collection('users').document(session['user_phone']) # user = user_ref.get() # if user.exists: # user_data = user.to_dict() # return render_template('user-dashboard.html', user=user_data) # else: # return "User not found", 404 # @app.route('/admin.html') # def admin(): # return render_template('admin.html') @app.route('/admin.html') def admin(): # Create a map centered on Delhi delhi_coordinates = [28.6139, 77.2090] folium_map = folium.Map(location=delhi_coordinates, zoom_start=12) # Add predefined markers in Delhi markers = [ {"name": "India Gate", "coordinates": [28.6129, 77.2295]}, {"name": "Red Fort", "coordinates": [28.6562, 77.2410]}, {"name": "Qutub Minar", "coordinates": [28.5245, 77.1855]}, ] # Add markers to the map for marker in markers: folium.Marker( location=marker["coordinates"], popup=marker["name"], icon=folium.Icon(color="blue", icon="info-sign"), ).add_to(folium_map) # Use a valid Folium tile layer folium.TileLayer('OpenStreetMap').add_to(folium_map) # Add Layer Control for toggling between tile layers folium.LayerControl().add_to(folium_map) # Generate the map HTML map_html = folium_map._repr_html_() # Render the template with the map return render_template('admin.html', map=map_html) @app.route('/logout') def logout(): # Remove the user's phone number from the session session.pop('user_phone', None) # Redirect to the index route (function name, not the file name) return redirect(url_for('index')) from twilio.rest import Client import firebase_admin from firebase_admin import credentials, firestore # Twilio Configuration ACCOUNT_SID = 'AC97ad50edcf94fdd7d4576be9651bf4bf' AUTH_TOKEN = '6d8b2559ffbbdbc5d06542e545220aaa' FROM_PHONE = '+12708175529' TO_PHONE = '+916382792828' import numpy as np import joblib # Save model using joblib # Load model using joblib with open('model.pkl','rb') as f: loaded_model=pickle.load( f) def predict_conc(pdiff): if pdiff>3.19: return 0 pdiff_value = pdiff # Replace 1.5 with your input value 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}" # Function to send SMS using Twilio def send_msg(field1,suggestion): # if field;1 client = Client(ACCOUNT_SID, AUTH_TOKEN) try: message = client.messages.create( from_=FROM_PHONE, body=f"""Test Results:\nE.coli Level: {field1} CFU/mL. Status: safe Suggestions:\n {suggestion}""", to=TO_PHONE ) print(f"Message sent successfully! SID: {message.sid}") except Exception as e: print(f"Failed to send message: {e}") # Firestore Listener for new data in the 'thingspeak_data' collection def on_snapshot(doc_snapshot, changes, read_time): for change in changes: if change.type.name == 'ADDED': # Detects new documents added to the collection new_data = change.document.to_dict() field1 = new_data.get('field1', 'N/A') # Replace 'field1' with your actual field key print(f"New data detected: {new_data}") concentration=predict_conc(field1) if concentration==0: send_msg(0,"The water is safe for use!!") else: send_msg(concentration,"You may boil the water to 50°C to eradicate the bacteria.") # Trigger the Twilio SMS function # Initialize Firestore Listener def start_firestore_listener(): thingspeak_ref = db.collection('thingspeak_data') thingspeak_watch = thingspeak_ref.on_snapshot(on_snapshot) print("Listening for new data in Firestore...") if __name__ == '__main__': app.run(host='0.0.0.0', port=7860, debug=True)