libre-code / app.py
mic3333's picture
Update app.py
f7d9f2d verified
raw
history blame
7.26 kB
#!/usr/bin/env python3
"""
Plotly Express Test Interface - Try Different Examples
"""
import gradio as gr
def create_pyodide_interface():
"""Simple interface to test different Express examples"""
pyodide_html = '''
<div id="pyodide-container" style="border: 1px solid #ddd; padding: 15px; border-radius: 5px; margin: 10px 0;">
<div id="status" style="font-weight: bold; padding: 10px; background: #f0f0f0; border-radius: 3px;">
🔄 Loading Pyodide...
</div>
<div id="output" style="display:none; margin-top: 10px;">
<h4>Output:</h4>
<pre id="text-output" style="background: #f8f8f8; padding: 10px; border-radius: 3px; max-height: 200px; overflow-y: auto;"></pre>
<div id="plots" style="margin-top: 15px;"></div>
</div>
</div>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<script src="https://cdn.jsdelivr.net/pyodide/v0.25.0/full/pyodide.js"></script>
<script>
let pyodide = null;
let ready = false;
let plotCount = 0;
function updateStatus(msg, color = 'black') {
document.getElementById('status').innerHTML = msg;
document.getElementById('status').style.color = color;
}
window.createPlot = function(data, layout) {
try {
plotCount++;
const plotId = 'plot-' + plotCount;
const plotsDiv = document.getElementById('plots');
const plotDiv = document.createElement('div');
plotDiv.innerHTML = `
<h5>📊 Plot ${plotCount}</h5>
<div id="${plotId}" style="width: 100%; height: 400px; border: 1px solid #ccc; margin: 10px 0;"></div>
`;
plotsDiv.appendChild(plotDiv);
if (typeof data === 'string') data = JSON.parse(data);
if (typeof layout === 'string') layout = JSON.parse(layout);
Plotly.newPlot(plotId, data, layout, {responsive: true});
return true;
} catch (error) {
console.error('Plot error:', error);
return false;
}
};
async function init() {
try {
updateStatus('🔄 Loading...', 'blue');
pyodide = await loadPyodide();
await pyodide.loadPackage(['numpy', 'pandas', 'micropip']);
await pyodide.runPythonAsync(`
import micropip
await micropip.install('plotly')
`);
pyodide.runPython(`
import json
from js import createPlot
def show_plot(fig):
try:
fig_dict = fig.to_dict()
data_json = json.dumps(fig_dict.get('data', []))
layout_json = json.dumps(fig_dict.get('layout', {}))
success = createPlot(data_json, layout_json)
if success:
print("Plot displayed!")
return success
except Exception as e:
print(f"Plot error: {e}")
return False
try:
import plotly.graph_objects as go
import plotly.express as px
go.Figure.show = lambda self, *args, **kwargs: show_plot(self)
print("Plotly ready!")
except Exception as e:
print(f"Setup error: {e}")
`);
ready = true;
updateStatus('✅ Ready!', 'green');
document.getElementById('output').style.display = 'block';
document.getElementById('text-output').textContent = 'Ready to test Plotly Express examples!';
} catch (error) {
updateStatus('❌ Error: ' + error.message, 'red');
}
}
async function runCode(code) {
if (!ready) return 'Not ready';
try {
updateStatus('▶️ Running...', 'blue');
document.getElementById('plots').innerHTML = '';
pyodide.runPython(`
import sys
from io import StringIO
old_stdout = sys.stdout
sys.stdout = capture = StringIO()
`);
pyodide.runPython(code);
let output = pyodide.runPython(`
sys.stdout = old_stdout
capture.getvalue()
`);
document.getElementById('text-output').textContent = output || 'Code executed';
updateStatus('✅ Done', 'green');
return output || 'Success';
} catch (error) {
const err = 'Error: ' + error.toString();
document.getElementById('text-output').textContent = err;
updateStatus('❌ Error', 'red');
return err;
}
}
function waitForCDN() {
if (typeof loadPyodide !== 'undefined' && typeof Plotly !== 'undefined') {
init();
} else {
setTimeout(waitForCDN, 1000);
}
}
waitForCDN();
window.runCode = runCode;
</script>
'''
return pyodide_html
# Example templates
examples = {
"Minimal Test": '''# Absolute minimal test
import plotly.express as px
print("Testing minimal Express...")
fig = px.scatter(x=[1, 2], y=[1, 2], title="Minimal")
fig.show()
print("Minimal test complete!")''',
"Direct Arrays": '''# Test without DataFrame
import plotly.express as px
print("Testing direct arrays...")
fig = px.scatter(x=[1, 2, 3, 4], y=[1, 4, 9, 16], title="Direct Arrays")
fig.show()
print("Direct arrays test complete!")''',
"Simple DataFrame": '''# Simple DataFrame test
import plotly.express as px
import pandas as pd
print("Creating DataFrame...")
df = pd.DataFrame({
'x': [1, 2, 3, 4, 5],
'y': [2, 4, 6, 8, 10]
})
print("DataFrame:")
print(df)
print("Creating plot...")
fig = px.scatter(df, x='x', y='y', title='DataFrame Test')
fig.show()
print("DataFrame test complete!")''',
"Line Chart": '''# Line chart test
import plotly.express as px
import pandas as pd
df = pd.DataFrame({
'x': [1, 2, 3, 4, 5],
'y': [1, 4, 2, 8, 5]
})
fig = px.line(df, x='x', y='y', title='Line Chart')
fig.show()
print("Line chart complete!")''',
"Bar Chart": '''# Bar chart test
import plotly.express as px
import pandas as pd
df = pd.DataFrame({
'category': ['A', 'B', 'C', 'D'],
'values': [20, 35, 30, 25]
})
fig = px.bar(df, x='category', y='values', title='Bar Chart')
fig.show()
print("Bar chart complete!")''',
"Data Types": '''# Test different data types
import plotly.express as px
import pandas as pd
import numpy as np
print("Creating mixed data types...")
df = pd.DataFrame({
'int_col': [1, 2, 3, 4],
'float_col': [1.1, 2.2, 3.3, 4.4],
'numpy_col': np.array([1, 2, 3, 4])
})
print("DataFrame info:")
print(df.dtypes)
fig = px.scatter(df, x='int_col', y='float_col', title='Data Types')
fig.show()
print("Data typ