theunknowntechie1 commited on
Commit
7f54610
·
verified ·
1 Parent(s): ea9449c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -61
app.py CHANGED
@@ -1,29 +1,24 @@
 
1
  import os
2
- # Set environment variables BEFORE importing torch
3
- os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # Force CPU-only mode
4
- os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0' # Disable oneDNN custom operations
 
5
 
6
- # Ensure entropy source is available
7
- try:
8
- # Try to initialize Python's RNG with system entropy
9
- random_bytes = os.urandom(16)
10
- except Exception:
11
- # Fallback to less secure method if system entropy fails
12
- import time
13
- os.environ['PYTHONHASHSEED'] = str(time.time())
14
-
15
- import gradio as gr
16
- import tensorflow as tf
17
  import numpy as np
18
- from PIL import Image
19
- import json
20
 
21
- # Suppress TensorFlow warnings
22
- os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
23
- tf.get_logger().setLevel('ERROR')
 
 
24
 
25
- # DEFER TORCH IMPORT UNTIL AFTER ENVIRONMENT SETUP
26
- import torch
 
27
  from torch_geometric.data import Data
28
  from torch_geometric.nn import GCNConv, global_mean_pool
29
  import torch.nn.functional as F
@@ -45,33 +40,45 @@ class GNN(torch.nn.Module):
45
  x = global_mean_pool(x, batch)
46
  return self.fc(x)
47
 
48
- # Model paths
49
  cnn_model_path = "final_cnn_model.h5"
50
  improved_model_path = "improved_model.h5"
51
  gnn_model_path = "higgs_gnn_model_cpu.pth"
52
 
53
- # Initialize models as None (will lazy-load later)
54
  cnn_model = None
55
  improved_model = None
56
  gnn_model = None
57
 
58
- # Prediction functions
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
  def predict_image(image):
60
- global cnn_model
61
  if image is None:
62
  return "Error: No image provided"
63
  if cnn_model is None:
64
- try:
65
- print("Loading CNN model...")
66
- cnn_model = tf.keras.models.load_model(cnn_model_path)
67
- print("CNN model loaded successfully")
68
- except Exception as e:
69
- return f"Error loading CNN model: {e}"
70
  try:
71
- # Convert to grayscale and resize to (25, 25)
72
  image = image.convert("L").resize((25, 25))
73
  image_array = np.array(image) / 255.0
74
- # Reshape to (1, 25, 25, 1) for the new model
75
  image_array = np.expand_dims(image_array, axis=(0, -1))
76
  prediction = cnn_model.predict(image_array)[0][0]
77
  label = "Signal" if prediction > 0.5 else "Background"
@@ -80,67 +87,44 @@ def predict_image(image):
80
  return f"Error processing image: {str(e)}"
81
 
82
  def predict_numerical(data):
83
- global improved_model
84
  if not data:
85
  return "Error: No numerical data provided"
86
  if improved_model is None:
87
- try:
88
- print("Loading Improved model...")
89
- improved_model = tf.keras.models.load_model(improved_model_path)
90
- print("Improved model loaded successfully")
91
- except Exception as e:
92
- return f"Error loading Improved model: {e}"
93
  try:
94
- # Convert comma-separated input to numpy array and reshape to (1, n_features)
95
  input_data = np.array([float(x) for x in data.split(",")], dtype=np.float32)
96
- # Check if the number of features matches the model's expected input
97
  expected_features = improved_model.input_shape[1]
98
  if len(input_data) != expected_features:
99
- return f"Error: Expected {expected_features} features, got {len(input_data)}. Provide correct number of comma-separated values."
100
  input_data = input_data.reshape(1, expected_features)
101
- # Predict using the improved model
102
  prediction = improved_model.predict(input_data)
103
- # Get the class with the highest probability
104
  predicted_class = np.argmax(prediction, axis=1)[0]
105
- # Get the probability of the predicted class
106
  confidence = prediction[0][predicted_class]
107
  return f"Improved Model Prediction: Class {predicted_class} (Confidence: {confidence:.4f})"
108
  except Exception as e:
109
  return f"Error processing numerical data: {str(e)}"
110
 
111
  def predict_graph(graph_json):
112
- global gnn_model
113
  if not graph_json:
114
  return "Error: No graph JSON provided"
115
  if gnn_model is None:
116
- try:
117
- print("Loading GNN model...")
118
- gnn_model = GNN()
119
- gnn_model.load_state_dict(torch.load(gnn_model_path, map_location='cpu'))
120
- gnn_model.eval()
121
- print("GNN model loaded successfully")
122
- except Exception as e:
123
- return f"Error loading GNN model: {e}"
124
  try:
125
  graph_data = json.loads(graph_json)
126
-
127
- # Convert to PyG Data format
128
  x = torch.tensor(graph_data['x'], dtype=torch.float32)
129
  edge_index = torch.tensor(graph_data['edge_index'], dtype=torch.long)
130
-
131
- # Create a batch with single graph
132
  data = Data(x=x, edge_index=edge_index)
133
  data.batch = torch.zeros(data.num_nodes, dtype=torch.long)
134
-
135
  with torch.no_grad():
136
  out = gnn_model(data)
137
  prob = F.softmax(out, dim=1)[0][1].item()
138
-
139
  return f"GNN Prediction: Signal Probability = {prob:.4f}"
140
  except Exception as e:
