from step_11 import *    from sklearn.metrics import mean_absolute_error, mean_squared_error    # Initial dataset for comparison  comparison_scenario = pd.DataFrame({"Scenario Name": [],                                      "RMSE baseline": [], "MAE baseline": [],                                      "RMSE ML": [], "MAE ML": []})    # Indicates if the comparison is done  comparison_scenario_done = False    # Selector for metrics  metric_selector = ["RMSE", "MAE"]  selected_metric = metric_selector[0]      def compute_metrics(historical_data, predicted_data):      rmse = mean_squared_error(historical_data, predicted_data)      mae = mean_absolute_error(historical_data, predicted_data)      return rmse, mae      def compare(state):      print("Comparing...")      # Initial lists for comparison      scenario_names = []      rmses_baseline = []      maes_baseline = []      rmses_ml = []      maes_ml = []        # Go through all the primary scenarios      all_scenarios = tp.get_primary_scenarios()      all_scenarios_ordered = sorted(all_scenarios, key=lambda x: x.creation_date.timestamp())        for scenario in all_scenarios_ordered:          print(f"Scenario {scenario.name}")          # Go through all the pipelines          for pipeline in scenario.pipelines.values():              print(f"     Pipeline {pipeline.config_id}")              # Get the predictions dataset with the historical data              only_prediction_dataset = create_predictions_dataset(pipeline)[-pipeline.n_predictions.read():]                # Series to compute the metrics (true values and predicted values)              historical_values = only_prediction_dataset["Historical values"]              predicted_values = only_prediction_dataset["Predicted values"]                # Compute the metrics for this pipeline and primary scenario              rmse, mae = compute_metrics(historical_values, predicted_values)                # Add values to the appropriate lists              if "baseline" in pipeline.config_id:                  rmses_baseline.append(rmse)                  maes_baseline.append(mae)              elif "ml" in pipeline.config_id:                  rmses_ml.append(rmse)                  maes_ml.append(mae)            scenario_names.append(scenario.creation_date.strftime("%A %d %b"))        # Update comparison_scenario      state.comparison_scenario = pd.DataFrame({"Scenario Name": scenario_names,                                                "RMSE baseline": rmses_baseline,                                                "MAE baseline": maes_baseline,                                                "RMSE ML": rmses_ml,                                                "MAE ML": maes_ml})        # When comparison_scenario_done will be set to True,      # the part with the graphs will be finally rendered      state.comparison_scenario_done = True      # Performance page  page_performance = """    <br/>    <|part|render={comparison_scenario_done}|    <|Table|expanded=False|expandable|  <|{comparison_scenario}|table|width=100%|>  |>    <|{selected_metric}|selector|lov={metric_selector}|dropdown|>    <|part|render={selected_metric=="RMSE"}|  <|{comparison_scenario}|chart|type=bar|x=Scenario Name|y[1]=RMSE baseline|y[2]=RMSE ML|height=100%|width=100%|>  |>    <|part|render={selected_metric=="MAE"}|  <|{comparison_scenario}|chart|type=bar|x=Scenario Name|y[1]=MAE baseline|y[2]=MAE ML|height=100%|width=100%|>  |>    |>      <center>  <|Compare primarys|button|on_action=compare|>  </center>  """    # Add the page_performance section to the menu  multi_pages = """  <|menu|label=Menu|lov={["Data Visualization", "Scenario Manager", "Performance"]}|on_action=menu_fct|>    <|part|render={page=="Data Visualization"}|""" + page_data_visualization + """|>  <|part|render={page=="Scenario Manager"}|""" + page_scenario_manager + """|>  <|part|render={page=="Performance"}|""" + page_performance + """|>  """    if __name__ == "__main__":      Gui(page=multi_pages).run(dark_mode=False)


