File size: 6,814 Bytes
5bda095
79c9006
5bda095
 
 
79c9006
5bda095
79c9006
5bda095
 
8f9883c
 
 
5bda095
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79c9006
 
 
 
 
5bda095
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79c9006
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5bda095
 
 
 
 
 
 
 
 
 
59cbdd5
 
 
 
 
 
 
 
 
 
 
9d3d643
59cbdd5
9d3d643
a37ce32
59cbdd5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79c9006
5bda095
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
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()

@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
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)