mic3333 commited on
Commit
f7d9f2d
Β·
verified Β·
1 Parent(s): 9b66796

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +86 -182
app.py CHANGED
@@ -1,17 +1,17 @@
1
  #!/usr/bin/env python3
2
  """
3
- Simple, Reliable Plotly + Pyodide - Back to Basics
4
  """
5
 
6
  import gradio as gr
7
 
8
  def create_pyodide_interface():
9
- """Simple working interface without complex conversions"""
10
 
11
  pyodide_html = '''
12
  <div id="pyodide-container" style="border: 1px solid #ddd; padding: 15px; border-radius: 5px; margin: 10px 0;">
13
  <div id="status" style="font-weight: bold; padding: 10px; background: #f0f0f0; border-radius: 3px;">
14
- πŸ”„ Loading Pyodide + Plotly...
15
  </div>
16
  <div id="output" style="display:none; margin-top: 10px;">
17
  <h4>Output:</h4>
@@ -31,10 +31,8 @@ def create_pyodide_interface():
31
  function updateStatus(msg, color = 'black') {
32
  document.getElementById('status').innerHTML = msg;
33
  document.getElementById('status').style.color = color;
34
- console.log('Status:', msg);
35
  }
36
 
37
- // Simple plot renderer
38
  window.createPlot = function(data, layout) {
39
  try {
40
  plotCount++;
@@ -43,17 +41,15 @@ def create_pyodide_interface():
43
 
44
  const plotDiv = document.createElement('div');
45
  plotDiv.innerHTML = `
46
- <h5>πŸ“ˆ Plot ${plotCount}</h5>
47
- <div id="${plotId}" style="width: 100%; height: 500px; border: 1px solid #ccc; margin: 10px 0;"></div>
48
  `;
49
  plotsDiv.appendChild(plotDiv);
50
 
51
- // Parse if strings
52
  if (typeof data === 'string') data = JSON.parse(data);
53
  if (typeof layout === 'string') layout = JSON.parse(layout);
54
 
55
  Plotly.newPlot(plotId, data, layout, {responsive: true});
56
- console.log('Plot created:', plotId);
57
  return true;
58
 
59
  } catch (error) {
@@ -62,274 +58,182 @@ def create_pyodide_interface():
62
  }
63
  };
64
 
65
- async function initPyodide() {
66
  try {
67
- updateStatus('πŸ”„ Loading Pyodide...', 'blue');
68
  pyodide = await loadPyodide();
69
 
70
- updateStatus('πŸ“¦ Installing packages...', 'blue');
71
  await pyodide.loadPackage(['numpy', 'pandas', 'micropip']);
72
-
73
- updateStatus('πŸ“ˆ Installing Plotly...', 'blue');
74
  await pyodide.runPythonAsync(`
75
  import micropip
76
  await micropip.install('plotly')
77
  `);
78
 
79
- updateStatus('πŸ”§ Setting up environment...', 'blue');
80
-
81
- // Simple Python setup - no complex conversions
82
  pyodide.runPython(`
83
  import json
84
  from js import createPlot
85
 
86
- def simple_show(fig):
87
  try:
88
- # Get the figure as dict
89
  fig_dict = fig.to_dict()
90
-
91
- # Simple approach: let Python handle the conversion
92
  data_json = json.dumps(fig_dict.get('data', []))
93
  layout_json = json.dumps(fig_dict.get('layout', {}))
94
-
95
- # Call JavaScript
96
  success = createPlot(data_json, layout_json)
97
-
98
  if success:
99
- print("Plot created!")
100
- return True
101
- else:
102
- print("Plot failed")
103
- return False
104
-
105
  except Exception as e:
106
  print(f"Plot error: {e}")
107
  return False
108
 
109
- # Setup Plotly
110
  try:
111
  import plotly.graph_objects as go
112
  import plotly.express as px
113
-
114
- # Replace show method
115
- go.Figure.show = lambda self, *args, **kwargs: simple_show(self)
116
-
117
  print("Plotly ready!")
118
-
119
  except Exception as e:
120
- print(f"Plotly setup error: {e}")
121
-
122
- print("Environment ready!")
123
  `);
124
 
125
  ready = true;
126
  updateStatus('βœ… Ready!', 'green');
127
 
128
  document.getElementById('output').style.display = 'block';
129
- document.getElementById('text-output').textContent = 'System ready. Try the simple examples.';
130
 
131
  } catch (error) {
132
- console.error('Initialization error:', error);
133
  updateStatus('❌ Error: ' + error.message, 'red');
134
  }
135
  }
136
 
137
  async function runCode(code) {
138
- if (!ready) return 'System not ready';
139
 
140
  try {
141
  updateStatus('▢️ Running...', 'blue');
142
 
143
- // Clear plots
144
  document.getElementById('plots').innerHTML = '';
145
 
146
- // Capture output
147
  pyodide.runPython(`
148
  import sys
149
  from io import StringIO
150
  old_stdout = sys.stdout
151
- sys.stdout = output = StringIO()
152
  `);
153
 
154
- // Run code
155
  pyodide.runPython(code);
156
 
157
- // Get output
158
- let result = pyodide.runPython(`
159
  sys.stdout = old_stdout
160
- output.getvalue()
161
  `);
162
 
163
- document.getElementById('text-output').textContent = result || 'Code executed';
164
- updateStatus('βœ… Complete', 'green');
165
 
166
- return result || 'Success';
167
 
168
  } catch (error) {
169
- const errorMsg = 'Error: ' + error.toString();
170
- document.getElementById('text-output').textContent = errorMsg;
171
  updateStatus('❌ Error', 'red');
172
- return errorMsg;
173
  }
174
  }
175
 
176
- // Initialize
177
- function startInit() {
178
  if (typeof loadPyodide !== 'undefined' && typeof Plotly !== 'undefined') {
179
- initPyodide();
180
  } else {
181
- setTimeout(startInit, 1000);
182
  }
183
  }
184
 
185
- startInit();
186
 
187
- // Global functions
188
  window.runCode = runCode;
189
- window.isReady = () => ready;
190
 
191
  </script>
192
  '''