import numpy as np  import pandas as pd    from step_04 import tp, baseline_pipeline_cfg, dt  from step_02 import *    # Initialize the "predictions" dataset  predictions_dataset = pd.DataFrame(      {"Date": [dt.datetime(2021, 6, 1)], "Historical values": [np.NaN], "Predicted values": [np.NaN]})    # Add a button and a chart for our predictions  pipeline_page = page + """  Press <|predict|button|on_action=predict|> to predict with default parameters (30 predictions) and June 1st as day.    <|{predictions_dataset}|chart|x=Date|y[1]=Historical values|type[1]=bar|y[2]=Predicted values|type[2]=scatter|height=80%|width=100%|>  """      def predict(state):      print("'Predict' button clicked")      pipeline = create_and_submit_pipeline()      update_predictions_dataset(state, pipeline)      def create_and_submit_pipeline():      print("Execution of pipeline...")      # Create the pipeline from the pipeline config      pipeline = tp.create_pipeline(baseline_pipeline_cfg)      # Submit the pipeline (Execution)      tp.submit(pipeline)      return pipeline      def create_predictions_dataset(pipeline):      print("Creating predictions dataset...")      # Read data from the pipeline      predictions = pipeline.predictions.read()      day = pipeline.day.read()      n_predictions = pipeline.n_predictions.read()      cleaned_data = pipeline.cleaned_dataset.read()        # Set arbitrarily the time window for the chart as 5 times the number of predictions      window = 5 * n_predictions        # Create the historical dataset that will be displayed      new_length = len(cleaned_data[cleaned_data["Date"] < day]) + n_predictions      temp_df = cleaned_data[:new_length]      temp_df = temp_df[-window:].reset_index(drop=True)        # Create the series that will be used in the concat      historical_values = pd.Series(temp_df["Value"], name="Historical values")      predicted_values = pd.Series([np.NaN] * len(temp_df), name="Predicted values")      predicted_values[-len(predictions):] = predictions        # Create the predictions dataset      # Columns : [Date, Historical values, Predicted values]      return pd.concat([temp_df["Date"], historical_values, predicted_values], axis=1)      def update_predictions_dataset(state, pipeline):      print("Updating predictions dataset...")      state.predictions_dataset = create_predictions_dataset(pipeline)      if __name__ == "__main__":      Gui(page=pipeline_page).run(dark_mode=False)


from taipy import Gui  import pandas as pd      def get_data(path_to_csv: str):      # pandas.read_csv() returns a pd.DataFrame      dataset = pd.read_csv(path_to_csv)      dataset["Date"] = pd.to_datetime(dataset["Date"])      return dataset      # Read the dataframe  path_to_csv = "dataset.csv"  dataset = get_data(path_to_csv)    # Initial value  n_week = 10    # Definition of the page  page = """  # Getting started with Taipy    Week number: *<|{n_week}|>*    Interact with this slider to change the week number:  <|{n_week}|slider|min=1|max=52|>    ## Dataset:    Display the last three months of data:  <|{dataset[9000:]}|chart|type=bar|x=Date|y=Value|height=100%|>    <|{dataset}|table|height=400px|width=95%|>  """    if __name__ == "__main__":      # Create a Gui object with our page content      Gui(page=page).run(dark_mode=False)


