AbdullahImran commited on
Commit
3a5b4c3
Β·
verified Β·
1 Parent(s): 2dadba8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -22
app.py CHANGED
@@ -4,35 +4,36 @@ import numpy as np
4
  import joblib
5
  import xgboost as xgb
6
  from tensorflow.keras.models import load_model
7
- import pickle
8
  import matplotlib.pyplot as plt
9
  import seaborn as sns
10
 
11
  # Load models & scalers
12
- xgb_clf = xgb.XGBClassifier(); xgb_clf.load_model("xgb_model.json")
 
 
13
  xgb_reg = joblib.load("xgb_pipeline_model.pkl")
 
14
  scaler_X = joblib.load("scaler_X.pkl")
15
  scaler_y = joblib.load("scaler_y.pkl")
 
16
  lstm_model = load_model("lstm_revenue_model.keras")
17
 
18
  # Prediction + Plot functions
19
- def classify_fn(df):
20
- # df: pandas DataFrame of features
21
  preds = xgb_clf.predict(df)
22
  probs = xgb_clf.predict_proba(df)
23
- # Bar chart for first prediction probabilities
24
  fig, ax = plt.subplots()
25
- ax.bar(['No Bankruptcy','Bankruptcy'], probs[0], color=['#4CAF50','#F44336'])
26
- ax.set_ylim(0,1)
27
  ax.set_title('Bankruptcy Probability')
28
  ax.set_ylabel('Probability')
29
  plt.tight_layout()
30
  return {"Predicted Label": int(preds[0])}, fig
31
 
32
 
33
- def regress_fn(df):
34
  preds = xgb_reg.predict(df)
35
- # Histogram of predictions
36
  fig, ax = plt.subplots()
37
  sns.histplot(preds, bins=20, kde=True, ax=ax)
38
  ax.set_title('Anomaly Score Distribution')
@@ -41,13 +42,11 @@ def regress_fn(df):
41
  return preds.tolist(), fig
42
 
43
 
44
- def lstm_fn(seq_str):
45
- # seq_str: comma-separated Q0-Q9 revenues
46
  vals = np.array(list(map(float, seq_str.split(',')))).reshape(1, -1)
47
  vals_s = scaler_X.transform(vals).reshape((1, vals.shape[1], 1))
48
  pred_s = lstm_model.predict(vals_s)
49
- pred = scaler_y.inverse_transform(pred_s)[0,0]
50
- # Plot input series + predicted point
51
  fig, ax = plt.subplots()
52
  ax.plot(range(10), vals.flatten(), marker='o', label='Input Revenue')
53
  ax.plot(10, pred, marker='X', markersize=10, color='red', label='Predicted Q10')
