From d20f402639fd645ba3a646e9bbf557a1b4d5ec78 Mon Sep 17 00:00:00 2001
From: amilashanaka <dsa.amilashanaka@gmail.com>
Date: Thu, 5 Jan 2023 01:20:48 +0000
Subject: [PATCH] Update dashboard

---
 api/run.py             | 66 +++++++++++++++++++++++++----
 dash_board.php         |  2 +-
 data/data_list.php     |  2 +-
 data/forecast_data.php | 61 +++++++++++++++++++++++++++
 forecast.php           | 96 ++++++++++++++++++++++++++++++++++++++++++
 inc/function.php       | 32 ++++++++++++--
 info_box.php           | 19 +++++----
 page_forecast.php      | 33 +++++++++++++++
 row_data.php           |  5 +--
 side_bar.php           |  6 +--
 10 files changed, 294 insertions(+), 28 deletions(-)
 create mode 100644 data/forecast_data.php
 create mode 100644 forecast.php
 create mode 100644 page_forecast.php

diff --git a/api/run.py b/api/run.py
index 7111698..7efe0bb 100644
--- a/api/run.py
+++ b/api/run.py
@@ -39,6 +39,7 @@ data_set =pd.DataFrame()
 index_data_set =pd.DataFrame()
 tranning_set=pd.DataFrame()
 result=pd.DataFrame()
+predictions_set=pd.DataFrame()
 
 # numpy Arrays 
 data_arr_x=np.array([])
@@ -53,16 +54,17 @@ predictions  = np.array([])
 # Initialising the LSTM model with training
 
 model = Sequential()
-feature_length = 10
-testing_records=5
+feature_length = 100
+testing_records=50
 batch_size = 5
-epochs = 10
+epochs = 100
 accuracy=0
 execute_time=0
 
 # Scaler 
 scaler =  MinMaxScaler()
 
+
 # MySQL database connection
 db_connection_str = 'mysql+pymysql://root:@localhost/csct'
 db_connection = create_engine(db_connection_str)
@@ -147,7 +149,8 @@ def input_and_targert(data,feature_length):
 # function to calculate prediction 
 
 def predict_given_date(data, date, feature_length):
-  if date not in data.index:   
+  if date not in data.index:
+    last_date=data.tail(1)   
     data.loc[date]=0
   idx = data.index.get_loc(date)
   # close_col = data.iloc[:,1:2]
@@ -156,7 +159,39 @@ def predict_given_date(data, date, feature_length):
   # Prediction = model.predict(close_col)
   # Prediction=np.array(Prediction).reshape(-1, 1)
   # Prediction = scaler.inverse_transform(Prediction)
-  return idx
+  return str(last_date)
+
+
+#------------------------------------------------------------------------------
+
+def one_step_ahade():
+  global data_set
+  global predictions_set
+  global model
+
+  last_values=data_set.tail(feature_length)['Order_Demand'].values
+  last_values=np.array(last_values)
+  print(last_values)
+  last_values=scaler.transform(last_values.reshape(-1,1))
+
+  NumSamples=1
+  TimeSteps=feature_length
+  NumFeatures=1
+  last_values=last_values.reshape(NumSamples,TimeSteps,NumFeatures)
+  predicted_order_demand = model.predict(last_values)
+  predicted_order_demand = scaler.inverse_transform(predicted_order_demand)
+  predicted_order_demand=round(predicted_order_demand[0][0])
+
+  last_date=str(data_set.tail(1)["Date"].values[0])
+  last_date = datetime.strptime(last_date, "%Y-%m-%d")
+  last_date+= timedelta(days=1)
+  new_date=datetime.strftime(last_date,"%Y-%m-%d")
+
+  new_row={'Date':new_date,'Order_Demand':predicted_order_demand}
+  data_set = data_set.append(new_row, ignore_index=True)
+  predictions_set= predictions_set.append(new_row, ignore_index=True)
+  print(predictions_set)
+
 
 
 #------------------------------------------------------------------------------
@@ -219,14 +254,14 @@ def setup():
 
   #Add First LSTM Layer
 
-  model.add(LSTM(units = 10, activation = 'relu', input_shape = (time_steps, features), return_sequences=True))
+  model.add(LSTM(units = 100, activation = 'relu', input_shape = (time_steps, features), return_sequences=True))
 
   # Adding the  Second hidden layer and the LSTM layer
 