from step_10 import *  from step_06 import ml_pipeline_cfg    from taipy import Config, Frequency  from taipy.gui import notify    # Create scenarios each week and compare them  scenario_daily_cfg = Config.configure_scenario(id="scenario",                                                 pipeline_configs=[baseline_pipeline_cfg, ml_pipeline_cfg],                                                 frequency=Frequency.DAILY)    if __name__ == "__main__":      # Delete all entities      Config.configure_global_app(clean_entities_enabled=True)      tp.clean_all_entities()    # Change the inital scenario selector to see which scenarios are primary  scenario_selector = [(scenario.id, ("*" if scenario.is_primary else "") + scenario.name) for scenario in tp.get_scenarios()]      # Redefine update_scenario_selector to add "*" in the display name when the scnario is primary  def update_scenario_selector(state, scenario):      print("Updating scenario selector...")      # Create the scenario name for the scenario selector      # This name changes dependind whether the scenario is primary or not      scenario_name = ("*" if scenario.is_primary else "") + scenario.name      print(scenario_name)      # Update the scenario selector      state.scenario_selector += [(scenario.id, scenario_name)]      selected_scenario_is_primary = None      # Change the create_scenario function to create a scenario with the selected frequency  def create_scenario(state):      print("Execution of scenario...")      # Extra information for scenario      creation_date = state.day      name = create_name_for_scenario(state)        # Create a scenario with the week cycle      scenario = tp.create_scenario(scenario_daily_cfg, creation_date=creation_date, name=name)        state.selected_scenario = (scenario.id, name)        # Change the scenario that is currently selected      submit_scenario(state)      # This is the same code as in step_9_dynamic_scenario_creation.py  def submit_scenario(state):      print("Submitting scenario...")      # Get the currently selected scenario      scenario = tp.get(state.selected_scenario[0])        # Conversion to the right format      state_day = dt.datetime(state.day.year, state.day.month, state.day.day)        # Change the default parameters by writing in the Data Nodes      # if state.day != scenario.day.read():      scenario.day.write(state_day)      # if int(state.n_predictions) != scenario.n_predictions.read():      scenario.n_predictions.write(int(state.n_predictions))      # if state.max_capacity != scenario.max_capacity.read():      scenario.max_capacity.write(int(state.max_capacity))      # if state.day != scenario.creation_date:      scenario.creation_date = state.day        # Execute the pipelines/code      tp.submit(scenario)        # Update the scenario selector and the scenario that is currently selected      update_scenario_selector(state, scenario)  # change list to scenario        # Update the chart directly      update_chart(state)      def make_primary(state):      print("Making the current scenario primary...")      scenario = tp.get(state.selected_scenario[0])      # Take the current scenario primary      tp.set_primary(scenario)        # Update the scenario selector accordingly      state.scenario_selector = [(scenario.id, ("*" if scenario.is_primary else "") + scenario.name)                                 for scenario in tp.get_scenarios()]      state.selected_scenario_is_primary = True      def remove_scenario_from_selector(state, scenario: list):      # Take all the scenarios in the selector that doesn't have the scenario.id      state.scenario_selector = [(s[0], s[1]) for s in state.scenario_selector if s[0] != scenario.id]      state.selected_scenario = state.scenario_selector[-1]      def delete_scenario(state):      scenario = tp.get(state.selected_scenario[0])        if scenario.is_primary:          # Notify the user that primary scenarios can not be deleted          notify(state, "info", "Cannot delete the primary scenario")      else:          # Delete the scenario and the related objects (datanodes, tasks, jobs,...)          tp.delete(scenario.id)            # Update the scenario selector accordingly          remove_scenario_from_selector(state, scenario)      # Add a "Delete scenario" and a "Make primary" buttons  page_scenario_manager = """  # Create your scenario:    <|layout|columns=1 1 1 1|  <|  **Prediction date**\n\n <|{day}|date|not with_time|>  |>    <|  **Max capacity**\n\n <|{max_capacity}|number|>  |>    <|  **Number of predictions**\n\n<|{n_predictions}|number|>  |>    <|

  <|Create new scenario|button|on_action=create_scenario|>  |>  |>      <|part|render={len(scenario_selector) > 0}|  <|layout|columns=1 1|    <|layout|columns=1 1|  <|  ## Scenario \n <|{selected_scenario}|selector|lov={scenario_selector}|dropdown|>  |>

  <|Delete scenario|button|on_action=delete_scenario|active={len(scenario_selector)>0}|>  <|Make primary|button|on_action=make_primary|active={not(selected_scenario_is_primary) and len(scenario_selector)>0}|>  |>          <|  ## Display the pipeline \n <|{selected_pipeline}|selector|lov={pipeline_selector}|dropdown|>  |>  |>    <|{predictions_dataset}|chart|x=Date|y[1]=Historical values|type[1]=bar|y[2]=Predicted values|type[2]=scatter|height=80%|width=100%|>  |>  """    # Redefine the multi_pages  multi_pages = """  <|menu|label=Menu|lov={["Data Visualization", "Scenario Manager"]}|on_action=menu_fct|>    <|part|render={page=="Data Visualization"}|""" + page_data_visualization + """|>  <|part|render={page=="Scenario Manager"}|""" + page_scenario_manager + """|>  """      def on_change(state, var_name: str, var_value):      if var_name == "n_week":          # Update the dataset when the slider is moved          state.dataset_week = dataset[dataset["Date"].dt.isocalendar().week == var_value]        elif var_name == "selected_pipeline" or var_name == "selected_scenario":          # Update selected_scenario_is_primary indicating if the current scenario is primary or not          state.selected_scenario_is_primary = tp.get(state.selected_scenario[0]).is_primary            # Check if we can read the data node to update the chart          if tp.get(state.selected_scenario[0]).predictions.read() is not None:              update_chart(state)      if __name__ == "__main__":      Gui(page=multi_pages).run(dark_mode=False)


from taipy import Gui    # A dark mode is available in Taipy  # However, we will use the light mode for the Getting Started  Gui(page="# Getting started with *Taipy*").run(dark_mode=False)


