File size: 14,019 Bytes
4be63b9
 
 
 
 
 
 
072b67a
 
4be63b9
 
 
 
072b67a
4be63b9
 
 
 
 
072b67a
 
4be63b9
072b67a
4be63b9
072b67a
4be63b9
072b67a
 
4be63b9
072b67a
 
 
 
 
 
 
 
 
4be63b9
 
 
 
072b67a
4be63b9
 
 
 
 
 
072b67a
 
 
 
4be63b9
 
072b67a
 
 
 
 
 
 
 
 
 
 
 
 
4be63b9
 
072b67a
 
4be63b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b5d0062
 
4be63b9
b5d0062
 
 
 
340d2bb
4be63b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
072b67a
4be63b9
 
 
 
 
 
 
 
 
 
 
 
 
 
072b67a
4be63b9
 
072b67a
4be63b9
072b67a
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
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)