NaokiOkamoto commited on
Commit
c9e326b
1 Parent(s): d18cc82

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -32
app.py CHANGED
@@ -1,49 +1,65 @@
1
  import pandas as pd
2
  import numpy as np
3
  import gradio as gr
 
 
4
  import matplotlib.pyplot as plt
5
  import japanize_matplotlib
6
  import matplotlib.dates as mdates
7
  from dateutil.relativedelta import relativedelta
8
  import datetime
9
- from func import get_fish_qty, get_estat, dr_prediction_deployment, prediction_func
10
 
11
  import yaml
12
  with open('config.yaml') as file:
13
  config = yaml.safe_load(file.read())
 
 
 
14
 
15
- def get_prediction_result():
16
  today = datetime.datetime.now()
17
- prediction_month = (today + relativedelta(months=1)).strftime('%Y%m')
 
 
 
 
18
  df = prediction_func.prediction_to_dr(config['oil_price_url'], config['fuel_procurement_cost_url'])
19
  df = df.loc[df['target_date'].astype(str).str[:6]==prediction_month]
20
  df['target_date'] = pd.to_datetime(df['target_date'].astype(str))
21
- return df[['target_date', '電気代']]
 
 
 
 
 
 
 
22
 
23
- # def plot_prediction_result():
24
- # update = gr.LinePlot.update(
25
- # value=get_prediction_result(),
26
- # x="target_date",
27
- # y="電気代",
28
- # title="昨日までの魚の卸売り量から予測された、来月の2人世帯の平均電気料金の推移",
29
- # width=500,
30
- # height=500,
31
- # )
32
- # return update
33
  def plot_prediction_result():
34
- df = get_prediction_result()
 
 
 
 
 
 
 
 
 
 
35
 
36
- fig, ax1 = plt.subplots(1, 1, figsize=(20, 5))
37
- fig.autofmt_xdate()
38
- ax1.xaxis.set_major_formatter(mdates.DateFormatter("%Y/%m/%d"))
39
- ax1.xaxis.set_major_locator(mdates.DayLocator(interval=1))
40
- plt.rcParams["font.size"] = 14
41
- ax1.grid(True)
42
- ax1.set_xlim(df['target_date'].min(), df['target_date'].max())
43
- ax1.set_xlabel('target_date')
44
- ax1.set_ylabel('電気代(円)')
45
- ax1.plot(df['target_date'], df['電気代'])
46
- ax1.legend(loc="upper left", bbox_to_anchor=(1.0, 1.0))
47
 
48
  return fig
49
 
@@ -51,20 +67,24 @@ def plot_prediction_result():
51
  with gr.Blocks() as electoric_ploting:
52
  gr.Markdown("# 📈 Real-Time Line Plot")
53
  with gr.Row():
54
- # plot = gr.LinePlot(show_label=False)
55
- plot = gr.Plot(label="Plot")
 
56
  with gr.Row():
57
  gr.DataFrame(get_prediction_result)
58
- # with gr.Column():
59
 
60
- # with gr.Column():
 
 
 
61
 
 
62
 
63
  electoric_ploting.load(lambda: datetime.datetime.now(),
64
  None,
65
  # c_time2,
66
- every=360)
67
- dep = electoric_ploting.load(plot_prediction_result, None, plot, every=360)
68
 
69
  electoric_ploting.queue().launch()
70
 
 
1
  import pandas as pd
2
  import numpy as np
3
  import gradio as gr
4
+ import datetime
5
+ import calendar
6
  import matplotlib.pyplot as plt
7
  import japanize_matplotlib
8
  import matplotlib.dates as mdates
9
  from dateutil.relativedelta import relativedelta
10
  import datetime
11
+ from func import get_fish_qty, get_estat, dr_prediction_deployment, prediction_func, train_modeling
12
 
13
  import yaml
14
  with open('config.yaml') as file:
15
  config = yaml.safe_load(file.read())