from step_09 import *    # Our first page is the original page  # (with the slider and the chart that displays a week of the historical data)  page_data_visualization = page    # Second page: create scenarios and display results  page_scenario_manager = """  # Create your scenario    <|layout|columns=1 1 1 1|  <|  **Prediction date**\n\n <|{day}|date|not with_time|>  |>    <|  **Max capacity**\n\n <|{max_capacity}|number|>  |>    <|  **Number of predictions**\n\n<|{n_predictions}|number|>  |>    <|

\n <|Create new scenario|button|on_action=create_scenario|>  |>  |>    <|part|render={len(scenario_selector) > 0}|  <|layout|columns=1 1|  <|  ## Scenario \n <|{selected_scenario}|selector|lov={scenario_selector}|dropdown|>  |>    <|  ## Display the pipeline \n <|{selected_pipeline}|selector|lov={pipeline_selector}|dropdown|>  |>  |>    <|{predictions_dataset}|chart|x=Date|y[1]=Historical values|type[1]=bar|y[2]=Predicted values|type[2]=scatter|height=80%|width=100%|>  |>  """    # Create a menu with our pages  multi_pages = """  <|menu|label=Menu|lov={["Data Visualization", "Scenario Manager"]}|on_action=menu_fct|>    <|part|render={page=="Data Visualization"}|""" + page_data_visualization + """|>  <|part|render={page=="Scenario Manager"}|""" + page_scenario_manager + """|>  """    # The initial page is the "Data Visualization" page  page = "Data Visualization"      def menu_fct(state, var_name: str, fct: str, var_value: list):      # Change the value of the state.page variable in order to render the correct page      state.page = var_value["args"][0]      if __name__ == "__main__":      Gui(page=multi_pages).run(dark_mode=False)


import taipy as tp    from step_03 import Config, clean_data_task_cfg, predict_baseline_task_cfg, dt    # Create the first pipeline configuration  baseline_pipeline_cfg = Config.configure_pipeline(id="baseline",                                                    task_configs=[clean_data_task_cfg, predict_baseline_task_cfg])    ## Execute the "baseline" pipeline  if __name__ == "__main__":      # Create the pipeline      baseline_pipeline = tp.create_pipeline(baseline_pipeline_cfg)      # Submit the pipeline (Execution)      tp.submit(baseline_pipeline)        # Read output data from the pipeline      baseline_predictions = baseline_pipeline.predictions.read()      print("Predictions of baseline algorithm\n", baseline_predictions)


from taipy.gui import Gui  from keras.models import load_model  from PIL import Image  import numpy as np    class_names = {      0: 'airplane',      1: 'automobile',      2: 'bird',      3: 'cat',      4: 'deer',      5: 'dog',      6: 'frog',      7: 'horse',      8: 'ship',      9: 'truck',  }    model = load_model("Neural Network Notebook/Cifar10Model.keras")    def predict_image(model, path_to_img):      img = Image.open(path_to_img)      img = img.convert("RGB")      img = img.resize((32, 32))      data = np.asarray(img)      data = data / 255      probs = model.predict(np.array([data])[:1])        top_prob = probs.max()      top_pred = class_names[np.argmax(probs)]            return top_prob, top_pred        content = ""  img_path = "placeholder_image.png"  prob = 0  pred = ""    index = """  <|text-center|  <|{"logo.png"}|image|width=16vw|>    <|{content}|file_selector|extensions=.png|>  select an image from your file system    <|{pred}|>    <|{img_path}|image|>    <|{prob}|indicator|value={prob}|min=0|max=100|width=25vw|>  >  """    def on_change(state, var_name, var_val):      if var_name == "content":          top_prob, top_pred = predict_image(model, var_val)          state.prob = round(top_prob * 100)          state.pred = "this is a " + top_pred          state.img_path = var_val      #print(var_name, var_val)    app = Gui(page=index)    if __name__ == "__main__":      app.run(use_reloader=True)


