Spaces:
Sleeping
Sleeping
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 | |
# Initialize Flask app | |
app = Flask(__name__) | |
app.secret_key = os.urandom(24) # For session management | |
# Initialize Firebase | |
# try: | |
# firebase_admin.get_app() | |
# except ValueError: | |
# cred = credentials.Certificate({ | |
# "type": "service_account", | |
# "project_id": "snippetscript-37175", | |
# "private_key_id": "your_private_key_id", | |
# "private_key": "your_private_key", | |
# "client_email": "your_client_email", | |
# "client_id": "your_client_id", | |
# "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": "your_cert_url" | |
# }) | |
# firebase_admin.initialize_app(cred) | |
# Initialize Firestore | |
# db = firestore.client() | |
def index(): | |
return render_template('index.html') | |
def user_dashboard(): | |
return render_template('user-dashboard.html') | |
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') | |
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) | |
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 | |
loaded_model = joblib.load('dlmodel.joblib') | |
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}" | |
# Firebase Configuration | |
cred = credentials.Certificate("snippetscript-37175-firebase-adminsdk-cf1z8-7d509b09fd.json") | |
firebase_admin.initialize_app(cred) | |
db = firestore.client() | |
# 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(concentration,"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) |