gaur3009 commited on
Commit
3675b89
·
verified ·
1 Parent(s): 20877cb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -23
app.py CHANGED
@@ -63,47 +63,49 @@ class GANRiskAnalyzer:
63
  # Risk Analysis
64
  def analyze_financial_data(file):
65
  try:
66
- # Attempt to read the CSV file
67
- data = pd.read_csv(file, encoding="utf-8", error_bad_lines=False)
68
  except UnicodeDecodeError:
69
- # Fallback for files with non-UTF-8 encodings
70
- data = pd.read_csv(file, encoding="ISO-8859-1", error_bad_lines=False)
 
 
 
71
  except Exception as e:
72
- return f"An error occurred while reading the file: {str(e)}"
73
 
74
  # Handle empty or malformed data
75
  if data.empty:
76
- return "The uploaded file is empty or has an invalid structure."
77
 
78
- # Check required columns
79
  required_columns = ["Revenue", "Profit", "Loss", "Expenses", "Risk_Level"]
80
  if not all(column in data.columns for column in required_columns):
81
- return "The uploaded CSV must include these columns: Revenue, Profit, Loss, Expenses, Risk_Level."
82
 
83
- # Data Preprocessing
84
  try:
 
85
  X = data[["Revenue", "Profit", "Loss", "Expenses"]].dropna()
86
  y = data["Risk_Level"].dropna()
87
 
88
- # Check for empty rows after cleaning
89
  if X.empty or y.empty:
90
- return "The data has missing values or invalid rows after cleaning. Please check the file."
91
-
92
  scaler = StandardScaler()
93
  X_scaled = scaler.fit_transform(X)
94
-
95
  # Dimensionality Reduction
96
  pca = PCA(n_components=2)
97
  X_pca = pca.fit_transform(X_scaled)
98
-
99
  # Train-Test Split
100
  X_train, X_test, y_train, y_test = train_test_split(X_pca, y, test_size=0.2, random_state=42)
101
-
102
  # Gradient Boosting Classifier
103
  model = GradientBoostingClassifier(n_estimators=100, learning_rate=0.1, max_depth=5)
104
  model.fit(X_train, y_train)
105
  y_pred = model.predict(X_test)
106
-
107
  accuracy = accuracy_score(y_test, y_pred)
108
  report = classification_report(y_test, y_pred, output_dict=True)
109
 
@@ -112,12 +114,12 @@ def analyze_financial_data(file):
112
  gan.train(torch.tensor(X_pca, dtype=torch.float32), epochs=200)
113
  anomalies = gan.generate(n_samples=5, input_dim=X_pca.shape[1])
114
 
115
- # Analysis Insights
116
  total_revenue = data["Revenue"].sum()
117
  total_profit = data["Profit"].sum()
118
  total_loss = data["Loss"].sum()
119
 
120
- insights = {
121
  "Accuracy": f"{accuracy * 100:.2f}%",
122
  "Classification Report": report,
123
  "Generated Anomalies (GAN)": anomalies.tolist(),
@@ -128,23 +130,22 @@ def analyze_financial_data(file):
128
  "Net Balance": f"${(total_revenue - total_loss):,.2f}"
129
  }
130
  }
131
- return insights
132
  except Exception as e:
133
- return f"An error occurred during analysis: {str(e)}"
134
 
 
135
  with gr.Blocks(theme=gr.themes.Monochrome()) as interface:
136
  gr.Markdown("# **AI Risk Analyst Agent**")
137
  gr.Markdown(
138
  "Analyze your financial risks and identify anomalies using advanced AI models. Upload financial data in CSV format to get started."
139
  )
140
-
141
  with gr.Row():
142
  with gr.Column():
143
- data_file = gr.File(label="Upload Financial Data (CSV)")
144
  submit_button = gr.Button("Analyze")
145
  with gr.Column():
146
  output = gr.JSON(label="Risk Analysis Insights")
147
 
