-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrohub_data_loader.html
More file actions
719 lines (608 loc) · 25.8 KB
/
rohub_data_loader.html
File metadata and controls
719 lines (608 loc) · 25.8 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ROHub Dataset Loader</title>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
max-width: 1000px;
margin: 0 auto;
padding: 20px;
background: linear-gradient(135deg, #173968 0%, #be2e78 100%);
min-height: 100vh;
}
.container {
background: white;
border-radius: 15px;
padding: 30px;
box-shadow: 0 15px 35px rgba(0,0,0,0.1);
}
h1 {
color: #333;
text-align: center;
margin-bottom: 30px;
background: linear-gradient(45deg, #173968, #be2e78);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
.input-section {
background: #f8f9fa;
padding: 25px;
border-radius: 12px;
margin-bottom: 25px;
border: 2px solid #e9ecef;
}
.input-group {
margin-bottom: 20px;
}
label {
display: block;
margin-bottom: 8px;
font-weight: 600;
color: #495057;
}
input, textarea, select {
width: 100%;
padding: 15px;
border: 2px solid #ddd;
border-radius: 8px;
font-size: 16px;
transition: all 0.3s ease;
box-sizing: border-box;
}
input:focus, textarea:focus, select:focus {
outline: none;
border-color: #173968;
box-shadow: 0 0 0 3px rgba(23, 57, 104, 0.1);
}
button {
background: linear-gradient(45deg, #173968, #be2e78);
color: white;
border: none;
padding: 15px 25px;
border-radius: 8px;
cursor: pointer;
font-size: 16px;
font-weight: 600;
transition: all 0.3s ease;
margin: 5px;
}
button:hover:not(:disabled) {
transform: translateY(-2px);
box-shadow: 0 8px 20px rgba(23, 57, 104, 0.3);
}
button:disabled {
background: #6c757d;
cursor: not-allowed;
transform: none;
}
.status {
margin: 20px 0;
padding: 15px 20px;
border-radius: 8px;
font-weight: 600;
}
.status.loading {
background: #e3f2fd;
color: #1565c0;
border: 2px solid #1976d2;
}
.status.success {
background: #e8f5e8;
color: #2e7d32;
border: 2px solid #4caf50;
}
.status.error {
background: #ffebee;
color: #c62828;
border: 2px solid #f44336;
}
.resource-selector {
background: #f8f9fa;
border: 2px solid #e9ecef;
border-radius: 12px;
margin: 20px 0;
padding: 20px;
display: none;
}
.data-viewer {
background: #f8f9fa;
border: 2px solid #e9ecef;
border-radius: 12px;
margin: 20px 0;
overflow: hidden;
display: none;
}
.data-header {
background: linear-gradient(45deg, #be2e78, #173968);
color: white;
padding: 20px;
font-weight: 600;
font-size: 1.2em;
}
.data-content {
padding: 25px;
max-height: 600px;
overflow-y: auto;
background: white;
}
.data-content pre {
background: #f8f9fa;
padding: 20px;
border-radius: 8px;
border: 1px solid #e9ecef;
overflow-x: auto;
font-family: 'Courier New', monospace;
font-size: 14px;
line-height: 1.6;
}
.json-viewer {
font-family: 'Courier New', monospace;
}
.json-key { color: #173968; font-weight: bold; }
.json-string { color: #be2e78; }
.json-number { color: #cc6600; }
.json-boolean { color: #cc0066; font-weight: bold; }
.spinner {
width: 20px;
height: 20px;
border: 2px solid #1976d2;
border-top: 2px solid transparent;
border-radius: 50%;
animation: spin 1s linear infinite;
display: inline-block;
margin-right: 10px;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.url-type {
font-size: 14px;
color: #6c757d;
margin-bottom: 10px;
}
.save-data-section {
background: #e8f5e8;
border: 2px solid #4caf50;
border-radius: 12px;
padding: 20px;
margin: 20px 0;
display: none;
}
.buttons-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 10px;
margin-top: 15px;
}
.file-info {
background: #fff3cd;
border: 2px solid #ffc107;
border-radius: 8px;
padding: 15px;
margin: 15px 0;
font-size: 14px;
}
</style>
</head>
<body>
<div class="container">
<h1>🔬 ROHub Dataset Loader</h1>
<div class="input-section">
<div class="input-group">
<label for="rohubUrl">ROHub URL (Resource or Research Object):</label>
<textarea id="rohubUrl" rows="3" placeholder="Paste your ROHub URL here...">https://w3id.org/ro-id/d5430aa5-7a8b-44fe-8d21-6a7c80ac36d4/resources/8d4cb501-4697-45ed-be43-65e001e07e8f</textarea>
<div id="urlType" class="url-type"></div>
</div>
<div>
<button onclick="analyzeAndLoad()">🔍 Load from ROHub</button>
<button onclick="clearAll()">🗑️ Clear</button>
</div>
</div>
<div id="status"></div>
<div id="resourceSelector" class="resource-selector">
<h3>📁 Select a Resource</h3>
<div class="input-group">
<label for="resourceSelect">Available resources:</label>
<select id="resourceSelect">
<option value="">-- Loading resources --</option>
</select>
</div>
<button onclick="loadSelectedResource()">📥 Load Selected Resource</button>
</div>
<div id="saveDataSection" class="save-data-section">
<h3>💾 Save Data Locally</h3>
<p>Data loaded successfully! Choose how to save this data to your computer:</p>
<div class="file-info">
<strong>📋 Instructions:</strong><br>
• Save as <strong>file</strong> to use with the Warming Stripes Visualizer<br>
• Place saved files in your <code>inputs/</code> folder for easy access<br>
</div>
<div class="buttons-grid">
<button onclick="saveAsCSV()">📄 Save File</button>
<button onclick="copyToClipboard()">📋 Copy to Clipboard</button>
</div>
</div>
<div id="dataViewer" class="data-viewer">
<div class="data-header" id="dataHeader">
📄 Dataset Content
</div>
<div class="data-content" id="dataContent">
</div>
</div>
</div>
<script>
// Global variables
let currentData = null;
let currentRO = null;
let parsedCSVData = null;
// Initialize without metaframe
document.addEventListener('DOMContentLoaded', function() {
console.log('🚀 Initializing ROHub Data Loader (Standalone Mode)...');
// Auto-detect URL type on input
document.getElementById('rohubUrl').addEventListener('input', detectUrlType);
detectUrlType();
});
function detectUrlType() {
const url = document.getElementById('rohubUrl').value.trim();
const typeDiv = document.getElementById('urlType');
if (!url) {
typeDiv.textContent = '';
return;
}
if (url.includes('/resources/')) {
typeDiv.textContent = '🔗 Individual Resource URL - will load directly';
typeDiv.style.color = '#28a745';
} else if (url.match(/\/ro-id\/[a-f0-9-]+\/?$/)) {
typeDiv.textContent = '📁 Research Object URL - will show resource selector';
typeDiv.style.color = '#007bff';
} else {
typeDiv.textContent = '❓ URL format not recognized';
typeDiv.style.color = '#dc3545';
}
}
async function analyzeAndLoad() {
const url = document.getElementById('rohubUrl').value.trim();
if (!url) {
showStatus('❌ Please enter a ROHub URL', 'error');
return;
}
// Determine if it's a resource or research object URL
if (url.includes('/resources/')) {
// Direct resource URL
await loadResourceDirectly(url);
} else {
// Research object URL
await loadResearchObjectAndShowSelector(url);
}
}
async function loadResourceDirectly(resourceUrl) {
showStatus('🔄 Loading resource directly...', 'loading');
try {
const content = await fetchResourceContent(resourceUrl);
const resourceName = extractResourceName(resourceUrl);
currentData = content;
displayData(content, resourceName, 'Direct resource');
parseAndStoreData(content, resourceName, resourceUrl);
showStatus('✅ Resource loaded successfully!', 'success');
showSaveDataSection();
} catch (error) {
showStatus(`❌ Error loading resource: ${error.message}`, 'error');
}
}
async function loadResearchObjectAndShowSelector(roUrl) {
showStatus('🔄 Loading research object...', 'loading');
try {
// Extract RO ID from URL
const roIdMatch = roUrl.match(/\/ro-id\/([a-f0-9-]+)/);
if (!roIdMatch) {
throw new Error('Invalid Research Object URL format');
}
const roId = roIdMatch[1];
// Load RO metadata
const roApiUrl = `https://api.rohub.org/api/ros/${roId}/`;
const roData = await fetchWithProxy(roApiUrl);
currentRO = roData;
// Load resources
const resourcesApiUrl = `https://api.rohub.org/api/ros/${roId}/resources/`;
const resourcesResponse = await fetchWithProxy(resourcesApiUrl);
const resources = resourcesResponse.results || resourcesResponse;
// Show resource selector
populateResourceSelector(resources, roId);
showStatus('✅ Research object loaded! Select a resource below.', 'success');
} catch (error) {
showStatus(`❌ Error loading research object: ${error.message}`, 'error');
}
}
function populateResourceSelector(resources, roId) {
const selector = document.getElementById('resourceSelector');
const select = document.getElementById('resourceSelect');
select.innerHTML = '<option value="">-- Select a resource --</option>';
resources.forEach((resource, index) => {
const resourceName = resource.name || resource.title || resource.identifier || `Resource ${index + 1}`;
const resourceType = resource.mimetype || resource.res_type || resource.type || 'Unknown';
const resourceId = resource.identifier || resource.res_id || resource.id;
const option = document.createElement('option');
option.value = index;
option.textContent = `${resourceName} (${resourceType})`;
// Store resource info in data attributes
option.dataset.resourceId = resourceId;
option.dataset.name = resourceName;
option.dataset.type = resourceType;
option.dataset.roId = roId;
select.appendChild(option);
});
selector.style.display = 'block';
}
async function loadSelectedResource() {
const select = document.getElementById('resourceSelect');
if (select.value === '') {
showStatus('❌ Please select a resource', 'error');
return;
}
const option = select.options[select.selectedIndex];
const resourceId = option.dataset.resourceId;
const resourceName = option.dataset.name;
const roId = option.dataset.roId;
showStatus('🔄 Loading selected resource...', 'loading');
try {
// Construct resource URL
const resourceUrl = `https://w3id.org/ro-id/${roId}/resources/${resourceId}`;
const content = await fetchResourceContent(resourceUrl);
currentData = content;
displayData(content, resourceName, 'Selected from RO');
parseAndStoreData(content, resourceName, resourceUrl);
showStatus('✅ Resource loaded successfully!', 'success');
showSaveDataSection();
} catch (error) {
showStatus(`❌ Error loading resource: ${error.message}`, 'error');
}
}
function parseAndStoreData(content, name, url) {
console.log('🔄 Parsing data for local storage...');
try {
// Try to parse as CSV
if (content.includes(',') && content.includes('\n')) {
const lines = content.trim().split('\n');
if (lines.length > 1) {
const headers = lines[0].split(',').map(h => h.trim().replace(/^"(.*)"$/, '$1'));
const data = lines.slice(1).map(line => {
const values = line.split(',').map(v => v.trim().replace(/^"(.*)"$/, '$1'));
const row = {};
headers.forEach((header, index) => {
const value = values[index];
const numValue = parseFloat(value);
row[header] = isNaN(numValue) ? value : numValue;
});
return row;
});
parsedCSVData = {
type: 'csv',
name: name,
url: url,
headers: headers,
data: data,
rawContent: content
};
console.log('✅ CSV data parsed successfully:', parsedCSVData);
return;
}
}
// Try to parse as JSON
try {
const jsonData = JSON.parse(content);
parsedCSVData = {
type: 'json',
name: name,
url: url,
data: jsonData,
rawContent: content
};
console.log('✅ JSON data parsed successfully:', parsedCSVData);
return;
} catch (e) {
// Not JSON
}
// Plain text
parsedCSVData = {
type: 'text',
name: name,
url: url,
content: content,
rawContent: content
};
console.log('✅ Text data stored successfully:', parsedCSVData);
} catch (error) {
console.error('❌ Error parsing data:', error);
parsedCSVData = null;
}
}
function showSaveDataSection() {
document.getElementById('saveDataSection').style.display = 'block';
}
function saveAsCSV() {
if (!parsedCSVData) {
showStatus('❌ No data available to save', 'error');
return;
}
const filename = sanitizeFilename(parsedCSVData.name) + '.csv';
downloadFile(parsedCSVData.rawContent, filename, 'text/csv');
showStatus('✅ File saved!', 'success');
}
function copyToClipboard() {
if (!parsedCSVData) {
showStatus('❌ No data available to copy', 'error');
return;
}
navigator.clipboard.writeText(parsedCSVData.rawContent).then(() => {
showStatus('✅ Data copied to clipboard!', 'success');
}).catch(err => {
console.error('Failed to copy:', err);
showStatus('❌ Failed to copy to clipboard', 'error');
});
}
function downloadFile(content, filename, mimeType) {
const blob = new Blob([content], { type: mimeType });
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}
function sanitizeFilename(filename) {
// Remove invalid characters and replace spaces
return filename.replace(/[^a-zA-Z0-9]/g, '_').replace(/_+/g, '_').toLowerCase();
}
async function fetchResourceContent(url) {
const methods = [
// Direct fetch with different Accept headers
async () => {
const response = await fetch(url, {
mode: 'cors',
headers: { 'Accept': '*/*' }
});
if (response.ok) return await response.text();
throw new Error(`HTTP ${response.status}`);
},
// AllOrigins proxy
async () => {
const proxyUrl = `https://api.allorigins.win/get?url=${encodeURIComponent(url)}`;
const response = await fetch(proxyUrl);
if (response.ok) {
const data = await response.json();
return data.contents;
}
throw new Error('Proxy failed');
},
// CORS proxy
async () => {
const proxyUrl = `https://corsproxy.io/?${encodeURIComponent(url)}`;
const response = await fetch(proxyUrl);
if (response.ok) return await response.text();
throw new Error('CORS proxy failed');
}
];
for (const method of methods) {
try {
return await method();
} catch (error) {
console.log('Method failed:', error.message);
}
}
throw new Error('All access methods failed');
}
async function fetchWithProxy(url) {
try {
const response = await fetch(url, {
mode: 'cors',
headers: { 'Accept': 'application/json' }
});
if (response.ok) return await response.json();
throw new Error(`HTTP ${response.status}`);
} catch (error) {
// Fallback to proxy
const proxyUrl = `https://api.allorigins.win/get?url=${encodeURIComponent(url)}`;
const proxyResponse = await fetch(proxyUrl);
if (proxyResponse.ok) {
const proxyData = await proxyResponse.json();
return JSON.parse(proxyData.contents);
}
throw error;
}
}
function extractResourceName(url) {
const parts = url.split('/');
return parts[parts.length - 1] || 'Resource';
}
function displayData(content, name, source) {
const viewer = document.getElementById('dataViewer');
const header = document.getElementById('dataHeader');
const contentDiv = document.getElementById('dataContent');
header.textContent = `📄 ${name} (${source})`;
let formattedContent;
// Try to format as JSON
try {
const parsed = JSON.parse(content);
formattedContent = `<div class="json-viewer">${syntaxHighlightJSON(JSON.stringify(parsed, null, 2))}</div>`;
} catch (e) {
// Check if it's CSV
if (content.includes(',') && content.includes('\n')) {
formattedContent = formatAsTable(content);
} else {
// Plain text
formattedContent = `<pre>${escapeHtml(content)}</pre>`;
}
}
contentDiv.innerHTML = formattedContent;
viewer.style.display = 'block';
}
function formatAsTable(csvContent) {
const lines = csvContent.trim().split('\n').slice(0, 50); // Show first 50 rows
if (lines.length < 2) return `<pre>${escapeHtml(csvContent)}</pre>`;
let html = '<table style="width: 100%; border-collapse: collapse; font-size: 14px;">';
lines.forEach((line, index) => {
const cells = line.split(',').map(cell => cell.trim().replace(/^"(.*)"$/, '$1'));
const tag = index === 0 ? 'th' : 'td';
const style = index === 0 ? 'background: #f8f9fa; font-weight: bold;' : '';
html += '<tr>';
cells.forEach(cell => {
html += `<${tag} style="border: 1px solid #ddd; padding: 8px; ${style}">${escapeHtml(cell)}</${tag}>`;
});
html += '</tr>';
});
html += '</table>';
return html;
}
function syntaxHighlightJSON(json) {
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
let cls = 'json-number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'json-key';
} else {
cls = 'json-string';
}
} else if (/true|false/.test(match)) {
cls = 'json-boolean';
}
return '<span class="' + cls + '">' + match + '</span>';
});
}
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
function clearAll() {
document.getElementById('resourceSelector').style.display = 'none';
document.getElementById('dataViewer').style.display = 'none';
document.getElementById('saveDataSection').style.display = 'none';
document.getElementById('status').innerHTML = '';
currentData = null;
currentRO = null;
parsedCSVData = null;
}
function showStatus(message, type) {
const statusDiv = document.getElementById('status');
if (type === 'loading') {
statusDiv.innerHTML = `<div class="status ${type}"><span class="spinner"></span>${message}</div>`;
} else {
statusDiv.innerHTML = `<div class="status ${type}">${message}</div>`;
}
if (type === 'success') {
setTimeout(() => {
statusDiv.innerHTML = '';
}, 3000);
}
}
</script>
</body>
</html>