app = Flask(__name__) @app.route("/", methods=['POST','GET']) def index(): if (request.method == "POST"): data = request.form['content'] # run() try: numbers = list(map(lambda x: float(x), data.split(','))) output = single_predict(model, numbers) except: output = "You have to write 4 numbers separated by commas" return render_template('index.html', value = output) else: return render_template('index.html') if __name__ == '__main__': model = Model() model.load_state_dict(torch.load('models/model_v1')) app.run(debug=True)
def predict_basin( basin: str, run_dir: Union[str, Path], camels_dir: Union[str, Path], period: str = "train", epoch: int = 30, ): if isinstance(run_dir, str): run_dir = Path(run_dir) elif not isinstance(run_dir, Path): raise TypeError(f"run_dir must be str or Path, not {type(run_dir)}") if isinstance(camels_dir, str): camels_dir = Path(camels_dir) elif not isinstance(camels_dir, Path): raise TypeError(f"run_dir must be str or Path, not {type(camels_dir)}") with open(run_dir / "cfg.json", "r") as fp: run_cfg = json.load(fp) if not period in ["train", "val"]: raise ValueError("period must be either train or val") basins = get_basin_list() db_path = str(run_dir / "attributes.db") attributes = load_attributes(db_path=db_path, basins=basins, drop_lat_lon=True) means = attributes.mean() stds = attributes.std() attrs_count = len(attributes.columns) timeseries_count = 6 input_size_stat = timeseries_count if run_cfg["no_static"] else attrs_count input_size_dyn = (timeseries_count if (run_cfg["no_static"] or not run_cfg["concat_static"]) else timeseries_count + attrs_count) model = Model( input_size_dyn=input_size_dyn, input_size_stat=input_size_stat, hidden_size=run_cfg["hidden_size"], dropout=run_cfg["dropout"], concat_static=run_cfg["concat_static"], no_static=run_cfg["no_static"], ).to(DEVICE) # load trained model weight_file = run_dir / f"model_epoch{epoch}.pt" model.load_state_dict(torch.load(weight_file, map_location=DEVICE)) ds_test = CamelsTXT( camels_root=camels_dir, basin=basin, dates=[ GLOBAL_SETTINGS[f"{period}_start"], GLOBAL_SETTINGS[f"{period}_end"] ], is_train=False, seq_length=run_cfg["seq_length"], with_attributes=True, attribute_means=means, attribute_stds=stds, concat_static=run_cfg["concat_static"], db_path=db_path, ) date_range = ds_test.dates_index[run_cfg["seq_length"] - 1:] loader = DataLoader(ds_test, batch_size=1024, shuffle=False, num_workers=4) preds, obs = evaluate_basin(model, loader) df = pd.DataFrame(data={ "qobs": obs.flatten(), "qsim": preds.flatten() }, index=date_range) results = df # plt.plot(date_range, results["qobs"], label="Obs") # plt.plot(date_range, results["qsim"], label="Preds") # plt.legend() # plt.savefig(f"{run_dir}/pred_basin_{basin}.pdf") # plt.close() return results, date_range