16
+
17
+ def retrain():
18
+ get_prediction_result(retrain = True)
19
 
20
+ def get_prediction_result(retrain = False):
21
  today = datetime.datetime.now()
22
+ if retrain:
23
+ train_modeling.modeling()
24
+ prediction_month = (today+relativedelta(months=1)).strftime('%Y%m')
25
+ month_days = month_days = [pd.to_datetime(prediction_month + str(i+1).zfill(2)) for i in range(calendar.monthrange((today+relativedelta(months=1)).year, (today+relativedelta(months=1)).month)[1])]
26
+ dfc = pd.DataFrame({'target_date':month_days})
27
  df = prediction_func.prediction_to_dr(config['oil_price_url'], config['fuel_procurement_cost_url'])
28
  df = df.loc[df['target_date'].astype(str).str[:6]==prediction_month]
29
  df['target_date'] = pd.to_datetime(df['target_date'].astype(str))
30
+ df['forecast_point'] = pd.to_datetime(df['forecast_point'].astype(str))
31
+ df = pd.merge(dfc,
32
+ df,
33
+ on='target_date',
34
+ how='left')
35
+ df.loc[df['forecast_point'].isnull(), 'forecast_point'] = df['target_date'].apply(lambda x:x-relativedelta(months=1))
36
+ df = df.loc[~((df['target_date']<(today+relativedelta(months=1)))&(df['電気代'].isnull()))]
37
+ return df[['forecast_point', 'target_date', '電気代']]
38
 
 
 
 
 
 
 
 
 
 
 
39
  def plot_prediction_result():
40
+ update = gr.LinePlot.update(
41
+ value=get_prediction_result(),
42
+ x="target_date",
43
+ y="電気代",
44
+ title="昨日までの魚の卸売り量から予測された、来月の2人世帯の平均電気料金の推移",
45
+ width=500,
46
+ height=400,
47
+ )
48
+ return update
49
+ # def plot_prediction_result():
50
+ # df = get_prediction_result()
51
 
52
+ # fig, ax1 = plt.subplots(1, 1, figsize=(30, 10))
53
+ # fig.autofmt_xdate()
54
+ # ax1.xaxis.set_major_formatter(mdates.DateFormatter("%Y/%m/%d"))
55
+ # ax1.xaxis.set_major_locator(mdates.DayLocator(interval=1))
56
+ # plt.rcParams["font.size"] = 14
57
+ # ax1.grid(True)
58
+ # ax1.set_xlim(df['target_date'].min(), df['target_date'].max())
59
+ # ax1.set_xlabel('target_date')
60
+ # ax1.set_ylabel('電気代(円)')
61
+ # ax1.plot(df['target_date'], df['電気代'])
62
+ # ax1.legend(loc="upper left", bbox_to_anchor=(1.0, 1.0))
63
 
64
  return fig
65
 
 
67
  with gr.Blocks() as electoric_ploting:
68
  gr.Markdown("# 📈 Real-Time Line Plot")
69
  with gr.Row():
70
+ with gr.Column():
71
+ plot = gr.LinePlot(show_label=False)
72
+ # plot = gr.Plot(label="昨日までの魚の卸売り量から予測された、来月の2人世帯の平均電気料金の推移")
73
  with gr.Row():
74
  gr.DataFrame(get_prediction_result)
 
75
 
76
+ with gr.Column():
77
+ btn= gr.Button(value="再学習")
78
+ btn.click(retrain, inputs=None, outputs=None)
79
+
80
 
81
+ # demo.load(make_plot, inputs=[button], outputs=[plot])
82
 
83
  electoric_ploting.load(lambda: datetime.datetime.now(),
84
  None,
85
  # c_time2,
86
+ every=3600)
87
+ dep = electoric_ploting.load(plot_prediction_result, None, plot, every=3600)
88
 
89
  electoric_ploting.queue().launch()
90