Spaces:
Sleeping
Sleeping
| from mistralai import Mistral | |
| import numpy as np | |
| import os | |
| import time | |
| import requests | |
| import folium | |
| from flask import Flask, render_template, jsonify, request, redirect, url_for, session | |
| from twilio.rest import Client | |
| import firebase_admin | |
| import pickle | |
| from firebase_admin import credentials, firestore | |
| # Twilio Configuration | |
| ACCOUNT_SID = 'AC7f8c344c6593572a0c925ab4c1b66cc6' | |
| AUTH_TOKEN = 'e5f750f99a87e84ca5b87ddd0c421560' | |
| FROM_PHONE = '+13613093564' | |
| TO_PHONE = '+919080522395' | |
| # Firebase Configuration | |
| FIREBASE_CREDENTIALS_PATH = r"snippetscript-37175-firebase-adminsdk-cf1z8-7d509b09fd.json" | |
| THINGSPEAK_API_KEY = "PIA8Z5BWH2DW6WLF" | |
| CHANNEL_ID = "2785999" | |
| # Global variable to track the last entry ID | |
| last_entry_id = None | |
| # with open(r'C:\Users\tiruv\Desktop\SIH\model.pkl', 'rb') as f: | |
| # loaded_model = pickle.load(f) | |
| def predict_conc(pdiff): | |
| # Reverse log transformation | |
| return pdiff | |
| # Initialize Firebase | |
| cred = credentials.Certificate(FIREBASE_CREDENTIALS_PATH) | |
| firebase_admin.initialize_app(cred) | |
| db = firestore.client() | |
| # Initialize Flask app | |
| app = Flask(__name__) | |
| app.secret_key = os.urandom(24) # For session management | |
| # Function to send SMS using Twilio | |
| def send_msg(doc_id, field1): | |
| try: | |
| field1 = (field1) | |
| # Fetch the document with the given doc_id | |
| doc_ref = db.collection('thingspeak_data').document(doc_id) | |
| doc = doc_ref.get() | |
| if doc.exists: | |
| data = doc.to_dict() | |
| msg_status = data.get('msg_status', 0) | |
| # Check if the message status is 0 | |
| if msg_status == 0: | |
| concen=predict_conc(field1) | |
| client = Client(ACCOUNT_SID, AUTH_TOKEN) | |
| if concen!=0: | |
| sugges="You may heat your water to eradicate the bacteria." | |
| else: | |
| sugges="Your water is safe.It can be used for drinking purpose!." | |
| # Send the message | |
| message = client.messages.create( | |
| from_=FROM_PHONE, | |
| body=f"""E.coli Level: {concen} CFU/mL\nStatus: Safe\nSuggestions:\n{sugges}\n--Ministry of Jal Shakthi.""", | |
| to=TO_PHONE | |
| ) | |
| print(f"Message sent successfully! SID: {message.sid}") | |
| # Update the msg_status to 1 | |
| doc_ref.update({'msg_status': 1}) | |
| print("Message status updated to 1 in Firestore.") | |
| else: | |
| print("Message already sent for this entry. Skipping...") | |
| else: | |
| print(f"No document found with ID: {doc_id}") | |
| except Exception as e: | |
| print(f"Failed to send message or update status: {e}") | |
| # Firestore Listener for new data | |
| def on_snapshot(doc_snapshot, changes, read_time): | |
| for change in changes: | |
| if change.type.name == 'ADDED': | |
| new_data = change.document.to_dict() | |
| print(f"New data detected: {new_data}") # Debugging info | |
| field1 = new_data.get('field1', 'N/A') | |
| try: | |
| field1 = float(field1) # Convert field1 to float | |
| print(f"Field1 as float: {field1}") | |
| send_msg(change.document.id, field1) | |
| except ValueError: | |
| print(f"Invalid field1 value: {field1}. Must be numeric.") | |
| # Firestore Listener Initialization | |
| def start_firestore_listener(): | |
| thingspeak_ref = db.collection('thingspeak_data') | |
| thingspeak_ref.on_snapshot(on_snapshot) | |
| print("Listening for new data in Firestore...") | |
| # Fetch data from ThingSpeak | |
| def fetch_thingspeak_data(): | |
| global last_entry_id | |
| try: | |
| url = f"https://api.thingspeak.com/channels/{CHANNEL_ID}/feeds.json?api_key={THINGSPEAK_API_KEY}" | |
| response = requests.get(url) | |
| response.raise_for_status() | |
| data = response.json() | |
| if not data.get('feeds'): | |
| print("No new feeds found.") | |
| return None | |
| latest_feed = data['feeds'][-1] | |
| 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 | |
| # Store data in Firestore | |
| def store_data_in_firestore(data): | |
| try: | |
| if not data: | |
| print("No data to store.") | |
| return | |
| doc_data = { | |
| 'field1': data.get('field1'), | |
| 'field2': data.get('field2'), | |
| 'entry_id': data.get('entry_id'), | |
| 'msg_status':0, | |
| 'timestamp': firestore.SERVER_TIMESTAMP | |
| } | |
| db.collection('thingspeak_data').add(doc_data) | |
| print("New data successfully stored in Firestore") | |
| except Exception as e: | |
| print(f"Firestore storage error: {e}") | |
| # Flask Routes | |
| def index(): | |
| return render_template('index.html') | |
| def user_dashboard(): | |
| return render_template('user-dashboard.html') | |
| def get_previous_results(): | |
| try: | |
| # Simulate ThingSpeak API call or shared data | |
| data = fetch_thingspeak_data() | |
| return jsonify({"status": "success", "data": data}) | |
| except Exception as e: | |
| return jsonify({"status": "error", "message": str(e)}) | |
| def admin(): | |
| delhi_coordinates = [28.6139, 77.2090] | |
| folium_map = folium.Map(location=delhi_coordinates, zoom_start=12) | |
| 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]}, | |
| ] | |
| for marker in markers: | |
| folium.Marker( | |
| location=marker["coordinates"], | |
| popup=marker["name"], | |
| icon=folium.Icon(color="blue", icon="info-sign"), | |
| ).add_to(folium_map) | |
| folium.TileLayer('OpenStreetMap').add_to(folium_map) | |
| folium.LayerControl().add_to(folium_map) | |
| map_html = folium_map._repr_html_() | |
| return render_template('admin.html', map=map_html) | |
| def logout(): | |
| session.pop('user_phone', None) | |
| return redirect(url_for('index')) | |
| # Main Function for Continuous Data Fetching | |
| def main(): | |
| try: | |
| start_firestore_listener() | |
| while True: | |
| thingspeak_data = fetch_thingspeak_data() | |
| if thingspeak_data: | |
| store_data_in_firestore(thingspeak_data) | |
| time.sleep(5) | |
| except KeyboardInterrupt: | |
| print("Process interrupted by user.") | |
| except Exception as e: | |
| print(f"Unexpected error: {e}") | |
| API_KEY = 'xQ2Zhfsp4cLar4lvBRDWZKljvp0Ej427' | |
| MODEL = "mistral-large-latest" | |
| client = Mistral(api_key=API_KEY) | |
| def chat(): | |
| data = request.json | |
| user_query = data.get("query", "") | |
| if not user_query: | |
| return jsonify({"error": "Query cannot be empty"}), 400 | |
| try: | |
| chat_response = client.chat.complete( | |
| model=MODEL, | |
| messages=[ | |
| {"role": "user", "content": user_query+"You are the best assistant. Provide the precise response within 2 to 3 sentence.Greet the user if user greets.Your response must be rural area people."}, | |
| ] | |
| ) | |
| response_content = chat_response.choices[0].message.content | |
| return jsonify({"response": response_content}) | |
| except Exception as e: | |
| return jsonify({"error": str(e)}), 500 | |
| if __name__ == '__main__': | |
| from threading import Thread | |
| # Run the main data-fetching loop in a separate thread | |
| data_thread = Thread(target=main, daemon=True) | |
| data_thread.start() | |
| # Run Flask app in the main thread with debugging enabled | |
| app.run(host='0.0.0.0', port=7860, debug=True) | |