193
 
194
  return pyodide_html
195
 
196
- with gr.Blocks(title="Simple Plotly Test") as demo:
197
- gr.Markdown("# πŸ”§ Simple Plotly Test")
198
- gr.Markdown("**Back to basics** - Let's get the fundamental setup working first.")
199
-
200
- pyodide_interface = gr.HTML(create_pyodide_interface())
201
-
202
- with gr.Row():
203
- with gr.Column():
204
- code_input = gr.Textbox(
205
- value="""# Test 1: Absolute basics with Python lists
206
- import plotly.graph_objects as go
207
-
208
- print("Creating basic plot with Python lists...")
209
 
210
- # Use plain Python lists (no NumPy)
211
- x_list = [1, 2, 3, 4, 5]
212
- y_list = [1, 4, 9, 16, 25]
 
 
 
 
213
 
214
- print(f"X: {x_list}")
215
- print(f"Y: {y_list}")
 
 
 
 
 
 
216
 
217
- fig = go.Figure()
218
- fig.add_trace(go.Scatter(
219
- x=x_list,
220
- y=y_list,
221
- mode='markers+lines',
222
- name='Basic Test'
223
- ))
224
 
225
- fig.update_layout(title='Basic Test - Python Lists Only')
 
226
  fig.show()
227
-
228
- print("Basic test complete!")""",
229
- lines=15,
230
- label="Test Code"
231
- )
232
-
233
- run_btn = gr.Button("πŸš€ Run Test", variant="primary")
234
-
235
- with gr.Column():
236
- status_output = gr.Textbox(
237
- label="Result",
238
- interactive=False,
239
- lines=3
240
- )
241
-
242
- # Quick test buttons
243
- basic_btn = gr.Button("Test: Python Lists", variant="secondary")
244
- express_btn = gr.Button("Test: Plotly Express", variant="secondary")
245
- numpy_manual_btn = gr.Button("Test: NumPy Manual", variant="secondary")
246
-
247
- gr.Markdown("""
248
- ### 🎯 **Testing Strategy:**
249
-
250
- 1. **Python Lists** - Should work (no NumPy conversion issues)
251
- 2. **Plotly Express** - You said this works
252
- 3. **NumPy Manual** - Convert arrays manually with `.tolist()`
253
-
254
- ### πŸ“ **Test Examples:**
255
-
256
- **Safe Python Lists:**
257
- ```python
258
- x = [1, 2, 3, 4, 5] # Plain list
259
- y = [1, 4, 9, 16, 25] # Plain list
260
- fig.add_trace(go.Scatter(x=x, y=y))
261
- ```
262
-
263
- **Manual NumPy Conversion:**
264
- ```python
265
- x = np.array([1, 2, 3, 4, 5])
266
- y = np.array([1, 4, 9, 16, 25])
267
- fig.add_trace(go.Scatter(x=x.tolist(), y=y.tolist())) # Manual .tolist()
268
- ```
269
- """)
270
 
