from flask import Flask, request, jsonify from flask_cors import CORS import pickle import pandas as pd # Importing the dataset # df = pd.read_csv('dataset/weather_dataset.csv') labels = {'Cloudy': 0, 'Rain': 1, 'Clear': 2, 'Thunderstorm': 3, 'Haze': 4, 'Mist': 5, 'Fog': 6, 'Smoke': 7} column_mapping = {value: idx for idx, value in enumerate(labels)} # Create a function that allows for adding new data to the model def predict_weather_from_sensors(modelName, temp, humidity, visibility, clouds): """ Predict weather using sensor data Parameters: temp (float): Temperature in Celsius humidity (float): Humidity percentage (0-100) visibility (float): Visibility (0-100) clouds (float): Cloud coverage percentage (0-100) Returns: str: Predicted weather condition """ # Create a DataFrame with the sensor data new_data = pd.DataFrame({ 'main.temp': [temp], 'main.humidity': [humidity], 'visibility': [visibility], 'clouds.all': [clouds] }) # # Load the saved model with open(modelName, 'rb') as f: model_data = pickle.load(f) # Get prediction prediction = model_data['model'].predict(new_data)[0] # Convert numeric prediction back to weather condition reverse_mapping = {v: k for k, v in column_mapping.items()} weather_condition = reverse_mapping[prediction] return weather_condition app = Flask(__name__) MAX_SENSOR_VALUE = 1023 weather = '' temperature = 0 humidity = 0 photores = 0 clouds = 0 # Enable CORS for all routes CORS(app, origins=["http://192.168.1.1"]) @app.route('/sensor/data', methods=['POST']) def receive_data(): # Getting the data from the URL-encoded form global temperature, humidity, photores, weather, clouds temperature = float(request.form.get('temperature')) humidity = float(request.form.get('humidity')) photores = request.form.get('light_sensor') # Processing the light so that it remains within the 100% mark photores = round((int(photores) / MAX_SENSOR_VALUE) * 100, 2) # Calculating the clouds probability based on the photores value clouds = round((1 - (photores / MAX_SENSOR_VALUE)) * 100, 2) # Gives a value based on the coverage of the clouds compared to the sunlight received # If no data is received, we can return an error response if not temperature or not humidity or not photores: return jsonify({"error": "Missing data"}), 400 weather = predict_weather_from_sensors('weather_predictor.pkl', temperature, humidity, photores, clouds) # Print the received data print(f"Temperature: {temperature}, Humidity: {humidity}, Light: {photores}") print(f"The weather today is: {weather}") # Respond with a success message and a 200 OK status return jsonify({"message": "Data received successfully"}), 200 # Create an endpoint here cause I want to @app.route('/weather', methods=['GET']) def send_data(): # Return the predicted weather return jsonify({ "temperature": temperature, "humidity": humidity, "light": photores, "clouds": clouds, "weather": weather }), 200 if __name__ == '__main__': app.run(host='0.0.0.0', port=6969, debug=True)