148
- submit_button.click(analyze_financial_data, inputs=[data_file], outputs=output)
149
 
150
  interface.launch()
 
63
  # Risk Analysis
64
  def analyze_financial_data(file):
65
  try:
66
+ # Read the uploaded CSV file
67
+ data = pd.read_csv(file.name, encoding="utf-8", error_bad_lines=False)
68
  except UnicodeDecodeError:
69
+ # Fallback for non-UTF-8 encoding
70
+ try:
71
+ data = pd.read_csv(file.name, encoding="ISO-8859-1", error_bad_lines=False)
72
+ except Exception as e:
73
+ return {"error": f"Failed to read file: {str(e)}"}
74
  except Exception as e:
75
+ return {"error": f"An unexpected error occurred: {str(e)}"}
76
 
77
  # Handle empty or malformed data
78
  if data.empty:
79
+ return {"error": "The uploaded file is empty or has an invalid structure."}
80
 
81
+ # Validate required columns
82
  required_columns = ["Revenue", "Profit", "Loss", "Expenses", "Risk_Level"]
83
  if not all(column in data.columns for column in required_columns):
84
+ return {"error": f"The CSV must include these columns: {', '.join(required_columns)}"}
85
 
 
86
  try:
87
+ # Data Preprocessing
88
  X = data[["Revenue", "Profit", "Loss", "Expenses"]].dropna()
89
  y = data["Risk_Level"].dropna()
90
 
 
91
  if X.empty or y.empty:
92
+ return {"error": "The data contains missing values or invalid rows after cleaning."}
93
+
94
  scaler = StandardScaler()
95
  X_scaled = scaler.fit_transform(X)
96
+
97
  # Dimensionality Reduction
98
  pca = PCA(n_components=2)
99
  X_pca = pca.fit_transform(X_scaled)
100
+
101
  # Train-Test Split
102
  X_train, X_test, y_train, y_test = train_test_split(X_pca, y, test_size=0.2, random_state=42)
103
+
104
  # Gradient Boosting Classifier
105
  model = GradientBoostingClassifier(n_estimators=100, learning_rate=0.1, max_depth=5)
106
  model.fit(X_train, y_train)
107
  y_pred = model.predict(X_test)
108
+
109
  accuracy = accuracy_score(y_test, y_pred)
110
  report = classification_report(y_test, y_pred, output_dict=True)
111
 
 
114
  gan.train(torch.tensor(X_pca, dtype=torch.float32), epochs=200)
115
  anomalies = gan.generate(n_samples=5, input_dim=X_pca.shape[1])
116
 
117
+ # Insights
118
  total_revenue = data["Revenue"].sum()
119
  total_profit = data["Profit"].sum()
120
  total_loss = data["Loss"].sum()
121
 
122
+ return {
123
  "Accuracy": f"{accuracy * 100:.2f}%",
124
  "Classification Report": report,
125
  "Generated Anomalies (GAN)": anomalies.tolist(),
 
130
  "Net Balance": f"${(total_revenue - total_loss):,.2f}"
131
  }
132
  }
 
133
  except Exception as e:
134
+ return {"error": f"An error occurred during analysis: {str(e)}"}
135
 
136
+ # Gradio Interface
137
  with gr.Blocks(theme=gr.themes.Monochrome()) as interface:
138
  gr.Markdown("# **AI Risk Analyst Agent**")
139
  gr.Markdown(
140
  "Analyze your financial risks and identify anomalies using advanced AI models. Upload financial data in CSV format to get started."
141
  )
 
142
  with gr.Row():
143
  with gr.Column():
144
+ data_file = gr.File(label="Upload Financial Data (CSV)", file_types=[".csv"])
145
  submit_button = gr.Button("Analyze")
146
  with gr.Column():
147
  output = gr.JSON(label="Risk Analysis Insights")
148
 
149
+ submit_button.click(analyze_financial_data, inputs=data_file, outputs=output)
150
 
151
  interface.launch()