import pandas as pd  from sklearn.model_selection import train_test_split  from sklearn.ensemble import RandomForestRegressor  from sklearn.compose import ColumnTransformer  from sklearn.pipeline import Pipeline  from sklearn.preprocessing import OneHotEncoder  from sklearn.metrics import mean_squared_error  import numpy as np  # Import numpy for RMSE calculation  from prophet import Prophet      def build_message(name: str):      return f"Hello {name}!"    def clean_data(initial_dataset: pd.DataFrame):      return initial_dataset    def retrained_model(cleaned_dataset: pd.DataFrame):      # Split the dataset into features (X) and target (y)      X = cleaned_dataset.drop('Claim_Amount', axis=1)      y = cleaned_dataset['Claim_Amount']        # Split the data into training and testing sets      X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)        # Define the categorical columns for one-hot encoding      categorical_cols = ['Procedure_Code', 'Diagnosis_Code', 'Provider_Specialty', 'Insurance_Plan']        # Create a column transformer      preprocessor = ColumnTransformer(          transformers=[              ('cat', OneHotEncoder(drop='first'), categorical_cols)          ],          remainder='passthrough'      )        # Create a pipeline with preprocessing and the Random Forest Regressor      model = Pipeline([          ('preprocessor', preprocessor),          ('regressor', RandomForestRegressor(n_estimators=100, random_state=42))      ])        # Fit the model on the training data      model.fit(X_train, y_train)        # Make predictions on the test set      predictions = model.predict(X_test)        # Calculate Mean Squared Error (MSE)      mse = mean_squared_error(y_test, predictions)        # Calculate Root Mean Squared Error (RMSE)      rmse = np.sqrt(mse)        # Print the RMSE      print(f"Mean Squared Error: {mse}")      print(f"Root Mean Squared Error (RMSE): {rmse}")            return model    def predict(model):      # Example: Make a prediction for a new patient      new_patient_data = pd.DataFrame({          'Procedure_Code': ['CPT456'],          'Diagnosis_Code': ['ICD-10-B'],          'Provider_Specialty': ['Orthopedics'],          'Patient_Age': [35],          'Insurance_Plan': ['PPO'],          'Deductible': [200],          'Copayment': [30],          'Coinsurance': [20],      }, index=[0])        # Predict the claim amount for the new patient      new_patient_claim = model.predict(new_patient_data)      print(f"Predicted Claim Amount for New Patient: ${new_patient_claim[0]:.2f}")


import taipy as tp  from taipy.core.config import Config    Config.load('my_config.toml')    scenario_cfg = Config.scenarios['scenario']    if __name__ == '__main__':      tp.Core().run()        scenario_1 = tp.create_scenario(scenario_cfg)      print("submitting")        scenario_1.submit()      print("submit shit ayyindhi")


from taipy.gui import Html    html_page = Html("""

        """)


from geopy.geocoders import Nominatim  import folium    user_agent = "geoapiExercises/1.0 AIzaSyBIeklfsRu1yz97lY2gJzWHJcmrd7lx2zU"    # Initialize the geocoder with the user agent  geolocator = Nominatim(user_agent=user_agent, timeout=10)  # List of locations to geocode  locations = ["Denver, CO, United States", "New York, NY, United States", "Los Angeles, CA, United States"]    # Create an empty map  map_location = folium.Map(location=[0, 0], zoom_start=5)    # Iterate through the list of locations  for location in locations:      # Perform geocoding      location_info = geolocator.geocode(location)        if location_info:          # Extract latitude and longitude          latitude = location_info.latitude          longitude = location_info.longitude            # Add a marker for the geocoded location          folium.Marker([latitude, longitude], popup=location).add_to(map_location)      else:          print(f"Geocoding was not successful for the location: {location}")    # Save or display the map (as an HTML file)  map_location.save("geocoded_locations_map.html")    print("Map created and saved as 'geocoded_locations_map.html'")


