-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathprocessor.py
More file actions
461 lines (413 loc) · 18.1 KB
/
processor.py
File metadata and controls
461 lines (413 loc) · 18.1 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
"""
GUI Processor - Core GUI processing logic for GNN Pipeline.
This module contains the main processing functions for the GUI module,
extracted from __init__.py to follow the thin orchestrator pattern.
"""
import json
import logging
import os
import tempfile
from pathlib import Path
from typing import Any, Dict, List
def process_gui(
target_dir: Path, output_dir: Path, verbose: bool = False, **kwargs: Any
) -> bool:
"""
Main processing function for GUI module.
By default, runs all available GUI implementations in headless mode.
Can be restricted using gui_types parameter.
Args:
target_dir: Directory containing files to process
output_dir: Output directory for results
verbose: Whether to enable verbose logging
**kwargs: Additional processing options
- gui_types: List of GUI types to run (default: gui_1, gui_2)
- headless: Run in headless mode (default: True for pipeline)
- interactive: Launch interactive GUI servers (overrides headless)
- open_browser: Whether to open browser for interactive GUIs
Returns:
Boolean indicating success of all GUI runs
"""
from .gui_1 import gui_1
from .gui_2 import gui_2
from .gui_3 import gui_3
from .oxdraw import oxdraw_gui
logger = logging.getLogger(__name__)
if verbose:
logger.setLevel(logging.DEBUG)
# Handle interactive vs headless mode
interactive = kwargs.get("interactive", False)
if interactive:
kwargs["headless"] = False
logger.info("🎮 Running in INTERACTIVE mode - will launch GUI servers")
else:
kwargs["headless"] = kwargs.get("headless", True)
if kwargs["headless"]:
logger.info(
"📦 Running in HEADLESS mode - generating artifacts only (fast)"
)
# Determine which GUIs to run
gui_types = kwargs.get("gui_types", "gui_1,gui_2")
if isinstance(gui_types, str):
gui_types = [g.strip() for g in gui_types.split(",")]
# Prepare kwargs for GUI functions
gui_kwargs = {
k: v
for k, v in kwargs.items()
if k not in ["logger", "target_dir", "output_dir", "verbose"]
}
results: dict[Any, Any] = {}
overall_success = True
try:
logger.info(f"Processing GUI module for files in {target_dir}")
logger.info(f"Running GUI types: {gui_types}")
logger.info(f"Mode: {'INTERACTIVE' if not kwargs['headless'] else 'HEADLESS'}")
# Map GUI types to functions
gui_functions: dict[str, Any] = {
"gui_1": gui_1,
"gui_2": gui_2,
"gui_3": gui_3,
"oxdraw": oxdraw_gui,
}
# Run each requested GUI
for index, gui_type in enumerate(gui_types, 1):
try:
logger.debug(
f"[{index}/{len(gui_types)}] Initializing pipeline for GUI component: {gui_type}..."
)
if gui_type in gui_functions:
logger.info(f"🎨 Generating visual assets via {gui_type} engine...")
result = gui_functions[gui_type](
target_dir=Path(target_dir),
output_dir=Path(output_dir),
logger=logger,
verbose=verbose,
**gui_kwargs,
)
if result.get("success", False):
logger.info(
f"✅ Successfully compiled {gui_type} visual DOM artifacts."
)
else:
logger.warning(
f"⚠️ Warning: {gui_type} returned non-success parsing state."
)
else:
logger.warning(
f"Unknown GUI type configuration: '{gui_type}'. Skipping."
)
result = {
"gui_type": gui_type,
"success": False,
"error": f"Unknown GUI type: {gui_type}",
}
results[gui_type] = result
if not result.get("success", False):
overall_success = False
except Exception as e:
logger.error(
f"🚨 GUI render exception in {gui_type}: {e}", exc_info=verbose
)
results[gui_type] = {
"gui_type": gui_type,
"success": False,
"error": str(e),
}
overall_success = False
# Save processing summary
_save_processing_summary(
output_dir, kwargs, gui_types, results, overall_success, logger
)
# Generate HTML navigation page for all outputs
_generate_navigation_page(output_dir, logger)
return overall_success
except Exception as e:
logger.error(f"GUI processing failed: {e}")
return False
def _save_processing_summary(
output_dir: Path,
kwargs: Dict[str, Any],
gui_types: List[str],
results: Dict[str, Any],
overall_success: bool,
logger: logging.Logger,
) -> None:
"""Save GUI processing summary to JSON file."""
try:
output_path = Path(output_dir)
summary_file = output_path / "gui_processing_summary.json"
with tempfile.NamedTemporaryFile(
mode="w", encoding="utf-8", dir=output_path, delete=False
) as tmp_f:
tmp_f.write(
json.dumps(
{
"mode": "interactive"
if not kwargs.get("headless", True)
else "headless",
"gui_types": gui_types,
"results": results,
"overall_success": overall_success,
},
indent=2,
)
)
os.replace(tmp_f.name, str(summary_file))
logger.info(f"📊 GUI processing summary saved to: {summary_file}")
except Exception as e:
logger.warning(f"Failed to save GUI processing summary: {e}")
def _generate_navigation_page(output_dir: Path, logger: logging.Logger) -> None:
"""Generate HTML navigation page for pipeline outputs."""
try:
pipeline_output_dir = Path(output_dir).parent
nav_success = generate_html_navigation(pipeline_output_dir, output_dir, logger)
if nav_success:
logger.info("✅ HTML navigation page generated")
except Exception as e:
logger.warning(f"Failed to generate HTML navigation: {e}")
def generate_html_navigation(
pipeline_output_dir: Path, output_dir: Path, logger: logging.Logger
) -> bool:
"""
Generate HTML navigation page that links to all pipeline output types.
Args:
pipeline_output_dir: Directory containing all pipeline outputs (typically output/)
output_dir: GUI output directory where navigation.html will be created
logger: Logger instance
Returns:
True if navigation page generated successfully, False otherwise
"""
try:
logger.info("Generating HTML navigation page for pipeline outputs")
# Ensure output directory exists
output_dir.mkdir(parents=True, exist_ok=True)
# Define pipeline steps and their output directories
pipeline_steps: list[Any] = [
("Template", "0_template_output", ["*.json", "*.md"]),
("Setup", "1_setup_output", ["*.json"]),
("Tests", "2_tests_output", ["*.txt", "*.json"]),
("GNN Processing", "3_gnn_output", ["*.json", "*.md", "*.pkl"]),
("Model Registry", "4_model_registry_output", ["*.json"]),
("Type Checker", "5_type_checker_output", ["*.json", "*.md"]),
("Validation", "6_validation_output", ["*.json"]),
("Export", "7_export_output", ["*.json", "*.xml", "*.pkl"]),
(
"Visualization",
"8_visualization_output",
["*.png", "*.svg", "*.csv", "*.json"],
),
("Advanced Visualization", "9_advanced_viz_output", ["*.png", "*.json"]),
("Ontology", "10_ontology_output", ["*.json"]),
("Render", "11_render_output", ["*.py", "*.jl", "*.md", "*.json", "*.png"]),
("Execute", "12_execute_output", ["*.txt", "*.json", "*.md", "*.png"]),
("LLM", "13_llm_output", ["*.md", "*.json"]),
("ML Integration", "14_ml_integration_output", ["*.json"]),
("Audio", "15_audio_output", ["*.json", "*.wav"]),
("Analysis", "16_analysis_output", ["*.json"]),
("Integration", "17_integration_output", ["*.json"]),
("Security", "18_security_output", ["*.json"]),
("Research", "19_research_output", ["*.json"]),
("Website", "20_website_output", ["*.html", "*.json"]),
("MCP", "21_mcp_output", ["*.json"]),
("GUI", "22_gui_output", ["*.md", "*.json"]),
("Report", "23_report_output", ["*.html", "*.md", "*.json"]),
(
"Intelligent Analysis",
"24_intelligent_analysis_output",
["*.json", "*.md", "*.html"],
),
]
# Collect output information
output_sections: list[Any] = []
total_files = 0
for step_name, step_dir, patterns in pipeline_steps:
step_path = pipeline_output_dir / step_dir
if not step_path.exists():
continue
step_files: list[Any] = []
for pattern in patterns:
for file_path in step_path.rglob(pattern):
if file_path.is_file():
try:
rel_path = str(file_path.relative_to(pipeline_output_dir))
file_size = file_path.stat().st_size
file_size_mb = file_size / (1024 * 1024)
step_files.append(
{
"name": file_path.name,
"path": rel_path,
"size_mb": round(file_size_mb, 3),
"type": file_path.suffix.lower(),
}
)
total_files += 1
except OSError as e:
logger.debug(f"Could not read file {file_path}: {e}")
if step_files:
step_files.sort(key=lambda x: (x["type"], x["name"]))
output_sections.append(
{
"step_name": step_name,
"step_dir": step_dir,
"file_count": len(step_files),
"files": step_files[:20],
}
)
# Generate HTML content
html_content = _build_navigation_html(
output_sections, total_files, pipeline_output_dir
)
# Write HTML file
nav_file = output_dir / "navigation.html"
with tempfile.NamedTemporaryFile(
mode="w", encoding="utf-8", dir=nav_file.parent, delete=False
) as tmp_f:
tmp_f.write(html_content)
os.replace(tmp_f.name, str(nav_file))
logger.info(f"✅ HTML navigation page generated: {nav_file}")
return True
except Exception as e:
logger.error(f"Failed to generate HTML navigation: {e}")
import traceback
logger.debug(traceback.format_exc())
return False
def _build_navigation_html(
output_sections: List[Dict[str, Any]], total_files: int, pipeline_output_dir: Path
) -> str:
"""Build the HTML content for the navigation page."""
html_content = f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>GNN Pipeline Output Navigation</title>
<style>
body {{
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
margin: 0;
padding: 20px;
background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
min-height: 100vh;
color: #2c3e50;
}}
.container {{
max-width: 1400px;
margin: 0 auto;
background: rgba(255, 255, 255, 0.75);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
border: 1px solid rgba(255, 255, 255, 0.3);
padding: 40px;
border-radius: 20px;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
}}
.header {{
text-align: center;
margin-bottom: 40px;
padding-bottom: 20px;
border-bottom: 2px solid rgba(0, 123, 255, 0.2);
}}
h1 {{ color: #1a202c; margin: 0; font-size: 2.8em; font-weight: 800; letter-spacing: -1px; }}
h2 {{ color: #2d3748; margin-top: 40px; margin-bottom: 20px; font-size: 1.8em; font-weight: 600; border-left: 5px solid #4299e1; padding-left: 15px; }}
.summary {{
background: linear-gradient(135deg, rgba(102, 126, 234, 0.8) 0%, rgba(118, 75, 162, 0.8) 100%);
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
border: 1px solid rgba(255,255,255,0.4);
color: white; padding: 30px; border-radius: 16px;
text-align: center; margin: 30px 0;
box-shadow: 0 8px 20px rgba(118, 75, 162, 0.2);
}}
.summary-grid {{ display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin-top: 20px; }}
.summary-card {{
background: rgba(255, 255, 255, 0.15);
border: 1px solid rgba(255,255,255,0.2);
border-radius: 12px; padding: 20px; text-align: center;
transition: transform 0.3s ease;
}}
.summary-card:hover {{ transform: translateY(-5px); background: rgba(255, 255, 255, 0.25); }}
.summary-card .value {{ font-size: 2.2em; font-weight: 800; color: #fff; margin: 10px 0; text-shadow: 0 2px 4px rgba(0,0,0,0.1); }}
.step-section {{
background: rgba(255, 255, 255, 0.6);
border: 1px solid rgba(255, 255, 255, 0.5);
border-radius: 16px; padding: 25px; margin: 25px 0;
box-shadow: 0 4px 6px rgba(0,0,0,0.02);
transition: all 0.3s ease;
}}
.step-section:hover {{ background: rgba(255, 255, 255, 0.8); box-shadow: 0 8px 15px rgba(0,0,0,0.05); }}
.step-header {{ font-weight: 700; color: #2d3748; margin-bottom: 15px; font-size: 1.3em; }}
.file-list {{ display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 15px; margin-top: 20px; }}
.file-item {{
background: rgba(255, 255, 255, 0.9);
border: 1px solid rgba(226, 232, 240, 0.8);
border-radius: 10px; padding: 15px;
transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}}
.file-item:hover {{ transform: translateY(-3px); box-shadow: 0 6px 12px rgba(0,0,0,0.08); border-color: #cbd5e0; }}
.file-item a {{ color: #3182ce; text-decoration: none; font-weight: 600; display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }}
.file-item a:hover {{ color: #2b6cb0; text-decoration: underline; }}
.file-meta {{ color: #718096; font-size: 12px; margin-top: 8px; font-weight: 500; text-transform: uppercase; letter-spacing: 0.5px; }}
.link {{ color: #3182ce; text-decoration: none; font-weight: 600; transition: color 0.2s; }}
.link:hover {{ color: #2b6cb0; text-decoration: underline; }}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>🎯 GNN Pipeline Output Navigation</h1>
<p>Comprehensive navigation to all pipeline outputs and artifacts</p>
</div>
<div class="summary">
<h2>Pipeline Overview</h2>
<div class="summary-grid">
<div class="summary-card">
<div>Pipeline Steps</div>
<div class="value">{len(output_sections)}</div>
</div>
<div class="summary-card">
<div>Total Files</div>
<div class="value">{total_files}</div>
</div>
<div class="summary-card">
<div>Output Directory</div>
<div class="value" style="font-size: 0.8em;">{pipeline_output_dir.name}</div>
</div>
</div>
</div>
<h2>📁 Output Sections</h2>
"""
# Add each step section
for section in output_sections:
html_content += f"""
<div class="step-section">
<div class="step-header">📂 {section["step_name"]} ({section["step_dir"]})</div>
<p><strong>Files:</strong> {section["file_count"]}</p>
<div class="file-list">
"""
for file_info in section["files"]:
html_content += f"""
<div class="file-item">
<a href="../{file_info["path"]}" target="_blank">{file_info["name"]}</a>
<div class="file-meta">{file_info["type"]} • {file_info["size_mb"]} MB</div>
</div>
"""
if section["file_count"] > len(section["files"]):
html_content += f"""
<div class="file-item" style="opacity: 0.7; font-style: italic;">
... and {section["file_count"] - len(section["files"])} more files
</div>
"""
html_content += """
</div>
</div>
"""
html_content += """
<div style="text-align: center; margin-top: 40px; padding-top: 20px; border-top: 1px solid #dee2e6; color: #6c757d;">
<p>Generated by GNN Pipeline GUI Module</p>
<p><a href="../23_report_output/comprehensive_analysis_report.html" class="link">View Comprehensive Report</a></p>
</div>
</div>
</body>
</html>
"""
return html_content