@@ -68,25 +67,29 @@ h1, h2 {color: #333;}
68
  demo = gr.Blocks(css=grid_css)
69
  with demo:
70
  gr.Markdown("# πŸš€ FinSight 360β„’ Dashboard")
71
- gr.Markdown("Comprehensive financial AI: Bankruptcy Classification, Anomaly Scoring, and Revenue Forecasting.")
 
72
  with gr.Tab("🏦 Bankruptcy Classifier"):
73
- gr.Markdown("Upload a single row of company features (CSV or paste) to predict bankruptcy:")
74
- inp1 = gr.Dataframe(headers="...", datatype=["number"]*20 + ["text"]*4, label="Features DataFrame")
75
- lbl1 = gr.Label(label="Predicted Label")
76
  plt1 = gr.Plot()
77
- inp1.submit(classify_fn, inp1, [lbl1, plt1])
 
78
  with gr.Tab("πŸ“ˆ Anomaly Regression"):
79
- gr.Markdown("Upload company features to predict anomaly score:")
80
- inp2 = gr.Dataframe(headers="...", datatype=["number"]*100, label="Features DataFrame")
81
  out2 = gr.Textbox(label="Predicted Scores List")
82
  plt2 = gr.Plot()
83
  inp2.submit(regress_fn, inp2, [out2, plt2])
 
84
  with gr.Tab("πŸ“Š LSTM Revenue Forecast"):
85
- gr.Markdown("Enter last 10 quarterly revenues (comma-separated) to forecast Q10 revenue:")
86
  inp3 = gr.Textbox(placeholder="e.g. 1000,1200,1100,...", label="Q0–Q9 Revenues")
87
  out3 = gr.Number(label="Predicted Q10 Revenue")
88
  plt3 = gr.Plot()
89
  inp3.submit(lstm_fn, inp3, [out3, plt3])
90
- gr.Markdown("---\n*Built with ❀️ by FinSight AI Team*")
 
91
 
92
  demo.launch()
 
4
  import joblib
5
  import xgboost as xgb
6
  from tensorflow.keras.models import load_model
7
+ from sklearn.preprocessing import MinMaxScaler
8
  import matplotlib.pyplot as plt
9
  import seaborn as sns
10
 
11
  # Load models & scalers
12
+ xgb_clf = xgb.XGBClassifier()
13
+ xgb_clf.load_model("xgb_model.json")
14
+
15
  xgb_reg = joblib.load("xgb_pipeline_model.pkl")
16
+
17
  scaler_X = joblib.load("scaler_X.pkl")
18
  scaler_y = joblib.load("scaler_y.pkl")
19
+
20
  lstm_model = load_model("lstm_revenue_model.keras")
21
 
22
  # Prediction + Plot functions
23
+ def classify_fn(df: pd.DataFrame):
 
24
  preds = xgb_clf.predict(df)
25
  probs = xgb_clf.predict_proba(df)
 
26
  fig, ax = plt.subplots()
27
+ ax.bar(['No Bankruptcy', 'Bankruptcy'], probs[0], color=['#4CAF50', '#F44336'])
28
+ ax.set_ylim(0, 1)
29
  ax.set_title('Bankruptcy Probability')
30
  ax.set_ylabel('Probability')
31
  plt.tight_layout()
32
  return {"Predicted Label": int(preds[0])}, fig
33
 
34
 
35
+ def regress_fn(df: pd.DataFrame):
36
  preds = xgb_reg.predict(df)
 
37
  fig, ax = plt.subplots()
38
  sns.histplot(preds, bins=20, kde=True, ax=ax)
39
  ax.set_title('Anomaly Score Distribution')
 
42
  return preds.tolist(), fig
43
 
44
 
45
+ def lstm_fn(seq_str: str):
 
46
  vals = np.array(list(map(float, seq_str.split(',')))).reshape(1, -1)
47
  vals_s = scaler_X.transform(vals).reshape((1, vals.shape[1], 1))
48
  pred_s = lstm_model.predict(vals_s)
49
+ pred = scaler_y.inverse_transform(pred_s)[0, 0]
 
50
  fig, ax = plt.subplots()
51
  ax.plot(range(10), vals.flatten(), marker='o', label='Input Revenue')
52
  ax.plot(10, pred, marker='X', markersize=10, color='red', label='Predicted Q10')
 
67
  demo = gr.Blocks(css=grid_css)
68
  with demo:
69
  gr.Markdown("# πŸš€ FinSight 360β„’ Dashboard")
70
+ gr.Markdown("Comprehensive financial AI:\\n- Bankruptcy Classification\\n- Anomaly Scoring\\n- Revenue Forecasting")
71
+
72
  with gr.Tab("🏦 Bankruptcy Classifier"):
73
+ gr.Markdown("**Upload company features** (as DataFrame) to predict bankruptcy:")
74
+ inp1 = gr.Dataframe(type="pandas", label="Features DataFrame")
75
+ out1 = gr.Label(label="Predicted Label")
76
  plt1 = gr.Plot()
77
+ inp1.submit(classify_fn, inp1, [out1, plt1])
78
+
79
  with gr.Tab("πŸ“ˆ Anomaly Regression"):
80
+ gr.Markdown("**Upload company features** (as DataFrame) to predict anomaly score:")
81
+ inp2 = gr.Dataframe(type="pandas", label="Features DataFrame")
82
  out2 = gr.Textbox(label="Predicted Scores List")
83
  plt2 = gr.Plot()
84
  inp2.submit(regress_fn, inp2, [out2, plt2])
85
+
86
  with gr.Tab("πŸ“Š LSTM Revenue Forecast"):
87
+ gr.Markdown("**Enter last 10 quarterly revenues** (comma-separated) to forecast Q10 revenue:")
88
  inp3 = gr.Textbox(placeholder="e.g. 1000,1200,1100,...", label="Q0–Q9 Revenues")
89
  out3 = gr.Number(label="Predicted Q10 Revenue")
90
  plt3 = gr.Plot()
91
  inp3.submit(lstm_fn, inp3, [out3, plt3])
92
+
93
+ gr.Markdown("---\\n*SDG 9: Industry, Innovation and Infrastructure*")
94
 
95
  demo.launch()