-  model.add(LSTM(units = 5, activation = 'relu', input_shape = (time_steps, features), return_sequences=True))
+  model.add(LSTM(units = 50, activation = 'relu', input_shape = (time_steps, features), return_sequences=True))
 
   # Adding the  Third hidden layer and the LSTM layer
-  model.add(LSTM(units = 5, activation = 'relu', return_sequences=False ))
+  model.add(LSTM(units = 50, activation = 'relu', return_sequences=False ))
 
 
   # Adding the output layer
@@ -301,6 +336,21 @@ setup()
 
 # end points declaration 
 
+@app.route("/predict_one_step",methods=['GET'])
+def predict_one_step():
+   one_step_ahade()
+   steps=str(len(predictions_set))
+   return steps
+
+@app.route("/predict_result",methods=['GET'])
+def predicpredict_result():
+    global predictions_set
+    return predictions_set.to_json(orient='records')
+
+
+
+  
+
 @app.route("/plot_order-demands",methods=['GET'])
 def plot_order_demands_total():
   global raw_data_set
diff --git a/dash_board.php b/dash_board.php
index e61ea54..3942082 100644
--- a/dash_board.php
+++ b/dash_board.php
@@ -47,7 +47,7 @@
 
             option = {
                 title: {
-                    text: 'Order Demad'
+                    text: 'Order Deamands'
                 },
                 tooltip: {
                     trigger: 'axis'
diff --git a/data/data_list.php b/data/data_list.php
index 10327cd..3172dc0 100644
--- a/data/data_list.php
+++ b/data/data_list.php
@@ -2,6 +2,6 @@
 
 include_once('./inc/conn.php');
  
-$sql = "SELECT * FROM product__demnd limit 10000";
+$sql = "SELECT * FROM aw_product_demand ";
 $result = mysqli_query($conn, $sql);
  
diff --git a/data/forecast_data.php b/data/forecast_data.php
new file mode 100644
index 0000000..dc274f5
--- /dev/null
+++ b/data/forecast_data.php
@@ -0,0 +1,61 @@
+<?php
+$curl = curl_init();
+
+curl_setopt_array($curl, array(
+  CURLOPT_URL => 'http://127.0.0.1:5000/predict_one_step',
+  CURLOPT_RETURNTRANSFER => true,
+  CURLOPT_ENCODING => '',
+  CURLOPT_MAXREDIRS => 10,
+  CURLOPT_TIMEOUT => 0,
+  CURLOPT_FOLLOWLOCATION => true,
+  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
+  CURLOPT_CUSTOMREQUEST => 'GET',
+));
+
+$steps = curl_exec($curl);
+
+curl_close($curl);
+
+
+
+$curl = curl_init();
+
+curl_setopt_array($curl, array(
+  CURLOPT_URL => 'http://127.0.0.1:5000/predict_result',
+  CURLOPT_RETURNTRANSFER => true,
+  CURLOPT_ENCODING => '',
+  CURLOPT_MAXREDIRS => 10,
+  CURLOPT_TIMEOUT => 0,
+  CURLOPT_FOLLOWLOCATION => true,
+  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
+  CURLOPT_CUSTOMREQUEST => 'GET',
+));
+
+$predict_result = curl_exec($curl);
+
+curl_close($curl);
+
+
+
+$arr_new = json_decode($predict_result, true);
+
+
+$dates = '';
+$order_validate = '';
+$predection = '';
+$error = '';
+
+foreach ($arr_new as $key => $value) {
+   
+    $dates = $dates . "'" .$value['Date']. "',";
+    $predection = $predection . "'" .round( $value['Order_Demand']). "',";
+ 
+}
+
+//==============================================================================
+
+// Fetch warehouse details from database
+
+
+
+
diff --git a/forecast.php b/forecast.php
new file mode 100644
index 0000000..bad07ef
--- /dev/null
+++ b/forecast.php
@@ -0,0 +1,96 @@
+<div class="content-wrapper">
+
+    <?php
+  $title = "Forecast Result";
+     $t1 = "Home";
+          $t2 = "Forecast";
+   
+   
+   include_once './page_header.php';?>
+    <!-- Main content -->
+    <div class="content">
+        <div class="container-fluid">
+
+            <?php include_once './data/forecast_data.php';?>
+
+
+
+            <div class="row" style="padding: 10px;">
+
+                <div class="col-md-12">
+
+                    <div style="width:full; height:400px;" id="chart1"></div>
+
+                </div>
+                <div class="col-md-12">
+                    <div class="row">
+                        <div class="col-md-8">
+                            <label for=""> Number of Days Predicted: <?=$steps?></label>
+                        </div>
+                        <div class="col-md-4">
+                            <button type="button" onclick="location.reload()" class="btn btn-success float-right">
+                                Forecast to next Day</button>
+                        </div>
+
+
+                    </div>
+
+
+
+                </div>
+
+            </div>
+
+            <script>
+            var chartDom = document.getElementById('chart1');
+            var myChart = echarts.init(chartDom);
+            var option;
+
+            option = {
+                title: {
+                    text: 'Order Demad'
+                },
+                tooltip: {
+                    trigger: 'axis'
+                },
+                legend: {
+                    data: ['Order Demand']
+                },
+                grid: {
+                    left: '3%',
+                    right: '4%',
+                    bottom: '3%',
+                    containLabel: true
+                },
+                toolbox: {
+                    feature: {
+                        saveAsImage: {}
+                    }
+                },
+                xAxis: {
+                    type: 'category',
+                    data: [<?=$dates?>]
+                },
+                yAxis: {
+                    type: 'value'
+                },
+                series: [{
+                    data: [<?=$predection?>],
+                    type: 'line',
+                    smooth: true
+                }]
+            };
+
+            option && myChart.setOption(option);
+            </script>
+
+
+
+
+            <!-- /.row -->
+        </div>
+        <!-- /.container-fluid -->
+    </div>
+    <!-- /.content -->
+</div>
+<!-- /.content-wrapper -->
\ No newline at end of file
diff --git a/inc/function.php b/inc/function.php
index 737a1bc..e5b8515 100644
--- a/inc/function.php
+++ b/inc/function.php
@@ -2,11 +2,37 @@
 
 include_once('conn.php');
 
-function get_all_data($conn){
+function get_accurecy($conn){
+
+    $sql = "select    accurecy from trannings ORDER BY id DESC LIMIT 1";
 
-    $sql = "SELECT * FROM product__demnd";
     $result = mysqli_query($conn, $sql);
-  
+    $res = mysqli_fetch_assoc($result);
+ 
+
+    return $res['accurecy'];
+
 
+}
+
+function get_epochs($conn){
+    $sql = "SELECT epochs from trannings order by id desc limit 1";
+    $result = mysqli_query($conn, $sql);
+    $res = mysqli_fetch_assoc($result);
+    return $res['epochs'];
 
+}
+
+function get_execute_time($conn){
+    $sql = "SELECT execute_time from trannings order by id desc limit 1";
+    $result = mysqli_query($conn, $sql);
+    $res = mysqli_fetch_assoc($result);
+    return $res['execute_time'];
+}
+
+function get_time_steps($conn){
+    $sql = "SELECT time_steps from trannings order by id desc limit 1";
+    $result = mysqli_query($conn, $sql);
+    $res = mysqli_fetch_assoc($result);
+    return $res['time_steps'];
 }
\ No newline at end of file
diff --git a/info_box.php b/info_box.php
index f97589f..fd750de 100644
--- a/info_box.php
+++ b/info_box.php
@@ -1,12 +1,15 @@
-  <!-- Info boxes -->
+<?php include_once('inc/function.php');?>
+
+
+<!-- Info boxes -->
         <div class="row">
           <div class="col-12 col-sm-6 col-md-3">
             <div class="info-box">
               <span class="info-box-icon bg-info elevation-1"><i class="fas fa-brain"></i></span>
 
               <div class="info-box-content">
-                <span class="info-box-text">LSTM Nodes</span>
-                <a href="user_daily_statement_dash.php"><span class="info-box-number">512</span></a>
+                <span class="info-box-text">LSTM Time Steps</span>
+                <a href="user_daily_statement_dash.php"><span class="info-box-number"><?=get_time_steps($conn)?></span></a>
               </div>
               <!-- /.info-box-content -->
             </div>
@@ -19,7 +22,7 @@
 
               <div class="info-box-content">
                 <span class="info-box-text">Accurecy</span>
-                <a href="winner_paid_list.php"><span class="info-box-number">30</span></a>
+                <a href="winner_paid_list.php"><span class="info-box-number"><?=get_accurecy($conn)?> %</span></a>
               </div>
               <!-- /.info-box-content -->
             </div>
@@ -38,7 +41,7 @@
               <div class="info-box-content">
                   
                 <span class="info-box-text">Times Trained</span>
-                <a href="game_list.php"><span class="info-box-number">50</span></a>
+                <a href="game_list.php"><span class="info-box-number"><?=get_epochs($conn)?></span></a>
               </div>
               <!-- /.info-box-content -->
             </div>
@@ -47,11 +50,11 @@
           <!-- /.col -->
           <div class="col-12 col-sm-6 col-md-3">
             <div class="info-box mb-3">
-              <span class="info-box-icon bg-warning elevation-1"><i class="fas fa-level-up"></i></span>
+              <span class="info-box-icon bg-warning elevation-1"><i class="fas fa-clock"></i></span>
 
              <div class="info-box-content">
-                <span class="info-box-text">Confidence</span>
-                  <a href="user_list.php"><span class="info-box-number">56</span>
+                <span class="info-box-text">Train Time</span>
+                  <a href="user_list.php"><span class="info-box-number"><?= get_execute_time($conn)?> minutes</span>
                   </a>
               </div>
             
diff --git a/page_forecast.php b/page_forecast.php
new file mode 100644
index 0000000..f362188
--- /dev/null
+++ b/page_forecast.php
@@ -0,0 +1,33 @@
+<?php
+
+include_once('inc/conn.php');
+include_once('header.php');
+
+
+
+
+
+
+
+?>
+
+<body class="hold-transition sidebar-mini">
+    <div class="wrapper">
+
+
+
+        <?php include_once('./nav_bar.php'); ?>
+        <!-- Main Sidebar Container -->
+        <?php include_once('./side_bar.php'); ?>
+
+        <?php include_once('forecast.php');?>
+
+        <?php include_once('control_side_bar.php');?>
+
+        <?php include_once('footer.php');?>
+    </div>
+
+    <?php include_once('footer_script.php');?>
+</body>
+
+</html>
\ No newline at end of file
diff --git a/row_data.php b/row_data.php
index d2b775b..9f6ac50 100644
--- a/row_data.php
+++ b/row_data.php
@@ -54,7 +54,6 @@ include_once('header.php');
                                             <th>#</th>
                                             <th>Product Code</th>
                                             <th>WareHouse</th>
-                                            <th>Category</th>
                                             <th>Date</th>
                                             <th>Order Demand</th>
 
@@ -66,7 +65,6 @@ include_once('header.php');
                                         <th>#</th>
                                             <th>Product Code</th>
                                             <th>WareHouse</th>
-                                            <th>Category</th>
                                             <th>Date</th>
                                             <th>Order Demand</th>
                                            
@@ -82,10 +80,9 @@ include_once('header.php');
                                         <tr>
                                             <td><?php echo $i++; ?></td>
                                             <td><a
-                                                    href="product.php?gpid=<?php echo base64_encode($row['Product_Code']); ?>"><?php echo $row['Product_Code']; ?></a>
+                                                    href="product.php?gpid=<?php echo base64_encode($row['Product_code']); ?>"><?php echo $row['Product_code']; ?></a>
                                             </td>
                                             <td><?= $row['Warehouse'] ?></td>
-                                            <td><?= $row['Product_Category']?></td>
                                             <td><?= $row['Date'] ?></td>
                                             <td><?= $row['Order_Demand'] ?></td>
                                         </tr>
diff --git a/side_bar.php b/side_bar.php
index 412eaf6..99520a4 100644
--- a/side_bar.php
+++ b/side_bar.php
@@ -1,6 +1,6 @@
 <aside class="main-sidebar sidebar-light-primary elevation-4">
     <!-- Brand Logo -->
-    <a href="index3.html" class="brand-link">
+    <a href="index.php" class="brand-link">
       <img src="dist/img/AdminLTELogo.png" alt="AdminLTE Logo" class="brand-image img-circle elevation-3" style="opacity: .8">
       <span class="brand-text font-weight-light"><?=APP_NAME?></span>
     </a>
@@ -68,9 +68,9 @@
             </a>
             <ul class="nav nav-treeview">
               <li class="nav-item">
-                <a href="forecast.php" class="nav-link">
+                <a href="page_forecast.php" class="nav-link">
                   <i class="fas fa-list nav-icon"></i>
-                  <p>Given Value</p>
+                  <p>Get the forecast</p>
                 </a>
               </li>
   
-- 
GitLab