from taipy.gui import Gui, notify  import pandas as pd  import yfinance as yf  from taipy.config import Config  import taipy as tp   import datetime as dt  from taipy import Core  from show_hospitals_map import html_page  from flask import Flask, request, session, jsonify, redirect, render_template  from flask_restful import Api, Resource  import requests    Config.load("config_model_train.toml")  scenario_cfg = Config.scenarios['stock']  tickers = yf.Tickers("msft aapl goog")    root_md = "<|navbar|>"    property_chart = {      "type": "lines",      "x": "Date",      "y[1]": "Open",      "y[2]": "Close",      "y[3]": "High",      "y[4]": "Low",      "color[1]": "green",      "color[2]": "grey",      "color[3]": "red",      "color[4]": "yellow",  }  df = pd.DataFrame([], columns=["Date", "High", "Low", "Open", "Close"])  df_pred = pd.DataFrame([], columns = ['Date','Close_Prediction'])    stock = ""  stock_text = "No Stock to Show"  chart_text = "No Chart to Show"  stocks = []      page = """  # Stock Portfolio    ### Choose the stock to show  <|toggle|theme|>    <|layout|columns=1 1|  <|  <|{stock_text}|>    <|{stock}|selector|lov=MSFT;AAPL;GOOG;Reset|dropdown|>    <|Press for Stock|button|on_action=on_button_action|>  <|Get the future predictions|button|on_action=get_predictions|>  |>    <|{stock}  <|{chart_text}|>  <|{df}|chart|properties={property_chart}|>  |>    |>  """    pages = {      "/" : root_md,      "home" : page,      "claim": "empty page"  }    def on_button_action(state):      if state.stock == "Reset":          state.stock_text = "No Stock to Show"          state.chart_text = "No Chart to Show"          state.df = pd.DataFrame([], columns=["Date", "High", "Low", "Open", "Close"])          state.df_pred = pd.DataFrame([], columns = ['Date','Close_Prediction'])          state.pred_text = "No Prediction to Show"      else:          state.stock_text = f"The stock is {state.stock}"          state.chart_text = f"Monthly history of stock {state.stock}"          state.df = tickers.tickers[state.stock].history().reset_index()          state.df.to_csv(f"{stock}.csv", index=False)        def get_predictions(state):            scenario_stock = tp.create_scenario(scenario_cfg)      scenario_stock.initial_dataset.path = f"{stock}".csv      notify(state, 'success', 'camehere')      scenario_stock.write(state.df)      tp.submit(scenario_stock)      state.df_pred = scenario_stock.predictions.read()      state.df_pred.to_csv("pred.csv", index=False)    tp.Core().run()  # Gui(pages=pages).run(use_reloader=True)      app = Flask(__name__)  # app = Flask(__name__)  app.secret_key = "your_secret_key"  # Set a secret key for session management  api = Api(app)    class SignupResource(Resource):      def get(self):          return redirect("/signup.html")            def post(self):          SIGNUP_API_URL = "https://health-insurance-rest-apis.onrender.com/api/signup"          signup_data = {              'username': request.form['username'],              'password': request.form['password'],              'email': request.form['email']          }          headers = {              'Content-Type': 'application/json'          }          print(signup_data)          response = requests.post(SIGNUP_API_URL, headers=headers, json=signup_data)          print("response", response)          if response.status_code == 200:              return redirect("/login.html")          else:              return 'Signup Failed'    # Login Resource  class LoginResource(Resource):      def get(self):          """          Return a simple login page HTML          """          return redirect("/login.html")      def post(self):          email = request.form['email']          password = request.form['password']          auth_data = {              'username': email,              'password': password          }          AUTH_API_URL = "https://health-insurance-rest-apis.onrender.com/api/login"          response = requests.post(AUTH_API_URL, json=auth_data)          if response.status_code == 200:              auth_data = response.json()              access_token = auth_data.get('access_token')              refresh_token = auth_data.get('refresh_token')                # Store tokens in the session              session['access_token'] = access_token              session['refresh_token'] = refresh_token                return redirect("/home")          else:              return 'Login failed', 401    # Protected Resource  class ProtectedResource(Resource):      def get(self):          # Check if the JWT token is present in the session          if 'jwt_token' in session:              jwt_token = session['jwt_token']                # You can add logic here to verify the JWT token if needed              # For simplicity, we assume the token is valid                return {'message': 'Access granted for protected route', 'jwt_token': jwt_token}, 200          else:              return {'message': 'Access denied'}, 401    print("registered the apis")  # Add resources to the API  api.add_resource(LoginResource, '/login')  api.add_resource(ProtectedResource, '/protected')  api.add_resource(SignupResource, '/signup')    @app.before_request  def check_access_token():      # print ('access_token' in session, "checkIt")      if request.endpoint != 'login' and 'access_token' not in session:      #     # Redirect to the login page if not on the login route and no access_token is in the session      #     print(request.endpoint, "endpoint")          return redirect("/login")    gui = Gui(pages=pages, flask=app).run(debug=False)


