Bhuvi20 commited on
Commit
a063804
·
verified ·
1 Parent(s): a51e041

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +20 -25
app.py CHANGED
@@ -1,38 +1,33 @@
1
- import os
2
  import torch
3
- from flask import Flask, request, jsonify
4
  import numpy as np
5
- from src.model import LSTM
6
-
7
- # Initialize Flask app
8
- app = Flask(__name__)
9
-
10
- # Device setup
11
- device = 'cuda' if torch.cuda.is_available() else 'cpu'
12
-
13
- # Ensure the model file is available in the environment
14
- model_path = './water_forecast_2.pth'
15
- if not os.path.exists(model_path):
16
- raise FileNotFoundError(f"Model file '{model_path}' not found.")
17
 
18
  # Load the model
 
 
19
  model = LSTM(input_size=8, lstm_layer_sizes=[128, 128, 128], output_size=3).to(device)
20
-
21
- print("Loading model...")
22
  model.load_state_dict(torch.load(model_path, map_location=device))
23
- print("Model loaded successfully")
24
  model.eval()
25
 
26
- @app.route("/predict", methods=["POST"])
27
- def predict_usage():
28
- data = request.get_json()
29
- structured_data = data["structured_data"]
30
  tensor_data = torch.tensor(np.array(list(structured_data.values())), dtype=torch.float32).to(device)
31
-
32
  with torch.no_grad():
33
- outputs = model(tensor_data)
 
 
 
 
 
 
 
 
 
34
 
35
- return jsonify({"prediction": outputs.tolist()})
36
 
 
37
  if __name__ == "__main__":
38
- app.run(debug=True)
 
 
1
  import torch
2
+ import gradio as gr
3
  import numpy as np
4
+ from src.model import LSTM # Adjust to your model path
 
 
 
 
 
 
 
 
 
 
 
5
 
6
  # Load the model
7
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
8
+ model_path = "./water_forecast_2.pth" # Your model path
9
  model = LSTM(input_size=8, lstm_layer_sizes=[128, 128, 128], output_size=3).to(device)
 
 
10
  model.load_state_dict(torch.load(model_path, map_location=device))
 
11
  model.eval()
12
 
13
+ # Define the prediction function
14
+ def predict_water_usage(state_idx, target_year, structured_data):
15
+ # Convert input data to tensor
 
16
  tensor_data = torch.tensor(np.array(list(structured_data.values())), dtype=torch.float32).to(device)
 
17
  with torch.no_grad():
18
+ output = model(tensor_data)
19
+ return output.tolist()
20
+
21
+ # Set up Gradio interface
22
+ inputs = [
23
+ gr.inputs.Number(label="State Index"),
24
+ gr.inputs.Number(label="Target Year"),
25
+ gr.inputs.JSON(label="Structured Data") # Expects JSON input
26
+ ]
27
+ outputs = gr.outputs.JSON(label="Prediction")
28
 
29
+ interface = gr.Interface(fn=predict_water_usage, inputs=inputs, outputs=outputs)
30
 
31
+ # Launch the Gradio app
32
  if __name__ == "__main__":
33
+ interface.launch()