-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
1270 lines (1109 loc) · 46.1 KB
/
Copy pathindex.html
File metadata and controls
1270 lines (1109 loc) · 46.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
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
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Q&A Dataset Generator</title>
<style>
:root {
/* Light mode colors */
--bg-gradient-start: white;
--bg-gradient-end: gainsboro;
--container-bg: #ffffff;
--section-bg: #f8f9fa;
--section-border: #e9ecef;
--text-primary: #333333;
--text-secondary: #555555;
--text-muted: #666666;
--text-light: #999999;
--input-bg: #ffffff;
--input-border: #dddddd;
--card-bg: #ffffff;
--stat-card-shadow: rgba(0, 0, 0, 0.1);
--qa-pair-shadow: rgba(0, 0, 0, 0.1);
--primary-color: #0f3460;
--primary-dark: #16213e;
--info-bg: #d1ecf1;
--info-border: #bee5eb;
--info-text: #0c5460;
--error-bg: #f8d7da;
--error-border: #f5c6cb;
--error-text: #721c24;
}
[data-theme="dark"] {
/* Dark mode colors */
--bg-gradient-start: #1a1a2e;
--bg-gradient-end: #16213e;
--container-bg: #0f3460;
--section-bg: #1a1a2e;
--section-border: #2d2d44;
--text-primary: #e8e8e8;
--text-secondary: #c8c8c8;
--text-muted: #a8a8a8;
--text-light: #888888;
--input-bg: #1a1a2e;
--input-border: #2d2d44;
--card-bg: #16213e;
--stat-card-shadow: rgba(0, 0, 0, 0.3);
--qa-pair-shadow: rgba(0, 0, 0, 0.3);
--primary-color: #0f3460;
--primary-dark: #16213e;
--info-bg: #1e3a4f;
--info-border: #2d5570;
--info-text: #89cff0;
--error-bg: #3d1f1f;
--error-border: #5c2e2e;
--error-text: #ff6b6b;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, var(--bg-gradient-start) 0%, var(--bg-gradient-end) 100%);
min-height: 100vh;
padding: 20px;
color: var(--text-primary);
transition: background 0.3s ease, color 0.3s ease;
}
.container {
max-width: 1200px;
margin: 0 auto;
background: var(--container-bg);
border-radius: 10px;
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
overflow: hidden;
transition: background 0.3s ease;
}
header {
background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-dark) 100%);
color: white;
padding: 30px;
text-align: center;
position: relative;
}
header h1 {
font-size: 2.5em;
margin-bottom: 10px;
}
header p {
font-size: 1.1em;
opacity: 0.9;
}
.theme-toggle {
position: absolute;
top: 20px;
right: 20px;
background: rgba(255, 255, 255, 0.2);
border: 2px solid rgba(255, 255, 255, 0.3);
color: white;
padding: 10px 20px;
border-radius: 25px;
cursor: pointer;
font-size: 1em;
font-weight: 600;
transition: all 0.3s ease;
display: flex;
align-items: center;
gap: 8px;
}
.theme-toggle:hover {
background: rgba(255, 255, 255, 0.3);
transform: translateY(-2px);
}
.theme-icon {
font-size: 1.2em;
}
.content {
padding: 30px;
}
.section {
margin-bottom: 30px;
padding: 20px;
background: var(--section-bg);
border-radius: 8px;
border: 1px solid var(--section-border);
transition: background 0.3s ease, border-color 0.3s ease;
}
.section-title {
font-size: 1.5em;
margin-bottom: 15px;
color: var(--primary-color);
border-bottom: 2px solid var(--primary-color);
padding-bottom: 10px;
}
.form-group {
margin-bottom: 15px;
}
label {
display: block;
margin-bottom: 5px;
font-weight: 600;
color: var(--text-secondary);
transition: color 0.3s ease;
}
input[type="text"],
input[type="number"],
input[type="password"],
textarea {
width: 100%;
padding: 12px;
border: 2px solid var(--input-border);
border-radius: 6px;
font-size: 1em;
transition: border-color 0.3s, background 0.3s, color 0.3s;
background: var(--input-bg);
color: var(--text-primary);
}
input[type="text"]:focus,
input[type="number"]:focus,
input[type="password"]:focus,
textarea:focus {
outline: none;
border-color: var(--primary-color);
}
textarea {
resize: vertical;
min-height: 80px;
}
.button-group {
display: flex;
gap: 10px;
flex-wrap: wrap;
}
button {
padding: 12px 24px;
font-size: 1em;
font-weight: 600;
border: none;
border-radius: 6px;
cursor: pointer;
transition: all 0.3s;
flex: 1;
min-width: 150px;
}
button.primary {
background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-dark) 100%);
color: white;
}
button.primary:hover {
transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
}
button.secondary {
background: #6c757d;
color: white;
}
button.secondary:hover {
background: #5a6268;
}
button.success {
background: #28a745;
color: white;
}
button.success:hover {
background: #218838;
}
button.danger {
background: #dc3545;
color: white;
}
button.danger:hover {
background: #c82333;
}
button:disabled {
opacity: 0.6;
cursor: not-allowed;
transform: none !important;
}
.export-wrapper {
position: relative;
flex: 1;
min-width: 150px;
}
.export-split {
display: flex;
width: 100%;
}
.export-split .export-main {
border-radius: 6px 0 0 6px;
flex: 1;
min-width: 0;
}
.export-split .export-caret {
border-radius: 0 6px 6px 0;
border-left: 1px solid rgba(255, 255, 255, 0.3);
padding: 12px 14px;
flex: 0 0 auto;
min-width: 0;
}
.export-menu {
display: none;
position: absolute;
top: calc(100% + 4px);
left: 0;
background: var(--card-bg);
border: 1px solid var(--section-border);
border-radius: 6px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
z-index: 100;
min-width: 180px;
overflow: hidden;
}
.export-menu.open {
display: block;
}
.export-menu button {
display: block;
width: 100%;
text-align: left;
background: none;
color: var(--text-primary);
padding: 10px 16px;
border: none;
border-radius: 0;
font-size: 0.95em;
font-weight: 500;
flex: none;
min-width: 0;
}
.export-menu button:hover {
background: var(--section-bg);
transform: none;
}
.progress-container {
margin-top: 20px;
display: none;
}
.progress-bar {
width: 100%;
height: 30px;
background: var(--section-border);
border-radius: 15px;
overflow: hidden;
position: relative;
transition: background 0.3s ease;
}
.progress-fill {
height: 100%;
background: linear-gradient(90deg, var(--primary-color) 0%, var(--primary-dark) 100%);
transition: width 0.3s;
display: flex;
align-items: center;
justify-content: center;
color: white;
font-weight: 600;
}
.progress-text {
margin-top: 10px;
text-align: center;
color: var(--text-secondary);
font-weight: 600;
transition: color 0.3s ease;
}
.qa-pairs {
margin-top: 20px;
}
.qa-pair {
background: var(--card-bg);
padding: 15px;
margin-bottom: 15px;
border-radius: 6px;
border-left: 4px solid var(--primary-color);
box-shadow: 0 2px 5px var(--qa-pair-shadow);
transition: background 0.3s ease, box-shadow 0.3s ease;
}
.qa-pair-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
}
.qa-pair-number {
font-weight: 600;
color: var(--primary-color);
}
.qa-pair-actions {
display: flex;
gap: 5px;
}
.qa-pair-actions button {
padding: 5px 10px;
font-size: 0.85em;
min-width: auto;
}
.question {
margin-bottom: 10px;
}
.question strong {
color: var(--primary-color);
}
.answer strong {
color: var(--primary-dark);
}
.stats {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 15px;
margin-bottom: 20px;
}
.stat-card {
background: var(--card-bg);
padding: 20px;
border-radius: 8px;
text-align: center;
box-shadow: 0 2px 5px var(--stat-card-shadow);
transition: background 0.3s ease, box-shadow 0.3s ease;
}
.stat-value {
font-size: 2.5em;
font-weight: bold;
color: var(--primary-color);
}
.stat-label {
color: var(--text-muted);
margin-top: 5px;
transition: color 0.3s ease;
}
.info-box {
background: var(--info-bg);
border: 1px solid var(--info-border);
color: var(--info-text);
padding: 15px;
border-radius: 6px;
margin-bottom: 20px;
transition: background 0.3s ease, border-color 0.3s ease, color 0.3s ease;
}
.error-box {
background: var(--error-bg);
border: 1px solid var(--error-border);
color: var(--error-text);
padding: 15px;
border-radius: 6px;
margin-bottom: 20px;
display: none;
transition: background 0.3s ease, border-color 0.3s ease, color 0.3s ease;
}
.hidden {
display: none;
}
input[type="file"] {
padding: 10px;
border: 2px dashed var(--primary-color);
border-radius: 6px;
width: 100%;
cursor: pointer;
background: var(--input-bg);
color: var(--text-primary);
transition: background 0.3s ease, color 0.3s ease;
}
.dataset-info {
background: var(--card-bg);
padding: 15px;
border-radius: 6px;
margin-top: 15px;
border: 1px solid var(--input-border);
transition: background 0.3s ease, border-color 0.3s ease;
}
.checkpoint-banner {
background: var(--info-bg);
border: 1px solid var(--info-border);
color: var(--info-text);
padding: 15px 20px;
border-radius: 6px;
margin-bottom: 20px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
flex-wrap: wrap;
transition: background 0.3s ease, border-color 0.3s ease, color 0.3s ease;
}
.checkpoint-banner.hidden {
display: none;
}
.checkpoint-actions {
display: flex;
gap: 8px;
flex-shrink: 0;
}
.checkpoint-actions button {
padding: 8px 14px;
min-width: auto;
flex: none;
font-size: 0.9em;
}
</style>
</head>
<body>
<div class="container">
<header>
<button class="theme-toggle" onclick="toggleTheme()" aria-label="Toggle theme">
<span class="theme-icon" id="themeIcon">🌙</span>
<span id="themeText">Dark</span>
</button>
<h1>Q&A Dataset Generator</h1>
<p>Generate high-quality question and answer pairs for LLM training</p>
</header>
<div class="content">
<div id="checkpointBanner" class="checkpoint-banner hidden">
<span>Checkpoint found: <strong id="checkpointCount">0</strong> pairs saved from a previous session.</span>
<div class="checkpoint-actions">
<button class="primary" onclick="restoreCheckpoint()">Restore <span id="checkpointCountBtn">0</span> pairs</button>
<button class="secondary" onclick="dismissCheckpoint()">Start fresh</button>
</div>
</div>
<div class="error-box" id="errorBox"></div>
<div class="section">
<h2 class="section-title">API Configuration</h2>
<div class="form-group">
<label for="apiEndpoint">API Endpoint:</label>
<input type="text" id="apiEndpoint" placeholder="https://api.openai.com/v1/chat/completions" value="https://api.openai.com/v1/chat/completions">
</div>
<div class="form-group">
<label for="apiKey">API Key:</label>
<input type="password" id="apiKey" placeholder="sk-...">
</div>
<div class="form-group">
<label for="modelName">Model Name:</label>
<input type="text" id="modelName" placeholder="gpt-3.5-turbo" value="gpt-3.5-turbo">
</div>
</div>
<div class="section">
<h2 class="section-title">Dataset Configuration</h2>
<div class="form-group">
<label for="topic">Topic:</label>
<textarea id="topic" placeholder="e.g., Python programming, Machine Learning basics, World History, etc."></textarea>
</div>
<div class="form-group">
<label for="numPairs">Number of Q&A Pairs:</label>
<input type="number" id="numPairs" min="1" value="100">
<div class="info-box">
Recommended minimum: 100 pairs for a useful training dataset
</div>
</div>
<div class="form-group">
<label for="batchSize">Batch Size (pairs generated per request):</label>
<input type="number" id="batchSize" min="1" value="5">
<div class="info-box" style="margin-top: 8px;">
Larger batches are faster but may occasionally be truncated by the model.
</div>
</div>
<div class="form-group">
<label for="concurrency">Parallel Batches (1–10):</label>
<input type="number" id="concurrency" min="1" max="10" value="3">
</div>
<div class="button-group">
<button class="primary" id="generateBtn" onclick="startGeneration()">Generate Dataset</button>
<button class="danger" id="stopBtn" onclick="stopGeneration()" style="display: none;">Stop Generation</button>
</div>
<div class="progress-container" id="progressContainer">
<div class="progress-bar">
<div class="progress-fill" id="progressFill">0%</div>
</div>
<div class="progress-text" id="progressText">Generating...</div>
</div>
</div>
<div class="section">
<h2 class="section-title">Current Dataset</h2>
<div class="stats">
<div class="stat-card">
<div class="stat-value" id="pairCount">0</div>
<div class="stat-label">Q&A Pairs</div>
</div>
<div class="stat-card">
<div class="stat-value" id="avgQLength">0</div>
<div class="stat-label">Avg Question Length</div>
</div>
<div class="stat-card">
<div class="stat-value" id="avgALength">0</div>
<div class="stat-label">Avg Answer Length</div>
</div>
<div class="stat-card">
<div class="stat-value" id="duplicatesSkipped">0</div>
<div class="stat-label">Duplicates Skipped</div>
</div>
</div>
<div class="button-group">
<div class="export-wrapper">
<div class="export-split">
<button class="success export-main" onclick="exportDataset('json')">Export JSON</button>
<button class="success export-caret" onclick="toggleExportMenu(event)" aria-label="More export formats" title="More export formats">▼</button>
</div>
<div class="export-menu" id="exportMenu">
<button onclick="exportDataset('json')">JSON (.json)</button>
<button onclick="exportDataset('jsonl')">JSONL (.jsonl)</button>
<button onclick="exportDataset('alpaca')">Alpaca (.json)</button>
<button onclick="exportDataset('csv')">CSV (.csv)</button>
</div>
</div>
<button class="secondary" onclick="clearDataset()">Clear Dataset</button>
<button class="secondary" onclick="document.getElementById('importFile').click()">Import Dataset</button>
</div>
<input type="file" id="importFile" accept=".json" style="display: none;" onchange="importDataset(event)">
<div id="datasetInfo" class="dataset-info hidden"></div>
</div>
<div class="section">
<h2 class="section-title">Combine Datasets</h2>
<div class="info-box">
Upload multiple JSON dataset files to combine them into a single dataset
</div>
<div class="form-group">
<label for="combineFiles">Select Multiple Dataset Files:</label>
<input type="file" id="combineFiles" accept=".json" multiple onchange="combineDatasets(event)">
</div>
</div>
<div class="section">
<h2 class="section-title">Generated Q&A Pairs</h2>
<div class="qa-pairs" id="qaPairs">
<p style="text-align: center; color: #999;">No pairs generated yet. Configure the settings above and click "Generate Dataset".</p>
</div>
</div>
</div>
</div>
<script>
// Theme Management
function initTheme() {
const savedTheme = localStorage.getItem('theme') || 'light';
document.documentElement.setAttribute('data-theme', savedTheme);
updateThemeButton(savedTheme);
}
function toggleTheme() {
const currentTheme = document.documentElement.getAttribute('data-theme') || 'light';
const newTheme = currentTheme === 'light' ? 'dark' : 'light';
document.documentElement.setAttribute('data-theme', newTheme);
localStorage.setItem('theme', newTheme);
updateThemeButton(newTheme);
}
function updateThemeButton(theme) {
const themeIcon = document.getElementById('themeIcon');
const themeText = document.getElementById('themeText');
if (theme === 'dark') {
themeIcon.textContent = '☀️';
themeText.textContent = 'Light';
} else {
themeIcon.textContent = '🌙';
themeText.textContent = 'Dark';
}
}
// Initialize theme on page load
initTheme();
// Dataset Management
let dataset = [];
let isGenerating = false;
let shouldStop = false;
let seenFingerprints = new Set();
let duplicatesSkipped = 0;
const CHECKPOINT_KEY = 'qa_dataset_checkpoint';
function fingerprint(question) {
return question.toLowerCase()
.replace(/[^\w\s]/g, '')
.replace(/\s+/g, ' ')
.trim();
}
function rebuildFingerprints() {
seenFingerprints = new Set(dataset.map(p => fingerprint(p.question)));
}
function saveCheckpoint() {
try {
localStorage.setItem(CHECKPOINT_KEY, JSON.stringify(dataset));
} catch (e) {
if (e.name === 'QuotaExceededError' || e.code === 22) {
showError('Dataset too large to auto-save \u2014 export a checkpoint manually');
}
}
}
function checkForCheckpoint() {
const saved = localStorage.getItem(CHECKPOINT_KEY);
if (!saved) return;
try {
const parsed = JSON.parse(saved);
if (!Array.isArray(parsed) || parsed.length === 0) return;
const count = parsed.length;
document.getElementById('checkpointCount').textContent = count;
document.getElementById('checkpointCountBtn').textContent = count;
document.getElementById('checkpointBanner').classList.remove('hidden');
window._checkpointData = parsed;
} catch (e) {
localStorage.removeItem(CHECKPOINT_KEY);
}
}
function restoreCheckpoint() {
const data = window._checkpointData;
if (!data) return;
dataset = data;
rebuildFingerprints();
duplicatesSkipped = 0;
updateStats();
renderQAPairs();
document.getElementById('checkpointBanner').classList.add('hidden');
window._checkpointData = null;
}
function dismissCheckpoint() {
localStorage.removeItem(CHECKPOINT_KEY);
document.getElementById('checkpointBanner').classList.add('hidden');
window._checkpointData = null;
}
function showError(message) {
const errorBox = document.getElementById('errorBox');
errorBox.textContent = message;
errorBox.style.display = 'block';
setTimeout(() => {
errorBox.style.display = 'none';
}, 5000);
}
function updateStats() {
document.getElementById('pairCount').textContent = dataset.length;
document.getElementById('duplicatesSkipped').textContent = duplicatesSkipped;
if (dataset.length > 0) {
const avgQ = Math.round(dataset.reduce((sum, pair) => sum + pair.question.length, 0) / dataset.length);
const avgA = Math.round(dataset.reduce((sum, pair) => sum + pair.answer.length, 0) / dataset.length);
document.getElementById('avgQLength').textContent = avgQ;
document.getElementById('avgALength').textContent = avgA;
} else {
document.getElementById('avgQLength').textContent = '0';
document.getElementById('avgALength').textContent = '0';
}
}
function createQAPairElement(pair, index) {
const div = document.createElement('div');
div.className = 'qa-pair';
div.id = `pair-${index}`;
div.innerHTML = `
<div class="qa-pair-header">
<span class="qa-pair-number">Pair #${index + 1}</span>
<div class="qa-pair-actions">
<button class="secondary">Edit</button>
<button class="danger">Delete</button>
</div>
</div>
<div class="question">
<strong>Q:</strong> ${escapeHtml(pair.question)}
</div>
<div class="answer">
<strong>A:</strong> ${escapeHtml(pair.answer)}
</div>
`;
const actions = div.querySelectorAll('.qa-pair-actions button');
actions[0].addEventListener('click', () => editPair(index));
actions[1].addEventListener('click', () => deletePair(index));
return div;
}
function renderQAPairs() {
const container = document.getElementById('qaPairs');
container.innerHTML = '';
if (dataset.length === 0) {
container.innerHTML = '<p style="text-align: center; color: #999;">No pairs generated yet. Configure the settings above and click "Generate Dataset".</p>';
return;
}
const fragment = document.createDocumentFragment();
dataset.forEach((pair, index) => fragment.appendChild(createQAPairElement(pair, index)));
container.appendChild(fragment);
}
function appendQAPairs(pairs, startIndex) {
const container = document.getElementById('qaPairs');
// Remove placeholder text if present
const placeholder = container.querySelector('p');
if (placeholder) placeholder.remove();
const fragment = document.createDocumentFragment();
pairs.forEach((pair, i) => fragment.appendChild(createQAPairElement(pair, startIndex + i)));
container.appendChild(fragment);
}
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
function deletePair(index) {
if (confirm('Are you sure you want to delete this Q&A pair?')) {
dataset.splice(index, 1);
updateStats();
renderQAPairs();
}
}
function editPair(index) {
const pair = dataset[index];
const newQuestion = prompt('Edit Question:', pair.question);
if (newQuestion !== null && newQuestion.trim() !== '') {
const newAnswer = prompt('Edit Answer:', pair.answer);
if (newAnswer !== null && newAnswer.trim() !== '') {
dataset[index] = { question: newQuestion.trim(), answer: newAnswer.trim() };
updateStats();
renderQAPairs();
}
}
}
async function callLLM(prompt) {
const apiEndpoint = document.getElementById('apiEndpoint').value;
const apiKey = document.getElementById('apiKey').value;
const modelName = document.getElementById('modelName').value;
const response = await fetch(apiEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({
model: modelName,
messages: [
{
role: 'system',
content: 'You are a helpful assistant that generates high-quality question and answer pairs for training language models. Generate diverse, educational, and well-structured Q&A pairs. Always return valid, complete JSON.'
},
{
role: 'user',
content: prompt
}
],
temperature: 0.8,
max_tokens: 4000
})
});
if (!response.ok) {
const error = await response.text();
throw new Error(`API Error: ${response.status} - ${error}`);
}
const data = await response.json();
return data.choices[0].message.content;
}
function sanitizeText(text) {
// Replace problematic Unicode characters with standard ASCII equivalents
return text
.replace(/[\u2010-\u2015]/g, '-') // Replace various dashes with standard hyphen
.replace(/[\u2018\u2019]/g, "'") // Replace smart single quotes
.replace(/[\u201C\u201D]/g, '"') // Replace smart double quotes
.replace(/\u2026/g, '...') // Replace ellipsis
.replace(/[\u2000-\u200B]/g, ' '); // Replace various spaces with standard space
}
function isCompleteJSON(text) {
// Check if JSON is properly closed
let bracketCount = 0;
let braceCount = 0;
let inString = false;
let escaped = false;
for (let i = 0; i < text.length; i++) {
const char = text[i];
if (escaped) {
escaped = false;
continue;
}
if (char === '\\') {
escaped = true;
continue;
}
if (char === '"' && !escaped) {
inString = !inString;
continue;
}
if (!inString) {
if (char === '[') bracketCount++;
if (char === ']') bracketCount--;
if (char === '{') braceCount++;
if (char === '}') braceCount--;
}
}
return bracketCount === 0 && braceCount === 0 && !inString;
}
async function withRetry(fn, batchNumber, maxAttempts = 3) {
const delays = [1000, 2000, 4000];
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
return await fn();
} catch (err) {
if (attempt === maxAttempts || shouldStop) throw err;
document.getElementById('progressText').textContent =
`Retrying batch ${batchNumber} (attempt ${attempt + 1}/${maxAttempts})...`;
await new Promise(resolve => setTimeout(resolve, delays[attempt - 1]));
}
}
}
async function generateBatch(topic, batchSize, batchNumber) {
const prompt = `Generate exactly ${batchSize} question and answer pairs about "${topic}".
Make the questions diverse, covering different aspects and difficulty levels. Each answer should be comprehensive and informative.
IMPORTANT:
- Use only standard ASCII characters for punctuation (regular hyphens, quotes, etc.)
- Keep answers concise enough to fit within token limits
- Format your response as ONLY a JSON array with no additional text before or after
Format your response as a JSON array like this:
[
{"question": "Question text here?", "answer": "Answer text here."},
{"question": "Another question?", "answer": "Another answer."}
]
Generate exactly ${batchSize} pairs. Make them unique and avoid repetition with previous batches (this is batch ${batchNumber}).`;
const response = await callLLM(prompt);
try {
// Sanitize the response to replace special Unicode characters
const sanitized = sanitizeText(response);
// Extract JSON array from response
const jsonMatch = sanitized.match(/\[[\s\S]*\]/);
if (!jsonMatch) {
throw new Error('No JSON array found in response');
}
const jsonString = jsonMatch[0];
// Check if JSON is complete before parsing
if (!isCompleteJSON(jsonString)) {
throw new Error('Incomplete JSON detected - response may have been truncated. Try reducing batch size or simplifying the topic.');
}
const pairs = JSON.parse(jsonString);
if (!Array.isArray(pairs)) {
throw new Error('Response is not an array');
}
const validPairs = pairs.filter(pair =>
pair.question && pair.answer &&
typeof pair.question === 'string' &&
typeof pair.answer === 'string' &&
pair.question.trim().length > 0 &&
pair.answer.trim().length > 0
);
if (validPairs.length === 0) {
throw new Error('No valid Q&A pairs found in response');
}
return validPairs;
} catch (e) {
console.error('Failed to parse LLM response:', response);
throw new Error('Failed to parse Q&A pairs from LLM response: ' + e.message);
}
}
async function startGeneration() {
const topic = document.getElementById('topic').value.trim();
const numPairs = parseInt(document.getElementById('numPairs').value);
const batchSize = parseInt(document.getElementById('batchSize').value);
const concurrency = Math.min(Math.max(parseInt(document.getElementById('concurrency').value) || 3, 1), 10);
const apiKey = document.getElementById('apiKey').value.trim();
if (!topic) { showError('Please enter a topic'); return; }
if (!apiKey) { showError('Please enter an API key'); return; }
if (numPairs < 1) { showError('Number of pairs must be at least 1'); return; }