Flamehaven commited on
Commit
4a6ac9e
·
1 Parent(s): c58dc06

Fix graph rendering errors for HF Spaces deployment

Browse files

- Set matplotlib to use 'Agg' backend for headless environment
- Convert base64 string returns to PIL Image objects
- Add error handling with fallback blank images
- Import PIL.Image for proper image handling
- Both SR9 heatmap and DI2 plot now return PIL Images compatible with Gradio

Files changed (2) hide show
  1. __pycache__/app.cpython-312.pyc +0 -0
  2. app.py +70 -55
__pycache__/app.cpython-312.pyc CHANGED
Binary files a/__pycache__/app.cpython-312.pyc and b/__pycache__/app.cpython-312.pyc differ
 
app.py CHANGED
@@ -5,11 +5,14 @@ Interactive simulation of AGI Ontological Drift using SR9/DI2 framework
5
 
6
  import gradio as gr
7
  import numpy as np
 
 
8
  import matplotlib.pyplot as plt
9
  import io
10
  import base64
11
  from typing import List, Tuple, Dict
12
  import json
 
13
 
14
  # Mock simplified implementation for demo
15
  class SR9Vector:
@@ -110,63 +113,75 @@ def simulate_drift_scenario(ethical_declarations: List[str], drift_intensity: fl
110
 
111
  return sr9_history, di2_history, alerts
112
 
113
- def create_sr9_heatmap(sr9_history: List[SR9Vector]) -> str:
114
  """Create SR9 values heatmap over time"""
115
- fig, ax = plt.subplots(figsize=(12, 8))
116
-
117
- # Prepare data matrix
118
- data_matrix = np.array([sr9.values for sr9 in sr9_history]).T
119
-
120
- # Create heatmap
121
- im = ax.imshow(data_matrix, cmap='RdYlGn', aspect='auto', vmin=0, vmax=1)
122
-
123
- # Set labels
124
- ax.set_yticks(range(len(SR9Vector.DIMENSIONS)))
125
- ax.set_yticklabels(SR9Vector.DIMENSIONS)
126
- ax.set_xlabel('Time Steps')
127
- ax.set_ylabel('SR9 Dimensions')
128
- ax.set_title('SR9 Ethical State Evolution Heatmap')
129
-
130
- # Add colorbar
131
- cbar = plt.colorbar(im, ax=ax)
132
- cbar.set_label('Ethical Alignment Score', rotation=270, labelpad=20)
133
-
134
- # Convert to base64
135
- buffer = io.BytesIO()
136
- plt.savefig(buffer, format='png', dpi=150, bbox_inches='tight')
137
- buffer.seek(0)
138
- img_base64 = base64.b64encode(buffer.read()).decode()
139
- plt.close(fig)
140
-
141
- return f"data:image/png;base64,{img_base64}"
142
-
143
- def create_di2_plot(di2_history: List[float]) -> str:
 
 
 
 
 
 
144
  """Create DI2 drift plot over time"""
145
- fig, ax = plt.subplots(figsize=(12, 6))
146
-
147
- steps = list(range(len(di2_history)))
148
- ax.plot(steps, di2_history, 'b-o', linewidth=2, markersize=4)
149
- ax.fill_between(steps, di2_history, alpha=0.3)
150
-
151
- # Add threshold lines
152
- ax.axhline(y=0.2, color='orange', linestyle='--', alpha=0.7, label='Warning Threshold')
153
- ax.axhline(y=0.3, color='red', linestyle='--', alpha=0.7, label='Critical Threshold')
154
-
155
- ax.set_xlabel('Time Steps')
156
- ax.set_ylabel('DI2 (Drift Integrity Index)')
157
- ax.set_title('Ontological Drift Detection Over Time')
158
- ax.grid(True, alpha=0.3)
159
- ax.legend()
160
- ax.set_ylim(0, max(1.0, max(di2_history) * 1.1))
161
-
162
- # Convert to base64
163
- buffer = io.BytesIO()
164
- plt.savefig(buffer, format='png', dpi=150, bbox_inches='tight')
165
- buffer.seek(0)
166
- img_base64 = base64.b64encode(buffer.read()).decode()
167
- plt.close(fig)
168
-
169
- return f"data:image/png;base64,{img_base64}"
 
 
 
 
 
 
170
 
171
  def drift_simulation_demo(ethical_declarations: str, drift_intensity: float, simulation_steps: int):
172
  """Main demo function for Ethical AGI Drift simulation"""
 
5
 
6
  import gradio as gr
7
  import numpy as np
8
+ import matplotlib
9
+ matplotlib.use('Agg') # Use non-interactive backend for HF Spaces
10
  import matplotlib.pyplot as plt
11
  import io
12
  import base64
13
  from typing import List, Tuple, Dict
14
  import json
15
+ from PIL import Image
16
 
17
  # Mock simplified implementation for demo
18
  class SR9Vector:
 
113
 
114
  return sr9_history, di2_history, alerts
115
 
116
+ def create_sr9_heatmap(sr9_history: List[SR9Vector]):
117
  """Create SR9 values heatmap over time"""
118
+ try:
119
+ fig, ax = plt.subplots(figsize=(12, 8))
120
+
121
+ # Prepare data matrix
122
+ data_matrix = np.array([sr9.values for sr9 in sr9_history]).T
123
+
124
+ # Create heatmap
125
+ im = ax.imshow(data_matrix, cmap='RdYlGn', aspect='auto', vmin=0, vmax=1)
126
+
127
+ # Set labels
128
+ ax.set_yticks(range(len(SR9Vector.DIMENSIONS)))
129
+ ax.set_yticklabels(SR9Vector.DIMENSIONS)
130
+ ax.set_xlabel('Time Steps')
131
+ ax.set_ylabel('SR9 Dimensions')
132
+ ax.set_title('SR9 Ethical State Evolution Heatmap')
133
+
134
+ # Add colorbar
135
+ cbar = plt.colorbar(im, ax=ax)
136
+ cbar.set_label('Ethical Alignment Score', rotation=270, labelpad=20)
137
+
138
+ # Convert to PIL Image
139
+ buffer = io.BytesIO()
140
+ plt.savefig(buffer, format='png', dpi=150, bbox_inches='tight')
141
+ buffer.seek(0)
142
+ pil_image = Image.open(buffer)
143
+ plt.close(fig)
144
+
145
+ return pil_image
146
+ except Exception as e:
147
+ print(f"Error creating SR9 heatmap: {e}")
148
+ # Return a blank image if error occurs
149
+ blank_img = Image.new('RGB', (800, 600), color='white')
150
+ return blank_img
151
+
152
+ def create_di2_plot(di2_history: List[float]):
153
  """Create DI2 drift plot over time"""
154
+ try:
155
+ fig, ax = plt.subplots(figsize=(12, 6))
156
+
157
+ steps = list(range(len(di2_history)))
158
+ ax.plot(steps, di2_history, 'b-o', linewidth=2, markersize=4)
159
+ ax.fill_between(steps, di2_history, alpha=0.3)
160
+
161
+ # Add threshold lines
162
+ ax.axhline(y=0.2, color='orange', linestyle='--', alpha=0.7, label='Warning Threshold')
163
+ ax.axhline(y=0.3, color='red', linestyle='--', alpha=0.7, label='Critical Threshold')
164
+
165
+ ax.set_xlabel('Time Steps')
166
+ ax.set_ylabel('DI2 (Drift Integrity Index)')
167
+ ax.set_title('Ontological Drift Detection Over Time')
168
+ ax.grid(True, alpha=0.3)
169
+ ax.legend()
170
+ ax.set_ylim(0, max(1.0, max(di2_history) * 1.1))
171
+
172
+ # Convert to PIL Image
173
+ buffer = io.BytesIO()
174
+ plt.savefig(buffer, format='png', dpi=150, bbox_inches='tight')
175
+ buffer.seek(0)
176
+ pil_image = Image.open(buffer)
177
+ plt.close(fig)
178
+
179
+ return pil_image
180
+ except Exception as e:
181
+ print(f"Error creating DI2 plot: {e}")
182
+ # Return a blank image if error occurs
183
+ blank_img = Image.new('RGB', (800, 600), color='white')
184
+ return blank_img
185
 
186
  def drift_simulation_demo(ethical_declarations: str, drift_intensity: float, simulation_steps: int):
187
  """Main demo function for Ethical AGI Drift simulation"""