Spaces:
Running
Running
File size: 19,234 Bytes
fe68dba 700f68a 1e9411d fe68dba 310bef9 3f10e1f 310bef9 700f68a 310bef9 1e9411d 310bef9 3f10e1f 700f68a 310bef9 3f10e1f 1e9411d 310bef9 1e9411d 101f725 1e9411d 101f725 1e9411d 43f50cc 1e9411d 43f50cc 1e9411d 43f50cc 1e9411d fe68dba 700f68a fe68dba 1e9411d fe68dba 1e9411d fe68dba 3f10e1f 310bef9 fe68dba 310bef9 fe68dba 1e9411d 310bef9 1e9411d 310bef9 1e9411d 3f10e1f 1e9411d 310bef9 1e9411d 310bef9 1e9411d 059fde9 1e9411d 43f50cc 1e9411d 1635f86 1e9411d 3f10e1f 1e9411d 101f725 1e9411d 43f50cc 1e9411d 43f50cc 1e9411d 101f725 1e9411d 43f50cc 1e9411d 43f50cc 1e9411d 101f725 1e9411d 101f725 1e9411d 43f50cc 1e9411d 43f50cc 1e9411d 43f50cc 310bef9 3f10e1f 1e9411d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 |
"""
app.py โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Preview ยท Save ยท Load ๊ธฐ๋ฅ ํฌํจ
โ Load ์ ๋
ธ๋/์ขํ/์ฃ์ง ์๋ ๋ณต์
โ gr.update()๋ฅผ ์ฌ์ฉํ ๊ฐ์ ์
๋ฐ์ดํธ
"""
import os, json, typing, tempfile
import gradio as gr
from gradio_workflowbuilder import WorkflowBuilder
# -------------------------------------------------------------------
# ๐ ๏ธ ํฌํผ
# -------------------------------------------------------------------
def export_pretty(data: typing.Dict[str, typing.Any]) -> str:
print(f"[Export] Current workflow data: {json.dumps(data, indent=2)}")
return json.dumps(data, indent=2, ensure_ascii=False) if data else "No workflow to export"
def export_file(data: typing.Dict[str, typing.Any]) -> typing.Optional[str]:
if not data:
return None
fd, path = tempfile.mkstemp(suffix=".json")
with os.fdopen(fd, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
return path
def import_workflow(file_obj):
"""ํ์ผ์์ JSON์ ์ฝ๊ณ WorkflowBuilder๋ฅผ ์
๋ฐ์ดํธ"""
if file_obj is None:
return None, "No file selected", "Status: No file", gr.update(visible=False)
try:
with open(file_obj.name, "r", encoding="utf-8") as f:
data = json.load(f)
print(f"[Import] Loaded data: {json.dumps(data, indent=2)}")
# ๋ฐ์ดํฐ ๊ฒ์ฆ
if not isinstance(data, dict):
return None, "Invalid format: not a dictionary", "Status: Invalid format", gr.update(visible=False)
# ํ์ ํ๋ ํ์ธ
if 'nodes' not in data:
data['nodes'] = []
if 'edges' not in data:
data['edges'] = []
nodes_count = len(data.get('nodes', []))
edges_count = len(data.get('edges', []))
# ์ง์ ๋ฐ์ดํฐ ๋ฐํ
return (
data, # ์ง์ ๋ฐ์ดํฐ ๋ฐํ
json.dumps(data, indent=2, ensure_ascii=False),
f"โ
Loaded: {nodes_count} nodes, {edges_count} edges",
gr.update(visible=True) # JavaScript ์คํ ๋ฒํผ ํ์
)
except Exception as e:
print(f"[Import] Error: {str(e)}")
return None, f"Error: {str(e)}", f"โ Error: {str(e)}", gr.update(visible=False)
def reset_workflow():
"""์ํฌํ๋ก์ฐ ์ด๊ธฐํ"""
empty_workflow = {"nodes": [], "edges": []}
return empty_workflow, "Reset complete"
def set_sample_workflow():
"""์ํ ์ํฌํ๋ก์ฐ ์ค์ """
sample = {
"nodes": [
{
"id": "1",
"type": "default",
"position": {"x": 100, "y": 100},
"data": {"label": "Start Node"}
},
{
"id": "2",
"type": "default",
"position": {"x": 300, "y": 100},
"data": {"label": "Process"}
},
{
"id": "3",
"type": "default",
"position": {"x": 500, "y": 100},
"data": {"label": "End Node"}
}
],
"edges": [
{
"id": "e1-2",
"source": "1",
"target": "2"
},
{
"id": "e2-3",
"source": "2",
"target": "3"
}
]
}
print(f"[Sample] Setting workflow: {json.dumps(sample, indent=2)}")
return sample, json.dumps(sample, indent=2, ensure_ascii=False), "โ
Sample loaded"
def debug_current_state(data):
"""ํ์ฌ ์ํ ๋๋ฒ๊น
"""
if not data:
return "Empty workflow", "{}"
nodes = data.get('nodes', [])
edges = data.get('edges', [])
debug_info = f"Nodes: {len(nodes)}, Edges: {len(edges)}"
if nodes:
debug_info += f"\nFirst node: {nodes[0].get('id', 'unknown')}"
return debug_info, json.dumps(data, indent=2)
# -------------------------------------------------------------------
# ๐จ CSS
# -------------------------------------------------------------------
CSS = """
.main-container{max-width:1600px;margin:0 auto;}
.workflow-section{margin-bottom:2rem;min-height:500px;}
.button-row{display:flex;gap:1rem;justify-content:center;margin:1rem 0;}
.status-box{
padding:10px;border-radius:5px;margin-top:10px;
background:#f0f9ff;border:1px solid #3b82f6;color:#1e40af;
}
.component-description{
padding:24px;background:linear-gradient(135deg,#f8fafc 0%,#e2e8f0 100%);
border-left:4px solid #3b82f6;border-radius:12px;
box-shadow:0 2px 8px rgba(0,0,0,.05);margin:16px 0;
}
"""
# -------------------------------------------------------------------
# ๐ฅ๏ธ Gradio ์ฑ
# -------------------------------------------------------------------
with gr.Blocks(title="๐จ Visual Workflow Builder", theme=gr.themes.Soft(), css=CSS) as demo:
gr.Markdown("# ๐จ Visual Workflow Builder\n**Debug Version - Testing JSON Load**")
# ์ํ ํ์
status_text = gr.Textbox(
label="Status",
value="Ready",
elem_classes=["status-box"],
interactive=False
)
# โโโ Workflow Builder โโโ
with gr.Column(elem_classes=["workflow-section"]):
workflow_builder = WorkflowBuilder(
label="๐จ Visual Workflow Designer",
value={"nodes": [], "edges": []},
elem_id="workflow_builder"
)
# โโโ Control Panel โโโ
gr.Markdown("## ๐ฎ Control Panel")
# JavaScript force update button (hidden by default)
btn_force_update = gr.Button("โก Force Update (JavaScript)", variant="warning", visible=False)
loaded_data_store = gr.State(None)
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("### ๐ฅ Import")
file_upload = gr.File(
label="Select JSON file",
file_types=[".json"],
type="filepath"
)
btn_load = gr.Button("๐ Load File", variant="primary", size="lg")
with gr.Column(scale=1):
gr.Markdown("### ๐งช Test")
btn_sample = gr.Button("๐ Load Sample", variant="primary", size="lg")
btn_reset = gr.Button("๐ Reset", variant="stop", size="lg")
with gr.Column(scale=1):
gr.Markdown("### ๐พ Export")
btn_preview = gr.Button("๐๏ธ Preview JSON", size="lg")
btn_download = gr.DownloadButton("๐พ Download JSON", size="lg")
# โโโ Alternative Render Method โโโ
with gr.Accordion("๐ฌ Alternative Load Method", open=False):
gr.Markdown("If normal loading fails, try this dynamic rendering approach:")
btn_render = gr.Button("๐ฏ Render with Data", variant="primary")
render_container = gr.Column()
@gr.render(inputs=[loaded_data_store], triggers=[btn_render.click])
def render_workflow_dynamic(data):
if data:
with gr.Column():
gr.Markdown("### Dynamically Rendered Workflow")
return WorkflowBuilder(
label="Dynamic Workflow",
value=data
)
else:
return gr.Markdown("No data loaded yet")
# โโโ Debug Section โโโ
with gr.Accordion("๐ Debug Info", open=True):
with gr.Row():
debug_text = gr.Textbox(label="State Info", lines=2)
debug_json = gr.Code(language="json", label="Current JSON", lines=10)
btn_debug = gr.Button("๐ Update Debug Info", variant="secondary")
# โโโ Code View โโโ
code_view = gr.Code(language="json", label="JSON Preview", lines=15)
# HTML Fallback Viewer ํจ์ ์ ์
def create_html_view(data):
"""JSON์ HTML๋ก ์๊ฐํ"""
if not data:
return "<p>No workflow data</p>"
html = """
<div style='font-family: Arial, sans-serif; padding: 20px; background: #f5f5f5; border-radius: 8px;'>
<h3>Workflow Visualization</h3>
<div style='display: flex; gap: 20px; flex-wrap: wrap;'>
"""
# ๋
ธ๋ ํ์
nodes = data.get('nodes', [])
for node in nodes:
node_id = node.get('id', 'unknown')
label = node.get('data', {}).get('label', 'Node')
x = node.get('position', {}).get('x', 0)
y = node.get('position', {}).get('y', 0)
html += f"""
<div style='background: white; border: 2px solid #3b82f6; border-radius: 8px;
padding: 15px; margin: 10px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);
min-width: 150px;'>
<strong>ID:</strong> {node_id}<br>
<strong>Label:</strong> {label}<br>
<strong>Position:</strong> ({x}, {y})
</div>
"""
html += "</div>"
# ์ฃ์ง ํ์
edges = data.get('edges', [])
if edges:
html += "<h4>Connections:</h4><ul>"
for edge in edges:
source = edge.get('source', '?')
target = edge.get('target', '?')
html += f"<li>{source} โ {target}</li>"
html += "</ul>"
html += "</div>"
return html
# HTML Fallback Viewer
gr.Markdown("### ๐ HTML Workflow Viewer (Fallback)")
html_viewer = gr.HTML(label="Workflow HTML View")
# โโโ Event Handlers โโโ
# Load file - ๋ฐ์ดํฐ๋ฅผ State์ ์ ์ฅ
file_upload.change(
fn=import_workflow,
inputs=file_upload,
outputs=[loaded_data_store, code_view, status_text, btn_force_update]
)
# Load button - State์์ WorkflowBuilder๋ก ์ ์ก
btn_load.click(
fn=lambda data: data if data else {"nodes": [], "edges": []},
inputs=loaded_data_store,
outputs=workflow_builder
)
# Force update with JavaScript
btn_force_update.click(
fn=None,
inputs=loaded_data_store,
outputs=None,
js="""
(data) => {
console.log('[Force Update] Attempting to update WorkflowBuilder with:', data);
// WorkflowBuilder ์๋ฆฌ๋จผํธ ์ฐพ๊ธฐ
const workflowElement = document.querySelector('#workflow_builder');
if (workflowElement) {
// ์ฌ๋ฌ ๋ฐฉ๋ฒ ์๋
// ๋ฐฉ๋ฒ 1: ์ง์ value ์ค์
if (workflowElement.__vue__) {
workflowElement.__vue__.value = data;
workflowElement.__vue__.$forceUpdate();
}
// ๋ฐฉ๋ฒ 2: ์ด๋ฒคํธ ๋ฐ์
const event = new CustomEvent('input', {
detail: data,
bubbles: true
});
workflowElement.dispatchEvent(event);
// ๋ฐฉ๋ฒ 3: Gradio ์ด๋ฒคํธ
if (window.gradio_config && window.gradio_config.components) {
const component = Object.values(window.gradio_config.components).find(
c => c.props && c.props.elem_id === 'workflow_builder'
);
if (component) {
component.props.value = data;
}
}
}
return data;
}
"""
)
# Sample workflow
btn_sample.click(
fn=set_sample_workflow,
outputs=[workflow_builder, code_view, status_text]
)
# Reset
btn_reset.click(
fn=reset_workflow,
outputs=[workflow_builder, status_text]
)
# Preview
btn_preview.click(
fn=export_pretty,
inputs=workflow_builder,
outputs=code_view
)
# Download
btn_download.click(
fn=export_file,
inputs=workflow_builder
)
# Debug
btn_debug.click(
fn=debug_current_state,
inputs=workflow_builder,
outputs=[debug_text, debug_json]
)
# Auto-debug on change
workflow_builder.change(
fn=lambda x: f"Changed - Nodes: {len(x.get('nodes', []))}, Edges: {len(x.get('edges', []))}",
inputs=workflow_builder,
outputs=status_text
)
# HTML viewer ์
๋ฐ์ดํธ
workflow_builder.change(
fn=create_html_view,
inputs=workflow_builder,
outputs=html_viewer
)
# Also update HTML view when loading
loaded_data_store.change(
fn=create_html_view,
inputs=loaded_data_store,
outputs=html_viewer
)
# โโโ Instructions โโโ
with gr.Accordion("๐ Troubleshooting", open=True):
gr.Markdown(
"""
### ๐ง If JSON doesn't load visually:
1. **Try the Sample first** - Click "Load Sample" to test if the component works
2. **Check Console** - Open browser DevTools (F12) for errors
3. **File Format** - Ensure your JSON has this structure:
```json
{
"nodes": [{
"id": "1",
"type": "default",
"position": {"x": 100, "y": 100},
"data": {"label": "Node"}
}],
"edges": [{
"id": "e1",
"source": "1",
"target": "2"
}]
}
```
4. **Alternative Methods**:
- Click file โ Click "Load File" button
- Try "Reset" then load again
- Refresh page (F5) after loading
- Use the "Force Update" button if it appears
5. **Component Limitations**:
- Some custom Gradio components may have bugs with dynamic updates
- The WorkflowBuilder might require specific node types or data formats
### ๐จ Known Issues with gradio_workflowbuilder:
This appears to be a bug in the gradio_workflowbuilder component where it doesn't properly respond to value updates. Possible workarounds:
1. **Manual Recreation**: Copy the JSON and manually recreate nodes
2. **Component Update**: Check if there's a newer version: `pip install --upgrade gradio_workflowbuilder`
3. **Alternative Components**: Consider using other workflow builders or diagram libraries
4. **Report Bug**: Report this issue to the component maintainer
### ๐ก Alternative Solution:
If loading continues to fail, you might need to:
```python
# Option 1: Recreate the component on each load
@gr.render(inputs=[loaded_data_store])
def render_workflow(data):
return WorkflowBuilder(value=data)
# Option 2: Use a different workflow library
# Consider react-flow, vis.js, or cytoscape.js wrapped in Gradio HTML
```
### ๐จ HTML Fallback Viewer:
If the WorkflowBuilder component is broken, use the HTML viewer below to at least see your workflow structure:
"""
)
# HTML Fallback Viewer
gr.Markdown("### ๐ HTML Workflow Viewer (Fallback)")
html_viewer = gr.HTML(label="Workflow HTML View")
def create_html_view(data):
"""JSON์ HTML๋ก ์๊ฐํ"""
if not data:
return "<p>No workflow data</p>"
html = """
<div style='font-family: Arial, sans-serif; padding: 20px; background: #f5f5f5; border-radius: 8px;'>
<h3>Workflow Visualization</h3>
<div style='display: flex; gap: 20px; flex-wrap: wrap;'>
"""
# ๋
ธ๋ ํ์
nodes = data.get('nodes', [])
for node in nodes:
node_id = node.get('id', 'unknown')
label = node.get('data', {}).get('label', 'Node')
x = node.get('position', {}).get('x', 0)
y = node.get('position', {}).get('y', 0)
html += f"""
<div style='background: white; border: 2px solid #3b82f6; border-radius: 8px;
padding: 15px; margin: 10px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);
min-width: 150px;'>
<strong>ID:</strong> {node_id}<br>
<strong>Label:</strong> {label}<br>
<strong>Position:</strong> ({x}, {y})
</div>
"""
html += "</div>"
# ์ฃ์ง ํ์
edges = data.get('edges', [])
if edges:
html += "<h4>Connections:</h4><ul>"
for edge in edges:
source = edge.get('source', '?')
target = edge.get('target', '?')
html += f"<li>{source} โ {target}</li>"
html += "</ul>"
html += "</div>"
return html
# HTML Fallback Viewer
gr.Markdown("### ๐ HTML Workflow Viewer (Fallback)")
html_viewer = gr.HTML(label="Workflow HTML View")
def create_html_view(data):
"""JSON์ HTML๋ก ์๊ฐํ"""
if not data:
return "<p>No workflow data</p>"
html = """
<div style='font-family: Arial, sans-serif; padding: 20px; background: #f5f5f5; border-radius: 8px;'>
<h3>Workflow Visualization</h3>
<div style='display: flex; gap: 20px; flex-wrap: wrap;'>
"""
# ๋
ธ๋ ํ์
nodes = data.get('nodes', [])
for node in nodes:
node_id = node.get('id', 'unknown')
label = node.get('data', {}).get('label', 'Node')
x = node.get('position', {}).get('x', 0)
y = node.get('position', {}).get('y', 0)
html += f"""
<div style='background: white; border: 2px solid #3b82f6; border-radius: 8px;
padding: 15px; margin: 10px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);
min-width: 150px;'>
<strong>ID:</strong> {node_id}<br>
<strong>Label:</strong> {label}<br>
<strong>Position:</strong> ({x}, {y})
</div>
"""
html += "</div>"
# ์ฃ์ง ํ์
edges = data.get('edges', [])
if edges:
html += "<h4>Connections:</h4><ul>"
for edge in edges:
source = edge.get('source', '?')
target = edge.get('target', '?')
html += f"<li>{source} โ {target}</li>"
html += "</ul>"
html += "</div>"
return html
# HTML viewer ์
๋ฐ์ดํธ
workflow_builder.change(
fn=create_html_view,
inputs=workflow_builder,
outputs=html_viewer
)
# -------------------------------------------------------------------
# ๐ ์คํ
# -------------------------------------------------------------------
if __name__ == "__main__":
demo.launch(
server_name="0.0.0.0",
show_error=True,
debug=True # ๋๋ฒ๊ทธ ๋ชจ๋ ํ์ฑํ
) |