from flask import Flask, request, jsonify import pandas as pd import numpy as np import requests import pickle from datetime import datetime import os import tempfile from flask_cors import CORS app = Flask(__name__) CORS(app, resources={r"/*": {"origins": "*"}}) # Store models in memory instead of files wind_model = None wind_scaler = None solar_model = None solar_scaler = None # Create a temporary directory that's definitely writable TEMP_DIR = tempfile.mkdtemp() def download_model_file(url, model_name): """ Download a model file from Hugging Face directly into memory """ try: print(f"Downloading {model_name} from {url}...") response = requests.get(url) if response.status_code == 200: # Return the content directly instead of saving to file return response.content else: print(f"Failed to download {model_name}: Status code {response.status_code}") return None except Exception as e: print(f"Error downloading {model_name}: {str(e)}") return None def load_models(): """ Load wind and solar models and their corresponding scalers. Downloads model files from Hugging Face directly into memory. """ global wind_model, wind_scaler, solar_model, solar_scaler try: # URLs to your Hugging Face model files model_urls = { "wind_model": "https://huggingface.co/PradeepSahu/RenewableEnergy/resolve/main/wind_model.pkl", "wind_scaler": "https://huggingface.co/PradeepSahu/RenewableEnergy/resolve/main/wind_scaler.pkl", "solar_model": "https://huggingface.co/PradeepSahu/RenewableEnergy/resolve/main/solar_model.pkl", "solar_scaler": "https://huggingface.co/PradeepSahu/RenewableEnergy/resolve/main/solar_scaler.pkl" } # Download each model directly into memory model_contents = {} for model_name, url in model_urls.items(): content = download_model_file(url, model_name) if content: model_contents[model_name] = content else: print(f"Failed to download {model_name}") return False # Load models from memory wind_model = pickle.loads(model_contents["wind_model"]) wind_scaler = pickle.loads(model_contents["wind_scaler"]) print("✅ Wind model and scaler loaded successfully") solar_model = pickle.loads(model_contents["solar_model"]) solar_scaler = pickle.loads(model_contents["solar_scaler"]) print("✅ Solar model and scaler loaded successfully") return True except Exception as e: print(f"❌ Error loading models: {str(e)}") return False @app.before_request def before_request_func(): global wind_model, solar_model if wind_model is None or solar_model is None: load_models() def process_weather_data(data): """Process weather API data and create features for models""" latitude = data['latitude'] longitude = data['longitude'] elevation = data.get('elevation', 0) hourly_data = { 'timestamp': data['hourly']['time'], 'temperature': data['hourly']['temperature_2m'], 'wind_speed': data['hourly']['wind_speed_10m'], 'direct_radiation': data['hourly']['direct_radiation'], 'shortwave_radiation_instant': data['hourly']['shortwave_radiation_instant'] } df = pd.DataFrame(hourly_data) df['timestamp'] = pd.to_datetime(df['timestamp'], unit='s') df['hour'] = df['timestamp'].dt.hour df['day_of_year'] = df['timestamp'].dt.dayofyear df['month'] = df['timestamp'].dt.month df['year'] = df['timestamp'].dt.year df['season'] = df['month'] % 12 // 3 + 1 df['latitude'] = latitude df['longitude'] = longitude df['elevation'] = elevation df = calculate_energy_potential(df) df = engineer_features(df) return df def calculate_energy_potential(df): """Calculate theoretical energy potential for wind and solar""" air_density = 1.225 wind_turbine_efficiency = 0.35 swept_area_per_sqkm = 2000 if 'elevation' in df.columns: elevation_factor = 1 - 0.012 * (df['elevation'] / 100) air_density = air_density * elevation_factor.iloc[0] df['wind_energy_potential'] = 0.5 * air_density * swept_area_per_sqkm * wind_turbine_efficiency * df['wind_speed']**3 / 1000 panel_efficiency = 0.2 panel_area_per_sqkm = 300000 if 'latitude' in df.columns and 'month' in df.columns and 'hour' in df.columns: latitude_rad = np.radians(abs(df['latitude'].iloc[0])) df['declination'] = 23.45 * np.sin(np.radians(360/365 * (df['day_of_year'] - 81))) hour_angle = (df['hour'] - 12) * 15 hour_angle_rad = np.radians(hour_angle) declination_rad = np.radians(df['declination']) df['solar_elevation'] = np.arcsin( np.sin(latitude_rad) * np.sin(declination_rad) + np.cos(latitude_rad) * np.cos(declination_rad) * np.cos(hour_angle_rad) ) df['solar_elevation_deg'] = np.degrees(df['solar_elevation']).clip(0) df['solar_factor'] = np.sin(df['solar_elevation']).clip(0) else: df['solar_factor'] = 1.0 if 'direct_radiation' in df.columns: df['solar_energy_direct'] = df['direct_radiation'] * df['solar_factor'] * panel_area_per_sqkm * panel_efficiency / 1000 if 'shortwave_radiation_instant' in df.columns: df['solar_energy_shortwave'] = df['shortwave_radiation_instant'] * df['solar_factor'] * panel_area_per_sqkm * panel_efficiency * 0.9 / 1000 solar_cols = [col for col in df.columns if col.startswith('solar_energy_')] if solar_cols: df['solar_energy_potential'] = df[solar_cols].sum(axis=1) df['combined_energy_potential'] = df['wind_energy_potential'] + df['solar_energy_potential'] return df def engineer_features(df): """Create additional features for models""" if 'wind_speed' in df.columns: df['wind_speed_squared'] = df['wind_speed']**2 df['wind_speed_cubed'] = df['wind_speed']**3 if 'temperature' in df.columns: df['temp_above_25'] = np.maximum(0, df['temperature'] - 25) df['temp_below_0'] = np.maximum(0, -df['temperature']) if 'wind_speed' in df.columns and 'temperature' in df.columns: df['wind_temp_interaction'] = df['wind_speed'] * df['temperature'] if 'direct_radiation' in df.columns and 'hour' in df.columns: df['radiation_hour_effect'] = df['direct_radiation'] * np.sin(np.pi * df['hour'] / 24) if 'hour' in df.columns: df['is_daytime'] = ((df['hour'] >= 6) & (df['hour'] <= 18)).astype(int) if 'wind_speed' in df.columns and 'day_of_year' in df.columns: df['seasonal_wind'] = df['wind_speed'] * np.sin(2 * np.pi * df['day_of_year'] / 365) df = df.fillna(method='ffill') return df def make_predictions(df): """Use models to predict wind and solar energy production""" global wind_model, wind_scaler, solar_model, solar_scaler exclude_cols = [ 'timestamp', 'wind_energy_potential', 'solar_energy_potential', 'combined_energy_potential', 'solar_energy_direct', 'solar_energy_shortwave', 'declination', 'solar_elevation', 'solar_elevation_deg', 'solar_factor' ] features = [col for col in df.columns if col not in exclude_cols] constant_columns = [] for col in features: if df[col].nunique() == 1: constant_columns.append(col) if constant_columns: features = [col for col in features if col not in constant_columns] predictions = {} try: if wind_model is not None and wind_scaler is not None: X_wind = df[features].copy() X_wind_scaled = wind_scaler.transform(X_wind) wind_predictions = wind_model.predict(X_wind_scaled) df['wind_energy_prediction'] = np.maximum(0, wind_predictions) else: df['wind_energy_prediction'] = df['wind_energy_potential'] if solar_model is not None and solar_scaler is not None: X_solar = df[features].copy() X_solar_scaled = solar_scaler.transform(X_solar) solar_predictions = solar_model.predict(X_solar_scaled) df['solar_energy_prediction'] = np.maximum(0, solar_predictions) else: df['solar_energy_prediction'] = df['solar_energy_potential'] df['combined_energy_prediction'] = df['wind_energy_prediction'] + df['solar_energy_prediction'] predictions = { 'wind_energy_prediction': df['wind_energy_prediction'].tolist(), 'solar_energy_prediction': df['solar_energy_prediction'].tolist(), 'combined_energy_prediction': df['combined_energy_prediction'].tolist() } except Exception as e: print(f"Error making predictions: {str(e)}") predictions = { 'wind_energy_prediction': df['wind_energy_potential'].tolist(), 'solar_energy_prediction': df['solar_energy_potential'].tolist(), 'combined_energy_prediction': df['combined_energy_potential'].tolist() } return predictions @app.route('/predict', methods=['GET']) def predict(): """API endpoint for energy predictions based on location""" try: latitude = request.args.get('latitude', type=float) longitude = request.args.get('longitude', type=float) if latitude is None or longitude is None: return jsonify({ 'error': 'Missing required parameters. Please provide latitude and longitude.' }), 400 # today = datetime.now().strftime('%Y-%m-%d') # api_url = f"https://api.open-meteo.com/v1/forecast?latitude={latitude}&longitude={longitude}&hourly=temperature_2m,wind_speed_10m,direct_radiation,shortwave_radiation_instant&daily=daylight_duration&timeformat=unixtime&timezone=auto&forecast_days=14&start_date={today}" today = datetime.now().strftime('%Y-%m-%d') end_date = (datetime.now() + pd.Timedelta(days=13)).strftime('%Y-%m-%d') api_url = f"https://api.open-meteo.com/v1/forecast?latitude={latitude}&longitude={longitude}&hourly=temperature_2m,wind_speed_10m,direct_radiation,shortwave_radiation_instant&daily=daylight_duration&timeformat=unixtime&timezone=IST&start_date={today}&end_date={end_date}" response = requests.get(api_url) if response.status_code != 200: return jsonify({ 'error': f'Failed to fetch weather data. API returned status code {response.status_code}' }), 500 weather_data = response.json() processed_data = process_weather_data(weather_data) predictions = make_predictions(processed_data) processed_data['wind_energy_prediction'] = predictions['wind_energy_prediction'] processed_data['solar_energy_prediction'] = predictions['solar_energy_prediction'] processed_data['combined_energy_prediction'] = predictions['combined_energy_prediction'] result = { 'metadata': { 'latitude': latitude, 'longitude': longitude, 'elevation': weather_data.get('elevation', 0), 'timezone': weather_data.get('timezone', 'UTC'), 'forecast_days': 14, 'generated_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S UTC') }, 'hourly': { 'time': weather_data['hourly']['time'], 'formatted_time': [datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') for ts in weather_data['hourly']['time']], 'temperature': weather_data['hourly']['temperature_2m'], 'wind_speed': weather_data['hourly']['wind_speed_10m'], 'direct_radiation': weather_data['hourly']['direct_radiation'], 'shortwave_radiation': weather_data['hourly']['shortwave_radiation_instant'], 'wind_energy': predictions['wind_energy_prediction'], 'solar_energy': predictions['solar_energy_prediction'], 'combined_energy': predictions['combined_energy_prediction'] } } processed_data['date'] = processed_data['timestamp'].dt.date daily_summary = processed_data.groupby('date').agg({ 'wind_energy_prediction': 'mean', 'solar_energy_prediction': 'mean', 'combined_energy_prediction': 'mean' }).reset_index() result['daily'] = { 'date': [d.strftime('%Y-%m-%d') for d in daily_summary['date']], 'wind_energy_avg': daily_summary['wind_energy_prediction'].tolist(), 'solar_energy_avg': daily_summary['solar_energy_prediction'].tolist(), 'combined_energy_avg': daily_summary['combined_energy_prediction'].tolist() } return jsonify(result) except Exception as e: return jsonify({ 'error': f'An error occurred: {str(e)}' }), 500 @app.route('/health', methods=['GET']) def health_check(): """Health check endpoint""" global wind_model, solar_model models_loaded = (wind_model is not None and solar_model is not None) return jsonify({ 'status': "healthy" if models_loaded else "degraded", 'models_loaded': models_loaded, 'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S UTC') }) if __name__ == '__main__': # Load models at startup load_models() # Get port from environment variable or use default port = int(os.environ.get('PORT', 7860)) app.run(host='0.0.0.0', port=port)