jithenderchoudary commited on
Commit
bc2ced8
·
verified ·
1 Parent(s): 8630dde

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +10 -24
app.py CHANGED
@@ -1,6 +1,4 @@
1
- # app.py
2
-
3
- # Import libraries
4
  import numpy as np
5
  import pandas as pd
6
  import matplotlib.pyplot as plt
@@ -19,29 +17,22 @@ data = pd.DataFrame({
19
  "Defect_Type": np.random.choice([0, 1, 2], 200, p=[0.6, 0.3, 0.1])
20
  })
21
 
22
- # Splitting data
23
  X = data[["Pressure", "Temperature", "Material_Type"]]
24
  y = data["Defect_Type"]
25
  X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
26
 
27
- # Step 2: Train the Model
28
  model = RandomForestClassifier(n_estimators=100, random_state=42)
29
  model.fit(X_train, y_train)
30
-
31
- # Save the model
32
  joblib.dump(model, "defect_model.pkl")
33
-
34
- # Test the Model
35
  y_pred = model.predict(X_test)
36
  print(f"Model Accuracy: {accuracy_score(y_test, y_pred):.2f}")
37
 
38
- # Step 3: Define Helper Functions for Visualizations
39
  def plot_simulation(pressure, temperature, material_type):
40
- # Simulate some stress/strain values for visualization
 
41
  stress = np.linspace(pressure * 0.5, pressure * 1.5, 100)
42
  strain = stress / (temperature * 0.01 * material_type)
43
-
44
- # Create the plot
45
  plt.figure(figsize=(8, 5))
46
  plt.plot(stress, strain, label="Stress-Strain Curve")
47
  plt.xlabel("Stress (MPa)")
@@ -49,29 +40,25 @@ def plot_simulation(pressure, temperature, material_type):
49
  plt.title("Stress-Strain Simulation")
50
  plt.legend()
51
  plt.grid(True)
52
-
53
- # Save the plot to an image
54
  plot_path = "simulation_plot.png"
55
  plt.savefig(plot_path)
56
  plt.close()
57
  return plot_path
58
 
59
- # Step 4: Prediction and Visualization Function
60
  def predict_and_visualize(pressure, temperature, material_type):
61
- # Load the model
 
 
62
  loaded_model = joblib.load("defect_model.pkl")
63
- # Predict
64
  input_data = np.array([[pressure, temperature, material_type]])
65
  prediction = loaded_model.predict(input_data)[0]
66
  defect_map = {0: "No Defect", 1: "Crack", 2: "Wrinkle"}
67
  defect_prediction = defect_map[prediction]
68
-
69
- # Generate visualization
70
  plot_path = plot_simulation(pressure, temperature, material_type)
71
-
72
  return f"Predicted Defect: {defect_prediction}", plot_path
73
 
74
- # Step 5: Create Gradio Interface with Visualization
75
  interface = gr.Interface(
76
  fn=predict_and_visualize,
77
  inputs=[
@@ -84,9 +71,8 @@ interface = gr.Interface(
84
  gr.Image(label="Stress-Strain Visualization")
85
  ],
86
  title="Defect Prediction & Simulation",
87
- description="Predict defect type and visualize stress-strain simulation for input features: Pressure, Temperature, and Material Type."
88
  )
89
 
90
- # Step 6: Launch the Interface
91
  if __name__ == "__main__":
92
  interface.launch()
 
1
+ import os
 
 
2
  import numpy as np
3
  import pandas as pd
4
  import matplotlib.pyplot as plt
 
17
  "Defect_Type": np.random.choice([0, 1, 2], 200, p=[0.6, 0.3, 0.1])
18
  })
19
 
 
20
  X = data[["Pressure", "Temperature", "Material_Type"]]
21
  y = data["Defect_Type"]
22
  X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
23
 
 
24
  model = RandomForestClassifier(n_estimators=100, random_state=42)
25
  model.fit(X_train, y_train)
 
 
26
  joblib.dump(model, "defect_model.pkl")
 
 
27
  y_pred = model.predict(X_test)
28
  print(f"Model Accuracy: {accuracy_score(y_test, y_pred):.2f}")
29
 
30
+ # Visualization Function
31
  def plot_simulation(pressure, temperature, material_type):
32
+ if material_type <= 0 or temperature <= 0:
33
+ raise ValueError("Material type and temperature must be greater than zero.")
34
  stress = np.linspace(pressure * 0.5, pressure * 1.5, 100)
35
  strain = stress / (temperature * 0.01 * material_type)
 
 
36
  plt.figure(figsize=(8, 5))
37
  plt.plot(stress, strain, label="Stress-Strain Curve")
38
  plt.xlabel("Stress (MPa)")
 
40
  plt.title("Stress-Strain Simulation")
41
  plt.legend()
42
  plt.grid(True)
 
 
43
  plot_path = "simulation_plot.png"
44
  plt.savefig(plot_path)
45
  plt.close()
46
  return plot_path
47
 
48
+ # Prediction Function
49
  def predict_and_visualize(pressure, temperature, material_type):
50
+ if not os.path.exists("defect_model.pkl"):
51
+ return "Error: Model file not found. Train the model first.", None
52
+
53
  loaded_model = joblib.load("defect_model.pkl")
 
54
  input_data = np.array([[pressure, temperature, material_type]])
55
  prediction = loaded_model.predict(input_data)[0]
56
  defect_map = {0: "No Defect", 1: "Crack", 2: "Wrinkle"}
57
  defect_prediction = defect_map[prediction]
 
 
58
  plot_path = plot_simulation(pressure, temperature, material_type)
 
59
  return f"Predicted Defect: {defect_prediction}", plot_path
60
 
61
+ # Gradio Interface
62
  interface = gr.Interface(
63
  fn=predict_and_visualize,
64
  inputs=[
 
71
  gr.Image(label="Stress-Strain Visualization")
72
  ],
73
  title="Defect Prediction & Simulation",
74
+ description="Predict defect type and visualize stress-strain simulation for input features."
75
  )
76
 
 
77
  if __name__ == "__main__":
78
  interface.launch()