-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathinteractive_canvas.py
More file actions
839 lines (736 loc) · 35.7 KB
/
Copy pathinteractive_canvas.py
File metadata and controls
839 lines (736 loc) · 35.7 KB
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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
import streamlit as st
import streamlit.components.v1 as components
import json
import uuid
from typing import Dict, List, Any, Optional
class InteractiveCanvas:
"""
Interactive canvas for P&ID design with drag-and-drop components and line drawing.
"""
def __init__(self):
self.component_types = {
"equipment": {
"label": "Equipment",
"icon": "🏭",
"color": "#3498db",
"shape": "box",
"size": 25
},
"instrumentation": {
"label": "Instrumentation",
"icon": "📊",
"color": "#f1c40f",
"shape": "ellipse",
"size": 20
},
"valves": {
"label": "Valves",
"icon": "🔧",
"color": "#2ecc71",
"shape": "triangle",
"size": 18
},
"junctions": {
"label": "Junctions",
"icon": "🔀",
"color": "#9b59b6",
"shape": "diamond",
"size": 15
},
"safety_devices": {
"label": "Safety Devices",
"icon": "🛡️",
"color": "#e67e22",
"shape": "star",
"size": 20
},
"lines": {
"label": "Lines",
"icon": "📏",
"color": "#e74c3c",
"shape": "dot",
"size": 8
}
}
def initialize_session_state(self):
"""Initialize session state for canvas data."""
if "canvas_components" not in st.session_state:
st.session_state.canvas_components = {}
if "canvas_connections" not in st.session_state:
st.session_state.canvas_connections = []
if "selected_tool" not in st.session_state:
st.session_state.selected_tool = "select"
if "canvas_mode" not in st.session_state:
st.session_state.canvas_mode = "design"
if "canvas_initialized" not in st.session_state:
st.session_state.canvas_initialized = False
def render_component_palette(self):
"""Render the component palette sidebar."""
st.sidebar.header("🎨 Component Palette")
# Tool selection
st.sidebar.subheader("Tools")
tool_options = {
"select": "🖱️ Select/Move",
"pan": "✋ Pan",
"line": "📏 Draw Line",
"delete": "🗑️ Delete"
}
selected_tool = st.sidebar.radio("Active Tool", list(tool_options.keys()),
format_func=lambda x: tool_options[x])
st.session_state.selected_tool = selected_tool
st.sidebar.write("---")
# Navigation instructions
st.sidebar.info("**Navigation:**\n- Scroll wheel: Zoom\n- Ctrl+drag: Pan\n- Pan tool: Click and drag")
st.sidebar.write("---")
# Component types
st.sidebar.subheader("Components")
for comp_type, props in self.component_types.items():
if comp_type != "lines": # Lines are drawn, not placed
col1, col2 = st.sidebar.columns([1, 3])
with col1:
st.write(props["icon"])
with col2:
if st.button(f"Add {props['label']}", key=f"add_{comp_type}",
help=f"Click to add {props['label']} to canvas"):
self._add_component_to_canvas(comp_type)
st.sidebar.write("---")
# Canvas controls
st.sidebar.subheader("Canvas Controls")
if st.sidebar.button("🗑️ Clear Canvas", help="Remove all user-added components"):
st.session_state.canvas_components = {}
st.session_state.canvas_connections = []
st.rerun()
if st.sidebar.button("💾 Save Design", help="Save current canvas design"):
self._save_canvas_design()
# Auto-save indicator
if st.session_state.get("design_saved", False):
st.sidebar.success("✅ Design saved")
else:
st.sidebar.info("💡 Make changes and save your design")
# Debug info
with st.sidebar.expander("🔍 Debug Info"):
st.write(f"Components: {len(st.session_state.canvas_components)}")
st.write(f"Connections: {len(st.session_state.canvas_connections)}")
st.write(f"Design saved: {st.session_state.get('design_saved', False)}")
if st.session_state.canvas_components:
st.write("**Components:**")
for comp_id, comp in st.session_state.canvas_components.items():
st.write(f"- {comp['label']} at ({comp['x']}, {comp['y']})")
if st.sidebar.button("📂 Load Design", help="Load saved canvas design"):
self._load_canvas_design()
# Component editing
st.sidebar.write("---")
st.sidebar.subheader("Component Editor")
# Show current components for editing
if st.session_state.canvas_components:
st.sidebar.write("**User Components:**")
for comp_id, comp in st.session_state.canvas_components.items():
col1, col2 = st.sidebar.columns([2, 1])
with col1:
st.write(f"• {comp['label']}")
with col2:
if st.button("✏️", key=f"edit_{comp_id}", help=f"Edit {comp['label']}"):
st.session_state[f"editing_{comp_id}"] = True
st.rerun()
# Show edit form for selected component
for comp_id, comp in st.session_state.canvas_components.items():
if st.session_state.get(f"editing_{comp_id}", False):
st.sidebar.write(f"**Editing: {comp['label']}**")
new_label = st.sidebar.text_input(
"Component Name",
value=comp['label'],
key=f"label_{comp_id}"
)
col1, col2 = st.sidebar.columns(2)
with col1:
if st.button("✅ Save", key=f"save_{comp_id}"):
comp['label'] = new_label
st.session_state[f"editing_{comp_id}"] = False
st.rerun()
with col2:
if st.button("❌ Cancel", key=f"cancel_{comp_id}"):
st.session_state[f"editing_{comp_id}"] = False
st.rerun()
else:
st.sidebar.write("No user components added yet.")
def _add_component_to_canvas(self, comp_type: str):
"""Add a new component to the canvas."""
component_id = str(uuid.uuid4())
props = self.component_types[comp_type]
# Default position (center of canvas)
default_x = 400
default_y = 300
# Generate a more descriptive default name
existing_count = len([c for c in st.session_state.canvas_components.values() if c['type'] == comp_type])
default_label = f"{props['label']}-{existing_count + 1:02d}"
component = {
"id": component_id,
"type": comp_type,
"label": default_label,
"x": default_x,
"y": default_y,
"properties": props.copy()
}
st.session_state.canvas_components[component_id] = component
st.rerun()
def _save_canvas_design(self):
"""Save current canvas design to session state."""
design_data = {
"components": st.session_state.canvas_components.copy(),
"connections": st.session_state.canvas_connections.copy(),
"timestamp": str(uuid.uuid4())
}
st.session_state.saved_design = design_data
st.session_state.design_saved = True
st.sidebar.success("Design saved!")
def _load_canvas_design(self):
"""Load saved canvas design."""
if "saved_design" in st.session_state:
st.session_state.canvas_components = st.session_state.saved_design["components"].copy()
st.session_state.canvas_connections = st.session_state.saved_design["connections"].copy()
st.sidebar.success("Design loaded!")
st.rerun()
else:
st.sidebar.error("No saved design found!")
def auto_load_saved_design(self):
"""Automatically load saved design if it exists."""
if "saved_design" in st.session_state and "design_saved" in st.session_state:
if not st.session_state.canvas_components and st.session_state.saved_design["components"]:
st.session_state.canvas_components = st.session_state.saved_design["components"].copy()
st.session_state.canvas_connections = st.session_state.saved_design["connections"].copy()
def render_canvas(self, ai_data: Dict[str, Any]):
"""Render the interactive canvas with AI data and user components."""
# Auto-save canvas state before rendering
self._auto_save_canvas_state()
# Generate HTML for the interactive canvas
html_content = self._generate_canvas_html(ai_data)
# Render the canvas
components.html(html_content, height=800, scrolling=False)
# Handle canvas events
self._handle_canvas_events()
def _auto_save_canvas_state(self):
"""Automatically save canvas state to session state."""
# This will be called before each render to ensure state is preserved
if not st.session_state.canvas_initialized:
st.session_state.canvas_initialized = True
# Mark that we have a saved state
if st.session_state.canvas_components:
st.session_state.design_saved = True
def _generate_canvas_html(self, ai_data: Dict[str, Any]) -> str:
"""Generate HTML content for the interactive canvas."""
# Convert AI data to canvas format
ai_components = self._convert_ai_data_to_components(ai_data)
# Combine AI components with user components
all_components = {**ai_components, **st.session_state.canvas_components}
# Generate the HTML
html = f"""
<!DOCTYPE html>
<html>
<head>
<title>Interactive P&ID Canvas</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/5.3.0/fabric.min.js"></script>
<style>
body {{
margin: 0;
padding: 20px;
font-family: Arial, sans-serif;
background-color: #f8f9fa;
}}
.canvas-container {{
border: 2px solid #ddd;
border-radius: 8px;
background: white;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}}
.toolbar {{
margin-bottom: 10px;
padding: 10px;
background: white;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}}
.tool-btn {{
margin: 5px;
padding: 8px 16px;
border: 1px solid #ddd;
border-radius: 4px;
background: white;
cursor: pointer;
transition: all 0.2s;
}}
.tool-btn:hover {{
background: #f0f0f0;
}}
.tool-btn.active {{
background: #007bff;
color: white;
border-color: #007bff;
}}
.component-info {{
position: absolute;
top: 10px;
right: 10px;
background: white;
padding: 10px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
font-size: 12px;
}}
</style>
</head>
<body>
<div class="toolbar">
<button class="tool-btn active" id="selectTool">🖱️ Select</button>
<button class="tool-btn" id="panTool">✋ Pan</button>
<button class="tool-btn" id="lineTool">📏 Draw Line</button>
<button class="tool-btn" id="deleteTool">🗑️ Delete</button>
<span style="margin-left: 20px;">
<button class="tool-btn" id="zoomIn">🔍+</button>
<button class="tool-btn" id="zoomOut">🔍-</button>
<button class="tool-btn" id="resetView">🏠 Reset</button>
</span>
</div>
<div class="component-info" id="componentInfo">
<strong>Canvas Info</strong><br>
Components: <span id="componentCount">0</span><br>
Connections: <span id="connectionCount">0</span>
</div>
<div class="canvas-container">
<canvas id="pidCanvas" width="1200" height="700"></canvas>
</div>
<script>
// Initialize Fabric.js canvas
const canvas = new fabric.Canvas('pidCanvas', {{
width: 1200,
height: 700,
backgroundColor: '#ffffff'
}});
// Component data from Python
const aiComponents = {json.dumps(ai_components)};
const userComponents = {json.dumps(st.session_state.canvas_components)};
const connections = {json.dumps(st.session_state.canvas_connections)};
// Component type properties
const componentTypes = {json.dumps(self.component_types)};
// Current tool
let currentTool = 'select';
let isDrawingLine = false;
let lineStart = null;
// Add AI components to canvas
function addAIComponents() {{
Object.values(aiComponents).forEach(comp => {{
const props = componentTypes[comp.type] || componentTypes.equipment;
const rect = new fabric.Rect({{
left: comp.x,
top: comp.y,
width: 60,
height: 40,
fill: props.color,
stroke: '#000',
strokeWidth: 2,
rx: 5,
ry: 5
}});
const text = new fabric.Text(comp.label, {{
left: comp.x + 5,
top: comp.y + 15,
fontSize: 10,
fill: 'white',
fontWeight: 'bold'
}});
const group = new fabric.Group([rect, text], {{
left: comp.x,
top: comp.y,
id: comp.id,
type: 'ai-component',
componentType: comp.type,
label: comp.label
}});
canvas.add(group);
}});
}}
// Add user components to canvas
function addUserComponents() {{
Object.values(userComponents).forEach(comp => {{
const props = componentTypes[comp.type] || componentTypes.equipment;
let shape;
switch(comp.type) {{
case 'equipment':
shape = new fabric.Rect({{
width: 60,
height: 40,
fill: props.color,
stroke: '#000',
strokeWidth: 2,
rx: 5,
ry: 5
}});
break;
case 'instrumentation':
shape = new fabric.Circle({{
radius: 25,
fill: props.color,
stroke: '#000',
strokeWidth: 2
}});
break;
case 'valves':
shape = new fabric.Triangle({{
width: 50,
height: 50,
fill: props.color,
stroke: '#000',
strokeWidth: 2
}});
break;
case 'junctions':
shape = new fabric.Polygon([
{{x: 0, y: -25}},
{{x: 25, y: 0}},
{{x: 0, y: 25}},
{{x: -25, y: 0}}
], {{
fill: props.color,
stroke: '#000',
strokeWidth: 2
}});
break;
case 'safety_devices':
shape = new fabric.Circle({{
radius: 20,
fill: props.color,
stroke: '#000',
strokeWidth: 2
}});
break;
default:
shape = new fabric.Rect({{
width: 50,
height: 30,
fill: props.color,
stroke: '#000',
strokeWidth: 2
}});
}}
const text = new fabric.Text(comp.label, {{
fontSize: 10,
fill: 'white',
fontWeight: 'bold',
textAlign: 'center'
}});
const group = new fabric.Group([shape, text], {{
left: comp.x,
top: comp.y,
id: comp.id,
type: 'user-component',
componentType: comp.type,
label: comp.label,
editable: true
}});
canvas.add(group);
}});
}}
// Add connections
function addConnections() {{
connections.forEach(conn => {{
const line = new fabric.Line([conn.x1, conn.y1, conn.x2, conn.y2], {{
stroke: '#666',
strokeWidth: 2,
selectable: true,
id: conn.id,
type: 'connection'
}});
canvas.add(line);
}});
}}
// Tool event handlers
document.getElementById('selectTool').addEventListener('click', () => {{
currentTool = 'select';
canvas.isDrawingMode = false;
canvas.selection = true;
updateToolButtons();
}});
document.getElementById('panTool').addEventListener('click', () => {{
currentTool = 'pan';
canvas.isDrawingMode = false;
canvas.selection = false;
updateToolButtons();
}});
document.getElementById('lineTool').addEventListener('click', () => {{
currentTool = 'line';
canvas.isDrawingMode = false;
canvas.selection = false;
updateToolButtons();
}});
document.getElementById('deleteTool').addEventListener('click', () => {{
currentTool = 'delete';
canvas.isDrawingMode = false;
canvas.selection = false;
updateToolButtons();
}});
// Zoom controls
document.getElementById('zoomIn').addEventListener('click', () => {{
canvas.setZoom(canvas.getZoom() * 1.1);
}});
document.getElementById('zoomOut').addEventListener('click', () => {{
canvas.setZoom(canvas.getZoom() * 0.9);
}});
document.getElementById('resetView').addEventListener('click', () => {{
canvas.setZoom(1);
canvas.viewportTransform = [1, 0, 0, 1, 0, 0];
}});
// Mouse wheel zoom
canvas.on('mouse:wheel', (opt) => {{
const delta = opt.e.deltaY;
let zoom = canvas.getZoom();
zoom *= 0.999 ** delta;
if (zoom > 20) zoom = 20;
if (zoom < 0.01) zoom = 0.01;
canvas.zoomToPoint({{ x: opt.e.offsetX, y: opt.e.offsetY }}, zoom);
opt.e.preventDefault();
opt.e.stopPropagation();
}});
// Pan with middle mouse button or Ctrl+drag
canvas.on('mouse:move', (e) => {{
if (canvas.isDragging) {{
const vpt = canvas.viewportTransform;
vpt[4] += e.e.clientX - canvas.lastPosX;
vpt[5] += e.e.clientY - canvas.lastPosY;
canvas.requestRenderAll();
canvas.lastPosX = e.e.clientX;
canvas.lastPosY = e.e.clientY;
e.e.preventDefault();
}}
}});
function updateToolButtons() {{
document.querySelectorAll('.tool-btn').forEach(btn => btn.classList.remove('active'));
document.getElementById(currentTool + 'Tool').classList.add('active');
}}
// Canvas event handlers
canvas.on('mouse:down', (e) => {{
// Handle panning - check for pan tool, Ctrl+drag, or middle mouse
if (currentTool === 'pan' || e.e.ctrlKey || e.e.button === 1) {{
canvas.isDragging = true;
canvas.selection = false;
canvas.lastPosX = e.e.clientX;
canvas.lastPosY = e.e.clientY;
e.e.preventDefault();
return;
}}
// Only handle tool-specific actions if not panning
if (!canvas.isDragging) {{
if (currentTool === 'line') {{
// Check if clicking on an existing line to edit it
const activeObject = canvas.getActiveObject();
if (activeObject && activeObject.type === 'connection') {{
// Remove the existing line
canvas.remove(activeObject);
canvas.renderAll();
}}
isDrawingLine = true;
const pointer = canvas.getPointer(e.e);
lineStart = {{x: pointer.x, y: pointer.y}};
}} else if (currentTool === 'delete') {{
const activeObject = canvas.getActiveObject();
if (activeObject) {{
canvas.remove(activeObject);
canvas.renderAll();
}}
}}
}}
}});
canvas.on('mouse:up', (e) => {{
// Handle panning end
if (canvas.isDragging) {{
canvas.setViewportTransform(canvas.viewportTransform);
canvas.isDragging = false;
canvas.selection = true;
return;
}}
if (currentTool === 'line' && isDrawingLine && lineStart) {{
const pointer = canvas.getPointer(e.e);
// Only create line if it's long enough (avoid accidental clicks)
const distance = Math.sqrt(
Math.pow(pointer.x - lineStart.x, 2) +
Math.pow(pointer.y - lineStart.y, 2)
);
if (distance > 10) {{ // Minimum line length
const line = new fabric.Line([lineStart.x, lineStart.y, pointer.x, pointer.y], {{
stroke: '#333',
strokeWidth: 4,
selectable: true,
type: 'connection',
id: 'line_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
}});
// Add arrow head
const angle = Math.atan2(pointer.y - lineStart.y, pointer.x - lineStart.x);
const arrowLength = 15;
const arrowAngle = Math.PI / 6; // 30 degrees
const arrowX1 = pointer.x - arrowLength * Math.cos(angle - arrowAngle);
const arrowY1 = pointer.y - arrowLength * Math.sin(angle - arrowAngle);
const arrowX2 = pointer.x - arrowLength * Math.cos(angle + arrowAngle);
const arrowY2 = pointer.y - arrowLength * Math.sin(angle + arrowAngle);
const arrow1 = new fabric.Line([pointer.x, pointer.y, arrowX1, arrowY1], {{
stroke: '#333',
strokeWidth: 3,
selectable: false
}});
const arrow2 = new fabric.Line([pointer.x, pointer.y, arrowX2, arrowY2], {{
stroke: '#333',
strokeWidth: 3,
selectable: false
}});
canvas.add(line);
canvas.add(arrow1);
canvas.add(arrow2);
}}
isDrawingLine = false;
lineStart = null;
}}
}});
// Update component info
function updateComponentInfo() {{
const components = canvas.getObjects().filter(obj => obj.type === 'ai-component' || obj.type === 'user-component');
const connections = canvas.getObjects().filter(obj => obj.type === 'connection');
document.getElementById('componentCount').textContent = components.length;
document.getElementById('connectionCount').textContent = connections.length;
}}
// Initialize canvas
addAIComponents();
addUserComponents();
addConnections();
updateComponentInfo();
// Update info on changes and auto-save
canvas.on('object:added', () => {{
updateComponentInfo();
saveCanvasState();
}});
canvas.on('object:removed', () => {{
updateComponentInfo();
saveCanvasState();
}});
canvas.on('object:modified', () => {{
updateComponentInfo();
saveCanvasState();
}});
// Function to save canvas state
function saveCanvasState() {{
const userComponents = {{}};
const userConnections = [];
// Extract user components
canvas.getObjects().forEach(obj => {{
if (obj.type === 'user-component') {{
userComponents[obj.id] = {{
id: obj.id,
type: obj.componentType,
label: obj.label,
x: obj.left,
y: obj.top
}};
}} else if (obj.type === 'connection') {{
userConnections.push({{
id: obj.id,
x1: obj.x1,
y1: obj.y1,
x2: obj.x2,
y2: obj.y2
}});
}}
}});
// Store in a global variable that can be accessed by Python
window.canvasState = {{
components: userComponents,
connections: userConnections,
timestamp: Date.now()
}};
}}
// Double-click to edit component labels
canvas.on('mouse:dblclick', (e) => {{
const activeObject = canvas.getActiveObject();
if (activeObject && (activeObject.type === 'user-component' || activeObject.type === 'ai-component')) {{
const newLabel = prompt('Enter new component name:', activeObject.label || '');
if (newLabel && newLabel.trim() !== '') {{
activeObject.label = newLabel.trim();
// Update the text in the group
if (activeObject.getObjects) {{
const textObj = activeObject.getObjects().find(obj => obj.type === 'text');
if (textObj) {{
textObj.set('text', newLabel.trim());
}}
}}
canvas.renderAll();
updateComponentInfo();
}}
}}
}});
// Auto-save every 2 seconds
setInterval(() => {{
saveCanvasState();
}}, 2000);
// Initial save
saveCanvasState();
// Render canvas
canvas.renderAll();
</script>
</body>
</html>
"""
return html
def _convert_ai_data_to_components(self, ai_data: Dict[str, Any]) -> Dict[str, Any]:
"""Convert AI-detected data to canvas component format."""
components = {}
# Map AI data categories to component types
category_mapping = {
"equipment": "equipment",
"instrumentation": "instrumentation",
"valves": "valves",
"junctions": "junctions",
"safety_devices": "safety_devices"
}
for category_key, category_name in category_mapping.items():
if category_key in ai_data and ai_data[category_key]:
for item in ai_data[category_key]:
tag = item.get('tag') or item.get('label') or item.get('junction_id')
if not tag:
continue
# Get bounding box coordinates
bbox = item.get('bounding_box')
if bbox and len(bbox) == 4:
x1, y1, x2, y2 = bbox
center_x = (x1 + x2) / 2
center_y = (y1 + y2) / 2
# Scale coordinates to fit canvas (0-1000 -> 0-1200)
pos_x = (center_x / 1000) * 1200
pos_y = (center_y / 1000) * 700
else:
# Fallback positioning
pos_x = 100 + len(components) * 100
pos_y = 100 + (len(components) % 5) * 100
component_id = f"ai_{tag}_{len(components)}"
display_label = item.get('description') or item.get('type') or tag
components[component_id] = {
"id": component_id,
"type": category_name,
"label": display_label,
"x": pos_x,
"y": pos_y,
"properties": self.component_types[category_name].copy(),
"ai_data": item
}
return components
def _handle_canvas_events(self):
"""Handle events from the canvas."""
# This would handle events sent from the JavaScript canvas
# For now, we'll implement basic state management
pass
def get_canvas_data(self) -> Dict[str, Any]:
"""Get current canvas data for export."""
return {
"user_components": st.session_state.canvas_components,
"user_connections": st.session_state.canvas_connections,
"canvas_mode": st.session_state.canvas_mode
}
def clear_canvas(self):
"""Clear all user-added components from canvas."""
st.session_state.canvas_components = {}
st.session_state.canvas_connections = []
st.rerun()