141
  return f"Error processing graph: {str(e)}"
142
 
143
  # Gradio Interface
 
 
144
  with gr.Blocks(title="Multi-Model Gradio Interface") as demo:
145
  gr.Markdown("## Multi-Model Prediction Interface")
146
 
 
1
+ # Set environment variables **before** importing libraries
2
  import os
3
+ os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # Suppress TensorFlow warnings
4
+ os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0' # Disable oneDNN custom ops
5
+ os.environ['PYTHONHASHSEED'] = '0' # Ensure reproducibility
6
+ os.environ['PYTORCH_NO_CUDA_MEMORY_CACHING'] = '1' # Reduce RNG reliance
7
 
8
+ # Set deterministic behavior for PyTorch
9
+ import torch
 
 
 
 
 
 
 
 
 
10
  import numpy as np
11
+ import tensorflow as tf
 
12
 
13
+ # Fix: Set seeds **before** model initialization
14
+ torch.manual_seed(42)
15
+ torch.use_deterministic_algorithms(True)
16
+ np.random.seed(42)
17
+ tf.random.set_seed(42)
18
 
19
+ # Import remaining libraries
20
+ import json
21
+ from PIL import Image
22
  from torch_geometric.data import Data
23
  from torch_geometric.nn import GCNConv, global_mean_pool
24
  import torch.nn.functional as F
 
40
  x = global_mean_pool(x, batch)
41
  return self.fc(x)
42
 
43
+ # Load models
44
  cnn_model_path = "final_cnn_model.h5"
45
  improved_model_path = "improved_model.h5"
46
  gnn_model_path = "higgs_gnn_model_cpu.pth"
47
 
48
+ # Initialize models as None
49
  cnn_model = None
50
  improved_model = None
51
  gnn_model = None
52
 
53
+ # Load models with error handling
54
+ try:
55
+ cnn_model = tf.keras.models.load_model(cnn_model_path)
56
+ print(f"CNN model loaded successfully from {cnn_model_path}")
57
+ except Exception as e:
58
+ print(f"Error loading CNN model: {e}")
59
+
60
+ try:
61
+ improved_model = tf.keras.models.load_model(improved_model_path)
62
+ print(f"Improved model loaded successfully from {improved_model_path}")
63
+ except Exception as e:
64
+ print(f"Error loading Improved model: {e}")
65
+
66
+ try:
67
+ gnn_model = GNN()
68
+ gnn_model.load_state_dict(torch.load(gnn_model_path, map_location='cpu'))
69
+ gnn_model.eval()
70
+ except Exception as e:
71
+ print(f"Error loading GNN model: {e}")
72
+
73
+ # Prediction functions (unchanged from original)
74
  def predict_image(image):
 
75
  if image is None:
76
  return "Error: No image provided"
77
  if cnn_model is None:
78
+ return "Error: CNN model failed to load. Please check the model file."
 
 
 
 
 
79
  try:
 
80
  image = image.convert("L").resize((25, 25))
81
  image_array = np.array(image) / 255.0
 
82
  image_array = np.expand_dims(image_array, axis=(0, -1))
83
  prediction = cnn_model.predict(image_array)[0][0]
84
  label = "Signal" if prediction > 0.5 else "Background"
 
87
  return f"Error processing image: {str(e)}"
88
 
89
  def predict_numerical(data):
 
90
  if not data:
91
  return "Error: No numerical data provided"
92
  if improved_model is None:
93
+ return "Error: Improved model failed to load. Please check the model file."
 
 
 
 
 
94
  try:
 
95
  input_data = np.array([float(x) for x in data.split(",")], dtype=np.float32)
 
96
  expected_features = improved_model.input_shape[1]
97
  if len(input_data) != expected_features:
98
+ return f"Error: Expected {expected_features} features, got {len(input_data)}."
99
  input_data = input_data.reshape(1, expected_features)
 
100
  prediction = improved_model.predict(input_data)
 
101
  predicted_class = np.argmax(prediction, axis=1)[0]
 
102
  confidence = prediction[0][predicted_class]
103
  return f"Improved Model Prediction: Class {predicted_class} (Confidence: {confidence:.4f})"
104
  except Exception as e:
105
  return f"Error processing numerical data: {str(e)}"
106
 
107
  def predict_graph(graph_json):
 
108
  if not graph_json:
109
  return "Error: No graph JSON provided"
110
  if gnn_model is None:
111
+ return "Error: GNN model failed to load"
 
 
 
 
 
 
 
112
  try:
113
  graph_data = json.loads(graph_json)
 
 
114
  x = torch.tensor(graph_data['x'], dtype=torch.float32)
115
  edge_index = torch.tensor(graph_data['edge_index'], dtype=torch.long)
 
 
116
  data = Data(x=x, edge_index=edge_index)
117
  data.batch = torch.zeros(data.num_nodes, dtype=torch.long)
 
118
  with torch.no_grad():
119
  out = gnn_model(data)
120
  prob = F.softmax(out, dim=1)[0][1].item()
 
121
  return f"GNN Prediction: Signal Probability = {prob:.4f}"
122
  except Exception as e:
123
  return f"Error processing graph: {str(e)}"
124
 
125
  # Gradio Interface
126
+ import gradio as gr
127
+
128
  with gr.Blocks(title="Multi-Model Gradio Interface") as demo:
129
  gr.Markdown("## Multi-Model Prediction Interface")
130