271
- def get_basic_test():
272
- return """# Basic Python Lists Test
273
- import plotly.graph_objects as go
274
 
275
- x = [1, 2, 3, 4, 5]
276
- y = [2, 4, 6, 8, 10]
 
 
277
 
278
- fig = go.Figure()
279
- fig.add_trace(go.Scatter(x=x, y=y, mode='markers+lines'))
280
- fig.update_layout(title='Python Lists Test')
281
  fig.show()
282
- print("Python lists test done!")"""
283
 
284
- def get_express_test():
285
- return """# Plotly Express Test
286
  import plotly.express as px
287
  import pandas as pd
288
 
289
- df = pd.DataFrame({'x': [1,2,3,4], 'y': [1,4,9,16]})
290
- fig = px.scatter(df, x='x', y='y', title='Express Test')
 
 
 
 
291
  fig.show()
292
- print("Express test done!")"""
293
 
294
- def get_numpy_manual_test():
295
- return """# NumPy with Manual Conversion
296
- import plotly.graph_objects as go
297
  import numpy as np
298
 
299
- print("Creating NumPy arrays...")
300
- x = np.array([1, 2, 3, 4, 5])
301
- y = np.array([1, 4, 9, 16, 25])
 
 
 
302
 
303
- print("Converting to lists manually...")
304
- x_list = x.tolist() # Manual conversion
305
- y_list = y.tolist() # Manual conversion
306
 
307
- print(f"Converted X: {x_list}")
308
- print(f"Converted Y: {y_list}")
309
-
310
- fig = go.Figure()
311
- fig.add_trace(go.Scatter(
312
- x=x_list,
313
- y=y_list,
314
- mode='markers+lines',
315
- marker=dict(size=8, color='red')
316
- ))
317
- fig.update_layout(title='NumPy Manual Conversion')
318
  fig.show()
319
- print("Manual NumPy conversion test done!")"""
320
-
321
- # Event handlers
322
- run_btn.click(
323
- fn=None,
324
- inputs=[code_input],
325
- outputs=[status_output],
326
- js="(code) => window.runCode ? window.runCode(code) : 'Not ready'"
327
- )
328
-
329
- basic_btn.click(fn=get_basic_test, outputs=[code_input])
330
- express_btn.click(fn=get_express_test, outputs=[code_input])
331
- numpy_manual_btn.click(fn=get_numpy_manual_test, outputs=[code_input])
332
-
333
- if __name__ == "__main__":
334
- print("πŸš€ Starting Simple Plotly Test...")
335
- demo.launch(server_name="0.0.0.0", server_port=7860, share=False)
 
1
  #!/usr/bin/env python3
2
  """
3
+ Plotly Express Test Interface - Try Different Examples
4
  """
5
 
6
  import gradio as gr
