Repository navigation
Expand file tree
/
Copy pathmain.js
More file actions
2029 lines (1815 loc) · 58.9 KB
/
Copy pathmain.js
File metadata and controls
2029 lines (1815 loc) · 58.9 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
/**
* CategoryDiffusion — Wikimedia Commons user script
*
* Helps editors diffuse overfull categories by suggesting appropriate
* subcategories for each file, using an LLM via a Cloudflare Worker proxy.
*
* All Commons API work (tree crawl, file metadata) runs in the browser.
* Only LLM calls go through the external Worker.
*
* Install: add the following to your common.js on Commons:
* importScript('User:Alaexis/Diffusor.js');
*/
( function () {
'use strict';
// -----------------------------------------------------------------------
// Configuration
// -----------------------------------------------------------------------
var CONFIG = {
// URL of your Cloudflare Worker that proxies LLM requests
llmProxyUrl: 'https://publicai-proxy.alaexis.workers.dev/hf',
llmModel: 'openai/gpt-oss-20b',
// gpt-oss is a reasoning model: reasoning tokens count against
// max_tokens, and at the default effort it often loops over the long
// category list until the budget runs out, returning no JSON at all.
llmMaxTokens: 8192,
llmReasoningEffort: 'low',
llmTemperature: 0.1,
// Subcategory tree crawl limits
maxTreeDepth: 5,
maxTreeNodes: 2000,
// LLM batching
filesPerBatch: 20,
maxFilesPerCategory: 500,
// UI
panelWidth: '420px',
localStoragePrefix: 'catdiffusion-'
};
// Allow user overrides
if ( window.CategoryDiffusionConfig ) {
$.extend( CONFIG, window.CategoryDiffusionConfig );
}
// -----------------------------------------------------------------------
// State
// -----------------------------------------------------------------------
var state = {
categoryTitle: mw.config.get( 'wgPageName' ),
analysisStatus: 'idle', // idle | running | done | error
suggestions: {}, // { "File:Foo.jpg": ["Cat1","Cat2"], ... }
reviewedFiles: {}, // { "File:Foo.jpg": true, ... }
currentFile: null, // file title currently shown in panel
subcategories: [], // flat list of subcategory titles (without "Category:")
fileMetadata: {}, // { "File:Foo.jpg": { description, categories }, ... }
customCategories: [], // categories the user added by hand, offered for every file
failedBatches: 0, // LLM batches that returned no usable JSON
totalBatches: 0
};
// -----------------------------------------------------------------------
// CSS
// -----------------------------------------------------------------------
function injectStyles() {
var css = [
/* Per-thumbnail suggest buttons */
'.catdiff-suggest-btn {',
' display: inline-block;',
' margin-top: 4px;',
' padding: 2px 8px;',
' font-size: 11px;',
' background: #36c;',
' color: #fff;',
' border: none;',
' border-radius: 3px;',
' cursor: pointer;',
'}',
'.catdiff-suggest-btn:hover { background: #2a4b8d; }',
'.catdiff-suggest-btn:disabled {',
' background: #aaa;',
' cursor: not-allowed;',
'}',
'.catdiff-suggest-btn.catdiff-reviewed {',
' background: #72777d;',
'}',
'.catdiff-suggest-btn.catdiff-reviewed::after {',
' content: " \\2713";',
'}',
'.catdiff-suggest-btn.catdiff-has-suggestions {',
' background: #14866d;',
'}',
/* Gallery item reviewed overlay */
'.catdiff-gallery-reviewed {',
' opacity: 0.55;',
'}',
/* Right-side panel */
'#catdiff-panel {',
' display: none;',
' position: fixed;',
' top: 0;',
' right: 0;',
' width: ' + CONFIG.panelWidth + ';',
' height: 100vh;',
' background: #fff;',
' border-left: 2px solid #a2a9b1;',
' box-shadow: -3px 0 12px rgba(0,0,0,0.15);',
' z-index: 10000;',
' overflow-y: auto;',
' padding: 16px;',
' box-sizing: border-box;',
' font-size: 13px;',
'}',
'#catdiff-panel.catdiff-panel-open {',
' display: block;',
'}',
/* Panel header */
'#catdiff-panel-close {',
' float: right;',
' background: none;',
' border: none;',
' font-size: 20px;',
' cursor: pointer;',
' color: #555;',
' line-height: 1;',
'}',
'#catdiff-panel-close:hover { color: #d33; }',
'#catdiff-panel h3 {',
' margin: 0 0 12px 0;',
' font-size: 15px;',
' border-bottom: 1px solid #c8ccd1;',
' padding-bottom: 8px;',
'}',
/* Panel thumbnail */
'#catdiff-panel-thumb {',
' max-width: 100%;',
' max-height: 200px;',
' display: block;',
' margin: 8px auto;',
' border: 1px solid #c8ccd1;',
'}',
/* Panel sections */
'.catdiff-section {',
' margin: 12px 0;',
'}',
'.catdiff-section-title {',
' font-weight: bold;',
' margin-bottom: 4px;',
' color: #222;',
'}',
/* Description */
'#catdiff-description {',
' max-height: 120px;',
' overflow-y: auto;',
' background: #f8f9fa;',
' padding: 6px 8px;',
' border-radius: 3px;',
' font-size: 12px;',
' white-space: pre-wrap;',
' word-break: break-word;',
'}',
/* Current categories list */
'#catdiff-current-cats {',
' list-style: none;',
' padding: 0;',
' margin: 4px 0;',
'}',
'#catdiff-current-cats li {',
' padding: 2px 0;',
' color: #555;',
' font-size: 12px;',
'}',
'#catdiff-current-cats li::before {',
' content: "\\2022 ";',
' color: #999;',
'}',
/* Suggested categories checkboxes */
'#catdiff-suggestions-list {',
' list-style: none;',
' padding: 0;',
' margin: 4px 0;',
'}',
'#catdiff-suggestions-list li {',
' padding: 3px 0;',
'}',
'#catdiff-suggestions-list label {',
' cursor: pointer;',
'}',
'#catdiff-suggestions-list label.catdiff-already-present,',
'#catdiff-custom-list label.catdiff-already-present {',
' color: #999;',
' text-decoration: line-through;',
'}',
/* User-added categories */
'#catdiff-custom-list {',
' list-style: none;',
' padding: 0;',
' margin: 4px 0;',
'}',
'#catdiff-custom-list li {',
' padding: 3px 0;',
'}',
'#catdiff-custom-list label {',
' cursor: pointer;',
'}',
'#catdiff-custom-list li.catdiff-custom-hint {',
' font-size: 11px;',
' color: #72777d;',
'}',
'.catdiff-custom-remove {',
' background: none;',
' border: none;',
' color: #999;',
' cursor: pointer;',
' font-size: 14px;',
' padding: 0 4px;',
'}',
'.catdiff-custom-remove:hover { color: #d33; }',
'#catdiff-custom-form {',
' display: flex;',
' gap: 6px;',
' margin-top: 6px;',
'}',
'#catdiff-custom-input {',
' flex: 1;',
' min-width: 0;',
' padding: 4px 6px;',
' font-size: 13px;',
' border: 1px solid #a2a9b1;',
' border-radius: 3px;',
'}',
'#catdiff-custom-add {',
' padding: 4px 12px;',
' background: #fff;',
' color: #36c;',
' font-weight: bold;',
' border: 1px solid #36c;',
' border-radius: 3px;',
' cursor: pointer;',
' font-size: 13px;',
'}',
'#catdiff-custom-add:hover { background: #eaf3ff; }',
'#catdiff-custom-add:disabled {',
' color: #72777d;',
' border-color: #c8ccd1;',
' background: #fff;',
' cursor: default;',
'}',
'#catdiff-custom-status {',
' font-size: 11px;',
' color: #72777d;',
' margin-top: 4px;',
'}',
'#catdiff-custom-status.catdiff-error {',
' color: #d33;',
'}',
/* Suggestion count */
'#catdiff-suggestion-count {',
' font-size: 11px;',
' color: #72777d;',
' margin-top: 4px;',
'}',
/* Panel action buttons */
'.catdiff-actions {',
' margin-top: 16px;',
' display: flex;',
' gap: 8px;',
'}',
'.catdiff-btn-accept {',
' flex: 1;',
' padding: 8px;',
' background: #14866d;',
' color: #fff;',
' font-weight: bold;',
' border: none;',
' border-radius: 4px;',
' cursor: pointer;',
' font-size: 13px;',
'}',
'.catdiff-btn-accept:hover { background: #0d6b56; }',
'.catdiff-btn-accept:disabled, .catdiff-btn-accept:disabled:hover {',
' background: #c8ccd1;',
' color: #72777d;',
' cursor: default;',
'}',
'.catdiff-btn-reject {',
' flex: 1;',
' padding: 8px;',
' background: #fff;',
' color: #555;',
' font-weight: bold;',
' border: 1px solid #a2a9b1;',
' border-radius: 4px;',
' cursor: pointer;',
' font-size: 13px;',
'}',
'.catdiff-btn-reject:hover { background: #f0f0f0; }',
'.catdiff-btn-review {',
' flex: 1;',
' padding: 8px;',
' background: #fff;',
' color: #36c;',
' font-weight: bold;',
' border: 1px solid #36c;',
' border-radius: 4px;',
' cursor: pointer;',
' font-size: 13px;',
'}',
'.catdiff-btn-review:hover { background: #eaf3ff; }',
/* Loading spinner */
'.catdiff-loading {',
' text-align: center;',
' padding: 24px;',
' color: #72777d;',
'}',
/* Progress status */
'#catdiff-progress-status {',
' margin: 8px 0;',
' line-height: 1.5;',
' color: #222;',
'}',
'#catdiff-progress-stages {',
' margin-top: 12px;',
'}',
/* Push content left when panel is open */
'body.catdiff-panel-active #mw-content-text {',
' margin-right: ' + CONFIG.panelWidth + ';',
'}'
].join( '\n' );
$( '<style>' ).text( css ).appendTo( 'head' );
}
// -----------------------------------------------------------------------
// LocalStorage helpers
// -----------------------------------------------------------------------
function getStorageKey( suffix ) {
return CONFIG.localStoragePrefix + state.categoryTitle + '-' + suffix;
}
function loadReviewedState() {
try {
var raw = localStorage.getItem( getStorageKey( 'reviewed' ) );
if ( raw ) {
state.reviewedFiles = JSON.parse( raw );
}
} catch ( e ) {
state.reviewedFiles = {};
}
}
function saveReviewedState() {
try {
localStorage.setItem(
getStorageKey( 'reviewed' ),
JSON.stringify( state.reviewedFiles )
);
} catch ( e ) {
// localStorage may be full or unavailable
}
}
function loadCachedSuggestions() {
try {
var raw = localStorage.getItem( getStorageKey( 'suggestions' ) );
if ( raw ) {
var parsed = JSON.parse( raw );
state.suggestions = parsed.suggestions || {};
state.subcategories = parsed.subcategories || [];
state.fileMetadata = parsed.fileMetadata || {};
state.analysisStatus = 'done';
return true;
}
} catch ( e ) {
// ignore
}
return false;
}
function saveCachedSuggestions() {
try {
localStorage.setItem(
getStorageKey( 'suggestions' ),
JSON.stringify( {
suggestions: state.suggestions,
subcategories: state.subcategories,
fileMetadata: state.fileMetadata
} )
);
} catch ( e ) {
// ignore
}
}
function loadCustomCategories() {
try {
var raw = localStorage.getItem( getStorageKey( 'custom' ) );
if ( raw ) {
state.customCategories = JSON.parse( raw ) || [];
}
} catch ( e ) {
state.customCategories = [];
}
}
function saveCustomCategories() {
try {
localStorage.setItem(
getStorageKey( 'custom' ),
JSON.stringify( state.customCategories )
);
} catch ( e ) {
// ignore
}
}
// -----------------------------------------------------------------------
// Commons API: subcategory tree crawl
// -----------------------------------------------------------------------
function fetchDirectSubcategories( categoryTitle ) {
var api = new mw.Api();
var allSubcats = [];
function fetchPage( cmcontinue ) {
var params = {
action: 'query',
list: 'categorymembers',
cmtitle: categoryTitle,
cmtype: 'subcat',
cmlimit: 500,
format: 'json'
};
if ( cmcontinue ) {
params.cmcontinue = cmcontinue;
}
return api.get( params ).then( function ( data ) {
var members = data.query.categorymembers || [];
var i, len;
for ( i = 0, len = members.length; i < len; i++ ) {
allSubcats.push( members[ i ].title );
}
if ( data[ 'continue' ] && data[ 'continue' ].cmcontinue ) {
return fetchPage( data[ 'continue' ].cmcontinue );
}
return allSubcats;
} );
}
return fetchPage( null );
}
function crawlSubcategoryTree() {
var deferred = $.Deferred();
var allSeen = {};
var currentLevel = [ state.categoryTitle ];
var depth = 0;
function processLevel() {
depth++;
if ( depth > CONFIG.maxTreeDepth || currentLevel.length === 0 ) {
var result = Object.keys( allSeen );
result.sort();
deferred.resolve( result );
return;
}
var nextLevel = [];
var idx = 0;
var total = currentLevel.length;
function processNext() {
if ( idx >= total ) {
currentLevel = nextLevel;
updateStatus(
'Depth ' + depth + ' done: ' +
Object.keys( allSeen ).length + ' subcategories found…'
);
processLevel();
return;
}
var cat = currentLevel[ idx ];
idx++;
updateStatus(
'Depth ' + depth + ': expanding ' + idx + '/' + total +
' (' + Object.keys( allSeen ).length + ' subcats so far)…'
);
fetchDirectSubcategories( cat ).then( function ( subcats ) {
var i, len, s;
for ( i = 0, len = subcats.length; i < len; i++ ) {
s = subcats[ i ];
if ( !allSeen[ s ] && s !== state.categoryTitle ) {
allSeen[ s ] = true;
nextLevel.push( s );
if ( Object.keys( allSeen ).length >= CONFIG.maxTreeNodes ) {
currentLevel = [];
var result = Object.keys( allSeen );
result.sort();
deferred.resolve( result );
return;
}
}
}
processNext();
}, function ( err ) {
// Skip failures, continue
mw.log.warn( 'CategoryDiffusion: failed to expand ' + cat, err );
processNext();
} );
}
processNext();
}
processLevel();
return deferred.promise();
}
// -----------------------------------------------------------------------
// Commons API: file listing + metadata
// -----------------------------------------------------------------------
function fetchCategoryFiles() {
var api = new mw.Api();
var allFiles = [];
function fetchPage( cmcontinue ) {
var params = {
action: 'query',
list: 'categorymembers',
cmtitle: state.categoryTitle,
cmtype: 'file',
cmlimit: 500,
format: 'json'
};
if ( cmcontinue ) {
params.cmcontinue = cmcontinue;
}
return api.get( params ).then( function ( data ) {
var members = data.query.categorymembers || [];
var i, len;
for ( i = 0, len = members.length; i < len; i++ ) {
allFiles.push( members[ i ].title );
}
if ( allFiles.length >= CONFIG.maxFilesPerCategory ) {
allFiles = allFiles.slice( 0, CONFIG.maxFilesPerCategory );
return allFiles;
}
if ( data[ 'continue' ] && data[ 'continue' ].cmcontinue ) {
return fetchPage( data[ 'continue' ].cmcontinue );
}
return allFiles;
} );
}
return fetchPage( null );
}
function fetchFileDescriptions( fileTitles ) {
var api = new mw.Api();
var result = {};
var chunks = [];
var i;
// Split into chunks of 50 (MediaWiki API limit)
for ( i = 0; i < fileTitles.length; i += 50 ) {
chunks.push( fileTitles.slice( i, i + 50 ) );
}
var chunkIdx = 0;
function processChunk() {
if ( chunkIdx >= chunks.length ) {
return $.Deferred().resolve( result ).promise();
}
var chunk = chunks[ chunkIdx ];
chunkIdx++;
updateStatus(
'Fetching file metadata: batch ' + chunkIdx + '/' + chunks.length + '…'
);
return api.post( {
action: 'query',
titles: chunk.join( '|' ),
prop: 'revisions|categories',
rvprop: 'content',
rvslots: 'main',
cllimit: 'max',
format: 'json'
} ).then( function ( data ) {
var pages = data.query.pages || {};
var pageId, page, title, wikitext, rev, cats, j, jLen;
for ( pageId in pages ) {
if ( !pages.hasOwnProperty( pageId ) || pageId === '-1' ) {
continue;
}
page = pages[ pageId ];
title = page.title || '';
if ( !title ) {
continue;
}
// Extract wikitext
wikitext = '';
if ( page.revisions && page.revisions[ 0 ] ) {
rev = page.revisions[ 0 ];
if ( rev.slots && rev.slots.main ) {
wikitext = rev.slots.main[ '*' ] || rev.slots.main.content || '';
} else if ( rev[ '*' ] ) {
wikitext = rev[ '*' ];
}
}
// Extract categories
cats = [];
if ( page.categories ) {
for ( j = 0, jLen = page.categories.length; j < jLen; j++ ) {
cats.push( page.categories[ j ].title.replace( /^Category:/, '' ) );
}
}
result[ title ] = {
description: extractDescription( wikitext ),
categories: cats
};
}
return processChunk();
}, function () {
// Skip failed chunk
return processChunk();
} );
}
return processChunk();
}
function extractDescription( wikitext ) {
// Try |description= from the Information template
var match = wikitext.match(
/\|\s*[Dd]escription\s*=\s*([\s\S]*?)(?=\n\s*\||\n\s*\}\})/m
);
if ( match ) {
var desc = match[ 1 ].trim();
desc = desc.replace( /\{\{[^}]*\}\}/g, '' );
desc = desc.replace( /\[\[(?:[^\]|]*\|)?([^\]]*)\]\]/g, '$1' );
desc = desc.replace( /'''?/g, '' );
desc = desc.replace( /\s+/g, ' ' ).trim();
if ( desc ) {
return desc.substring( 0, 500 );
}
}
// Fallback: first meaningful line
var lines = wikitext.split( '\n' );
var i, len, line;
for ( i = 0, len = lines.length; i < len; i++ ) {
line = lines[ i ].trim();
if ( line && !line.match( /^\s*[\[{|!=<]/ ) && line.length > 10 ) {
return line.substring( 0, 300 );
}
}
return '';
}
// -----------------------------------------------------------------------
// LLM: build prompt, call Worker, parse response
// -----------------------------------------------------------------------
function buildLLMPrompt( subcatNames, fileBatch ) {
var catDisplay = state.categoryTitle.replace( /^Category:/, '' );
var subcatList = subcatNames.join( '\n' );
var filesSection = [];
var i, len, f, name, desc, cats;
for ( i = 0, len = fileBatch.length; i < len; i++ ) {
f = fileBatch[ i ];
name = f.title.replace( /^File:/, '' );
desc = f.description || '(no description)';
cats = f.categories.length ? f.categories.join( ', ' ) : '(none)';
filesSection.push(
( i + 1 ) + '. Name: ' + name + '\n' +
' Description: ' + desc + '\n' +
' Current categories: ' + cats
);
}
return 'You are helping categorize Wikimedia Commons files. The category ' +
'"' + catDisplay + '" needs to be diffused — files should be moved to ' +
'more specific subcategories.\n\n' +
'Here are ALL available subcategories (within ' + CONFIG.maxTreeDepth +
' levels of depth):\n' +
subcatList + '\n\n' +
'For each file below, pick 3-5 categories from the above list that ' +
'best fit the file. Only pick categories from the list above. ' +
'If none of the listed categories fit well, return an empty list for that file.\n\n' +
'Output ONLY valid JSON in this exact format, using the file numbers below as keys:\n' +
'{"1": ["Cat1", "Cat2"], "2": ["Cat3"]}\n\n' +
'Files:\n\n' + filesSection.join( '\n\n' );
}
function callLLM( prompt ) {
return $.ajax( {
url: CONFIG.llmProxyUrl,
method: 'POST',
contentType: 'application/json',
data: JSON.stringify( {
model: CONFIG.llmModel,
messages: [ { role: 'user', content: prompt } ],
max_tokens: CONFIG.llmMaxTokens,
reasoning_effort: CONFIG.llmReasoningEffort,
temperature: CONFIG.llmTemperature
} ),
dataType: 'json',
timeout: 120000
} ).then( function ( data ) {
var choice = data.choices && data.choices[ 0 ];
return {
content: choice && choice.message.content || '',
finishReason: choice && choice.finish_reason || ''
};
} );
}
// Returns { "File:Foo.jpg": [cats] } keyed by the real titles in
// batchTitles, or null if the response contains no parseable JSON.
function parseLLMResponse( responseText, validCatsSet, batchTitles ) {
// Extract JSON from response (LLM may include markdown fences)
var jsonMatch = responseText.match( /\{[\s\S]*\}/ );
if ( !jsonMatch ) {
return null;
}
var parsed;
try {
parsed = JSON.parse( jsonMatch[ 0 ] );
} catch ( e ) {
return null;
}
var result = {};
var key, fileTitle, cats, validated, i, len, cat;
for ( key in parsed ) {
if ( !parsed.hasOwnProperty( key ) ) {
continue;
}
cats = parsed[ key ];
if ( !$.isArray( cats ) ) {
continue;
}
// Keys are 1-based file numbers from the prompt. The model mangles
// long filenames when echoing them, so we never key on names.
fileTitle = batchTitles[ parseInt( key, 10 ) - 1 ];
if ( !fileTitle ) {
continue;
}
validated = [];
for ( i = 0, len = cats.length; i < len; i++ ) {
cat = String( cats[ i ] ).trim();
if ( validCatsSet[ cat ] ) {
validated.push( cat );
}
}
result[ fileTitle ] = validated;
}
return result;
}
// -----------------------------------------------------------------------
// Wake Lock: prevent browser from freezing the tab during analysis
// -----------------------------------------------------------------------
var wakeLockSentinel = null;
var wakeLockActive = false;
function acquireWakeLock() {
wakeLockActive = true;
requestWakeLock();
// The Screen Wake Lock is released automatically when the tab becomes
// hidden. Re-acquire it when the tab becomes visible again so the
// analysis can keep running if the user switches away a second time.
document.addEventListener( 'visibilitychange', onVisibilityChange );
}
function requestWakeLock() {
if ( !wakeLockActive || !navigator.wakeLock ) {
return;
}
navigator.wakeLock.request( 'screen' ).then( function ( sentinel ) {
wakeLockSentinel = sentinel;
}, function () {
// Wake Lock denied (e.g. page not visible) – continue without it
} );
}
function onVisibilityChange() {
if ( document.visibilityState === 'visible' && wakeLockActive ) {
requestWakeLock();
}
}
function releaseWakeLock() {
wakeLockActive = false;
document.removeEventListener( 'visibilitychange', onVisibilityChange );
if ( wakeLockSentinel ) {
wakeLockSentinel.release();
wakeLockSentinel = null;
}
}
// -----------------------------------------------------------------------
// Analysis pipeline (runs entirely in-browser)
// -----------------------------------------------------------------------
function startAnalysis() {
if ( state.analysisStatus === 'running' ) {
return;
}
// Clear previous results so a re-run starts fresh
state.suggestions = {};
state.subcategories = [];
state.fileMetadata = {};
state.failedBatches = 0;
state.totalBatches = 0;
state.analysisStatus = 'running';
// Acquire a Web Lock to prevent the browser from freezing this tab
// while the analysis is running in the background.
acquireWakeLock();
// Now that the analysis has been started explicitly by the user,
// (re)inject per-thumbnail buttons so they appear only after the
// script has been run at least once.
injectThumbnailButtons();
updateThumbnailButtons();
// Step 1: Crawl subcategory tree
updateStatus( 'Crawling subcategory tree…' );
crawlSubcategoryTree().then( function ( subcatTitles ) {
if ( subcatTitles.length === 0 ) {
state.analysisStatus = 'done';
state.suggestions = {};
releaseWakeLock();
updateStatus( 'No subcategories found.' );
updatePanelProgress( 'No subcategories found.' );
return;
}
// Strip "Category:" prefix for display and LLM prompt
var subcatNames = [];
var i, len;
for ( i = 0, len = subcatTitles.length; i < len; i++ ) {
subcatNames.push( subcatTitles[ i ].replace( /^Category:/, '' ) );
}
state.subcategories = subcatNames;
updateStatus(
'Found ' + subcatNames.length + ' subcategories. Fetching files…'
);
// Step 2: Fetch files
return fetchCategoryFiles().then( function ( fileTitles ) {
if ( fileTitles.length === 0 ) {
state.analysisStatus = 'done';
state.suggestions = {};
saveCachedSuggestions();
releaseWakeLock();
updateStatus( 'No files found in category.' );
updatePanelProgress( 'No files found in category.' );
return;
}
updateStatus(
'Fetching metadata for ' + fileTitles.length + ' files…'
);
// Step 3: Fetch file metadata
return fetchFileDescriptions( fileTitles ).then( function ( metadata ) {
state.fileMetadata = metadata;
// Step 4: Batch LLM calls
return runLLMBatches( subcatNames, metadata );
} );
} );
} ).fail( function ( err ) {
state.analysisStatus = 'error';
releaseWakeLock();
var errorMsg = 'Error: ' + ( err && err.message || err || 'Analysis failed.' );
updateStatus( errorMsg );
updatePanelProgress( errorMsg );
} );
}
function runLLMBatches( subcatNames, metadata ) {
var fileTitles = Object.keys( metadata );
var totalBatches = Math.ceil( fileTitles.length / CONFIG.filesPerBatch );
var batchIdx = 0;
var allSuggestions = {};
state.failedBatches = 0;
state.totalBatches = totalBatches;
// Build valid category set for validation
var validCatsSet = {};
var i, len;
for ( i = 0, len = subcatNames.length; i < len; i++ ) {
validCatsSet[ subcatNames[ i ] ] = true;
}
function processBatch() {
if ( batchIdx >= totalBatches ) {
// All batches done
state.suggestions = allSuggestions;
for ( i = 0, len = fileTitles.length; i < len; i++ ) {
allSuggestions[ fileTitles[ i ] ] = addExistingSubcategories(
allSuggestions[ fileTitles[ i ] ] || [],
( metadata[ fileTitles[ i ] ] || {} ).categories || [],
validCatsSet
);
}
state.analysisStatus = 'done';
saveCachedSuggestions();
releaseWakeLock();
updateThumbnailButtons();
updatePanelProgress();
return $.Deferred().resolve().promise();
}
var start = batchIdx * CONFIG.filesPerBatch;
var end = Math.min( start + CONFIG.filesPerBatch, fileTitles.length );
var batchTitles = fileTitles.slice( start, end );
batchIdx++;
updateStatus(
'LLM batch ' + batchIdx + '/' + totalBatches +
' (' + batchTitles.length + ' files)…'
);
// Build batch for prompt
var fileBatch = [];
var j, title, meta;
for ( j = 0; j < batchTitles.length; j++ ) {
title = batchTitles[ j ];
meta = metadata[ title ] || {};
fileBatch.push( {
title: title,
description: meta.description || '',
categories: meta.categories || []
} );
}
var prompt = buildLLMPrompt( subcatNames, fileBatch );
return callLLM( prompt ).then( function ( response ) {
var batchResult = parseLLMResponse(
response.content, validCatsSet, batchTitles
);
if ( batchResult ) {
$.extend( allSuggestions, batchResult );
} else {
state.failedBatches++;
mw.log.warn(
'CategoryDiffusion: LLM batch ' + batchIdx + ' returned no usable JSON' +
' (finish_reason: ' + ( response.finishReason || 'unknown' ) + ').' +
' Raw response:', response.content
);
}
return processBatch();
}, function ( err ) {
state.failedBatches++;
mw.log.warn( 'CategoryDiffusion: LLM batch ' + batchIdx + ' failed', err );
// Continue with next batch
return processBatch();
} );
}