from taipy import Config, Scope  import pandas as pd  from prophet import Prophet  from functions import *      # Input Data Nodes  initial_dataset_cfg = Config.configure_data_node(id="initial_dataset",                                                   storage_type="csv",                                                   default_path='df.csv')    cleaned_dataset_cfg = Config.configure_data_node(id="cleaned_dataset")            clean_data_task_cfg = Config.configure_task(id="clean_data_task",                                              function=clean_data,                                              input=initial_dataset_cfg,                                              output=cleaned_dataset_cfg,                                              skippable=True)      model_training_cfg = Config.configure_data_node(id="model_output")        predictions_cfg = Config.configure_data_node(id="predictions")            model_training_task_cfg = Config.configure_task(id="model_retraining_task",                                                  function=retrained_model,                                                  input=cleaned_dataset_cfg,                                                  output=model_training_cfg,                                                  skippable=True)    predict_task_cfg = Config.configure_task(id="predict_task",                                           function=predict,                                           input=model_training_cfg,                                           output=predictions_cfg,                                             skippable=True)      # Create the first pipeline configuration  # retraining_model_pipeline_cfg = Config.configure_pipeline(  #     id="model_retraining_pipeline",  #     task_configs=[clean_data_task_cfg, model_training_task_cfg],  # )      # Run the Taipy Core service  # import taipy as tp    # # Run of the Taipy Core service  # tp.Core().run()    # # Create the pipeline  # retrain_pipeline = tp.create_pipeline(retraining_model_pipeline_cfg)    # # Submit the pipeline  # tp.submit(retrain_pipeline)      # tp.Core().stop()    scenario_cfg = Config.configure_scenario_from_tasks(id="stock",                                                      task_configs=[clean_data_task_cfg,                                                      model_training_task_cfg,                                                      predict_task_cfg])      # tp.Core().run()  # tp.submit(scenario_cfg)    Config.export("config_model_train.toml")


from taipy import Config  from functions import build_message          name_data_node_cfg = Config.configure_data_node(id="name")  message_data_node_cfg = Config.configure_data_node(id="message")  build_msg_task_cfg = Config.configure_task("build_msg", build_message, name_data_node_cfg, message_data_node_cfg)  scenario_cfg = Config.configure_scenario_from_tasks("scenario", task_configs=[build_msg_task_cfg])    Config.export('my_config.toml')


from functools import wraps  import jwt  from flask import request, abort  from flask import current_app    def token_required(f):      @wraps(f)      def decorated(*args, **kwargs):          token = None          if "Authorization" in request.headers:              token = request.headers["Authorization"].split(" ")[1]          if not token:              return {                  "message": "Authentication Token is missing!",                  "data": None,                  "error": "Unauthorized"              }, 401          try:              # data=jwt.decode(token, current_app.config["SECRET_KEY"], algorithms=["RS256"])              print("got the token")              # current_user=models.User().get_by_id(data["user_id"])              current_user = 12              if current_user is None:                  return {                  "message": "Invalid Authentication token!",                  "data": None,                  "error": "Unauthorized"              }, 401              if not current_user["active"]:                  abort(403)          except Exception as e:              return {                  "message": "Something went wrong",                  "data": None,                  "error": str(e)              }, 500            return f(current_user, *args, **kwargs)        return decorated


from flask import Flask, request, session, jsonify  from flask_restful import Api, Resource    app = Flask(__name__)  app.secret_key = "your_secret_key"  # Set a secret key for session management  api = Api(app)    # Dummy user data for demonstration  users = {      'maneesh': {'password': 'securepassword'}  }    # Login Resource  class LoginResource(Resource):      def post(self):          data = request.get_json()          username = data.get('username')          password = data.get('password')          print("hello")          # Check if user exists and password is correct          if username in users and users[username]['password'] == password:              # Simulate receiving a JWT token from a third-party API              jwt_token = "your_received_jwt_token"                # Store the JWT token in the session              session['jwt_token'] = jwt_token                return {'message': 'Login successful'}, 200          else:              return {'message': 'Invalid credentials'}, 401    # Protected Resource  class ProtectedResource(Resource):      def get(self):          # Check if the JWT token is present in the session          if 'jwt_token' in session:              jwt_token = session['jwt_token']                # You can add logic here to verify the JWT token if needed              # For simplicity, we assume the token is valid                return {'message': 'Access granted for protected route', 'jwt_token': jwt_token}, 200          else:              return {'message': 'Access denied'}, 401    # Add resources to the API  api.add_resource(LoginResource, '/login')  api.add_resource(ProtectedResource, '/protected')    if __name__ == '__main__':      app.run(debug=True)