7
 
8
  def create_pyodide_interface():
9
+ """Simple interface to test different Express examples"""
10
 
11
  pyodide_html = '''
12
  <div id="pyodide-container" style="border: 1px solid #ddd; padding: 15px; border-radius: 5px; margin: 10px 0;">
13
  <div id="status" style="font-weight: bold; padding: 10px; background: #f0f0f0; border-radius: 3px;">
14
+ πŸ”„ Loading Pyodide...
15
  </div>
16
  <div id="output" style="display:none; margin-top: 10px;">
17
  <h4>Output:</h4>
 
31
  function updateStatus(msg, color = 'black') {
32
  document.getElementById('status').innerHTML = msg;
33
  document.getElementById('status').style.color = color;
 
34
  }
35
 
 
36
  window.createPlot = function(data, layout) {
37
  try {
38
  plotCount++;
 
41
 
42
  const plotDiv = document.createElement('div');
43
  plotDiv.innerHTML = `
44
+ <h5>πŸ“Š Plot ${plotCount}</h5>
45
+ <div id="${plotId}" style="width: 100%; height: 400px; border: 1px solid #ccc; margin: 10px 0;"></div>
46
  `;
47
  plotsDiv.appendChild(plotDiv);
48
 
 
49
  if (typeof data === 'string') data = JSON.parse(data);
50
  if (typeof layout === 'string') layout = JSON.parse(layout);
51
 
52
  Plotly.newPlot(plotId, data, layout, {responsive: true});
 
53
  return true;
54
 
55
  } catch (error) {
 
58
  }
59
  };
60
 
61
+ async function init() {
62
  try {
63
+ updateStatus('πŸ”„ Loading...', 'blue');
64
  pyodide = await loadPyodide();
65
 
 
66
  await pyodide.loadPackage(['numpy', 'pandas', 'micropip']);
 
 
67
  await pyodide.runPythonAsync(`
68
  import micropip
69
  await micropip.install('plotly')
70
  `);
71
 
 
 
 
72
  pyodide.runPython(`
73
  import json
74
  from js import createPlot
75
 
76
+ def show_plot(fig):
77
  try:
 
78
  fig_dict = fig.to_dict()
 
 
79
  data_json = json.dumps(fig_dict.get('data', []))
80
  layout_json = json.dumps(fig_dict.get('layout', {}))
 
 
81
  success = createPlot(data_json, layout_json)
 
82
  if success:
83
+ print("Plot displayed!")
84
+ return success
 
 
 
 
85
  except Exception as e:
86
  print(f"Plot error: {e}")
87
  return False
88
 
 
89
  try:
90
  import plotly.graph_objects as go
91
  import plotly.express as px
92
+ go.Figure.show = lambda self, *args, **kwargs: show_plot(self)
 
 
 
93
  print("Plotly ready!")
 
94
  except Exception as e:
95
+ print(f"Setup error: {e}")
 
 
96
  `);
97
 
98
  ready = true;
99
  updateStatus('βœ… Ready!', 'green');
100
 
101
  document.getElementById('output').style.display = 'block';
102
+ document.getElementById('text-output').textContent = 'Ready to test Plotly Express examples!';
103
 
104
  } catch (error) {
 
105
  updateStatus('❌ Error: ' + error.message, 'red');
106
  }
107
  }
108
 
109
  async function runCode(code) {
110
+ if (!ready) return 'Not ready';
111
 
112
  try {
113
  updateStatus('▢️ Running...', 'blue');
114
 
 
115
  document.getElementById('plots').innerHTML = '';
116
 
 
117
  pyodide.runPython(`
118
  import sys
119
  from io import StringIO
120
  old_stdout = sys.stdout
121
+ sys.stdout = capture = StringIO()
122
  `);
123
 
 
124
  pyodide.runPython(code);
125
 
126
+ let output = pyodide.runPython(`
 
127
  sys.stdout = old_stdout
128
+ capture.getvalue()
129
  `);
130
 
131
+ document.getElementById('text-output').textContent = output || 'Code executed';
132
+ updateStatus('βœ… Done', 'green');
133
 
134
+ return output || 'Success';
135
 
136
  } catch (error) {
137
+ const err = 'Error: ' + error.toString();
138
+ document.getElementById('text-output').textContent = err;
139
  updateStatus('❌ Error', 'red');
140
+ return err;
141
  }
142
  }
143
 
144
+ function waitForCDN() {
 
145
  if (typeof loadPyodide !== 'undefined' && typeof Plotly !== 'undefined') {
146
+ init();
147
  } else {
148
+ setTimeout(waitForCDN, 1000);
149
  }
150
  }
151
 
152
+ waitForCDN();
153
 
 
154
  window.runCode = runCode;
 
155
 
156
  </script>
157
  '''
