openfree commited on
Commit
28db47c
·
verified ·
1 Parent(s): 07f65c1

Delete app-backup.py

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