158
 
159
  return pyodide_html
160
 
161
+ # Example templates
162
+ examples = {
163
+ "Minimal Test": '''# Absolute minimal test
164
+ import plotly.express as px
 
 
 
 
 
 
 
 
 
165
 
166
+ print("Testing minimal Express...")
167
+ fig = px.scatter(x=[1, 2], y=[1, 2], title="Minimal")
168
+ fig.show()
169
+ print("Minimal test complete!")''',
170
+
171
+ "Direct Arrays": '''# Test without DataFrame
172
+ import plotly.express as px
173
 
174
+ print("Testing direct arrays...")
175
+ fig = px.scatter(x=[1, 2, 3, 4], y=[1, 4, 9, 16], title="Direct Arrays")
176
+ fig.show()
177
+ print("Direct arrays test complete!")''',
178
+
179
+ "Simple DataFrame": '''# Simple DataFrame test
180
+ import plotly.express as px
181
+ import pandas as pd
182
 
183
+ print("Creating DataFrame...")
184
+ df = pd.DataFrame({
185
+ 'x': [1, 2, 3, 4, 5],
186
+ 'y': [2, 4, 6, 8, 10]
187
+ })
188
+ print("DataFrame:")
189
+ print(df)
190
 
191
+ print("Creating plot...")
192
+ fig = px.scatter(df, x='x', y='y', title='DataFrame Test')
193
  fig.show()
194
+ print("DataFrame test complete!")''',
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
195
 
196
+ "Line Chart": '''# Line chart test
197
+ import plotly.express as px
198
+ import pandas as pd
199
 
200
+ df = pd.DataFrame({
201
+ 'x': [1, 2, 3, 4, 5],
202
+ 'y': [1, 4, 2, 8, 5]
203
+ })
204
 
205
+ fig = px.line(df, x='x', y='y', title='Line Chart')
 
 
206
  fig.show()
207
+ print("Line chart complete!")''',
208
 
209
+ "Bar Chart": '''# Bar chart test
 
210
  import plotly.express as px
211
  import pandas as pd
212
 
213
+ df = pd.DataFrame({
214
+ 'category': ['A', 'B', 'C', 'D'],
215
+ 'values': [20, 35, 30, 25]
216
+ })
217
+
218
+ fig = px.bar(df, x='category', y='values', title='Bar Chart')
219
  fig.show()
220
+ print("Bar chart complete!")''',
221
 
222
+ "Data Types": '''# Test different data types
223
+ import plotly.express as px
224
+ import pandas as pd
225
  import numpy as np
226
 
227
+ print("Creating mixed data types...")
228
+ df = pd.DataFrame({
229
+ 'int_col': [1, 2, 3, 4],
230
+ 'float_col': [1.1, 2.2, 3.3, 4.4],
231
+ 'numpy_col': np.array([1, 2, 3, 4])
232
+ })
233
 
234
+ print("DataFrame info:")
235
+ print(df.dtypes)
 
236
 
237
+ fig = px.scatter(df, x='int_col', y='float_col', title='Data Types')
 
 
 
 
 
 
 
 
 
 
238
  fig.show()
239
+ print("Data typ