forked from ZeldaFan0225/ai_horde
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
1688 lines (1529 loc) · 58.8 KB
/
index.ts
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
import SuperMap from "@thunder04/supermap"
import Centra from "centra"
import { IncomingMessage } from "http"
/*
* https://github.com/db0/AI-Horde/blob/main/CHANGELOG.md
*/
enum ModelGenerationInputStableSamplers {
"k_lms" = "k_lms",
"k_heun" = "k_heun",
"k_euler" = "k_euler",
"k_dpm_2" = "k_dpm_2",
"k_dpm_2_a" = "k_dpm_2_a",
"DDIM" = "DDIM",
"PLMS" = "PLMS",
"k_dpm_fast" = "k_dpm_fast",
"k_dpm_adaptive" = "k_dpm_adaptive",
"k_dpmpp_2s_a" = "k_dpmpp_2s_a",
"k_dpmpp_2m" = "k_dpmpp_2m",
"dpmsolver" = "dpmsolver"
}
enum SourceImageProcessingTypes {
"img2img" = "img2img",
"inpainting" = "inpainting",
"outpainting" = "outpainting"
}
enum ModelGenerationInputPostProcessingTypes {
"GFPGAN" = "GFPGAN",
"RealESRGAN_x4plus" = "RealESRGAN_x4plus"
}
class StableHordeError extends Error {
rawError: RequestError;
status: number;
method: string;
url: string;
requestBody: any;
constructor(rawError: RequestError, core_res: IncomingMessage, requestBody?: any) {
super()
this.rawError = rawError
this.status = core_res.statusCode ?? 0
this.method = core_res.method ?? "GET"
this.url = core_res.url ?? ""
this.requestBody = requestBody
}
get name() {
return this.rawError.message
}
}
class StableHorde {
static readonly ModelGenerationInputStableSamplers = ModelGenerationInputStableSamplers;
readonly ModelGenerationInputStableSamplers = StableHorde.ModelGenerationInputStableSamplers;
static readonly SourceImageProcessingTypes = SourceImageProcessingTypes;
readonly SourceImageProcessingTypes = StableHorde.SourceImageProcessingTypes;
static readonly ModelGenerationInputPostProcessingTypes = ModelGenerationInputPostProcessingTypes;
readonly ModelGenerationInputPostProcessingTypes = StableHorde.ModelGenerationInputPostProcessingTypes;
static readonly StableHordeError = StableHordeError;
readonly StableHordeError = StableHorde.StableHordeError;
#default_token?: string
#cache_config: StableHordeCacheConfiguration
#cache: StableHordeCache
#api_route: string
constructor(options?: StableHordeInitOptions) {
this.#default_token = options?.default_token
this.#cache_config = {
users: options?.cache?.users ?? 0,
generations_check: options?.cache?.generations_check ?? 0,
generations_status: options?.cache?.generations_status ?? 0,
models: options?.cache?.models ?? 0,
modes: options?.cache?.modes ?? 0,
news: options?.cache?.news ?? 0,
performance: options?.cache?.performance ?? 0,
workers: options?.cache?.workers ?? 0,
teams: options?.cache?.teams ?? 0
}
if(Object.values(this.#cache_config).some(v => !Number.isSafeInteger(v) || v < 0)) throw new TypeError("Every cache duration must be a positive safe integer")
this.#cache = {
users: this.#cache_config.users ? new SuperMap({intervalTime: options?.cache_interval ?? 1000, expireAfter: this.#cache_config.users}) : undefined,
generations_check: this.#cache_config.generations_check ? new SuperMap({intervalTime: options?.cache_interval ?? 1000, expireAfter: this.#cache_config.generations_check}) : undefined,
generations_status: this.#cache_config.generations_status ? new SuperMap({intervalTime: options?.cache_interval ?? 1000, expireAfter: this.#cache_config.generations_status}) : undefined,
models: this.#cache_config.models ? new SuperMap({intervalTime: options?.cache_interval ?? 1000, expireAfter: this.#cache_config.models}) : undefined,
modes: this.#cache_config.modes ? new SuperMap({intervalTime: options?.cache_interval ?? 1000, expireAfter: this.#cache_config.modes}) : undefined,
news: this.#cache_config.news ? new SuperMap({intervalTime: options?.cache_interval ?? 1000, expireAfter: this.#cache_config.news}) : undefined,
performance: this.#cache_config.performance ? new SuperMap({intervalTime: options?.cache_interval ?? 1000, expireAfter: this.#cache_config.performance}) : undefined,
workers: this.#cache_config.workers ? new SuperMap({intervalTime: options?.cache_interval ?? 1000, expireAfter: this.#cache_config.workers}) : undefined,
teams: this.#cache_config.teams ? new SuperMap({intervalTime: options?.cache_interval ?? 1000, expireAfter: this.#cache_config.teams}) : undefined,
}
this.#api_route = options?.api_route ?? "https://stablehorde.net/api/v2"
}
/* GENERAL */
#getToken(token?: string): string {
return token || this.#default_token || "0000000000"
}
clearCache() {
Object.values(this.#cache).forEach(m => m.clear())
}
get cache() {
return this.#cache
}
/* GET REQUESTS */
/**
* Lookup user details based on their API key.
* This can be used to verify a user exists
* @param token - The token of the user; If none given the default from the contructor is used
* @returns UserDetailsStable - The user data of the requested user
*/
async findUser(options?: {token?: string}): Promise<UserDetailsStable> {
const t = this.#getToken(options?.token)
const res = await Centra(`${this.#api_route}/find_user`, "GET")
.header("apikey", t)
.send()
if(res.statusCode === 404) throw new this.StableHordeError(await res.json().then(res => res), res.coreRes)
const data = await res.json() as UserDetailsStable
if(this.#cache_config.users) this.#cache.users?.set(data.id!, data)
return data
}
/**
* Details and statistics about a specific user
* @param id - The user ids to get
* @param options.token - The token of the requesting user; Has to be Moderator, Admin or Reuqested users token
* @param options.force - Set to true to skip cache
* @returns UserDetailsStable - The user data of the requested user
*/
async getUserDetails(id: number, options?: {token?: string, force?: boolean}): Promise<UserDetailsStable> {
const t = this.#getToken(options?.token)
const temp = !options?.force && this.#cache.users?.get(id)
if(temp) return temp
const res = await Centra(`${this.#api_route}/users/${id}`, "GET")
.header("apikey", t)
.send()
if(res.statusCode === 404) throw new this.StableHordeError(await res.json().then(res => res), res.coreRes)
const data = await res.json() as UserDetailsStable
if(this.#cache_config.users) this.#cache.users?.set(data.id!, data)
return data
}
/**
* Details of a worker Team
* @param id - The teams id to get
* @param options.token - The token of the requesting user
* @param options.force - Set to true to skip cache
* @returns TeamDetailsStable - The team data
*/
async getTeam(id: string, options?: {token?: string, force?: boolean}): Promise<TeamDetailsStable> {
const t = this.#getToken(options?.token)
const temp = !options?.force && this.#cache.teams?.get(id)
if(temp) return temp
const res = await Centra(`${this.#api_route}/teams/${id}`, "GET")
.header("apikey", t)
.send()
switch(res.statusCode) {
case 401:
case 403:
case 404:
{
throw new this.StableHordeError(await res.json().then(res => res), res.coreRes)
}
}
const data = await res.json() as TeamDetailsStable
if(this.#cache_config.teams) this.#cache.teams?.set(data.id!, data)
return data
}
/**
* Details of a registered worker.
* This can be used to verify a user exists
* @param id - The id of the worker
* @param options.fields - Array of fields that will be included in the worker object
* @param options.token - Moderator or API key of workers owner (gives more information if requesting user is owner or moderator)
* @param options.force - Set to true to skip cache
* @returns worker details for the requested worker
*/
async getWorkerDetails<
T extends keyof WorkerDetailsStable
>(id: string, options?: {token?: string, force?: boolean, fields?: T[]}): Promise<Pick<WorkerDetailsStable, T>> {
const fields_string = options?.fields?.length ? options.fields.join(',') : ''
const t = this.#getToken(options?.token)
const temp = !options?.force && this.#cache.workers?.get(id + fields_string)
if(temp) return temp as Pick<WorkerDetailsStable, T>
const req = Centra(`${this.#api_route}/workers/${id}`, "GET")
.header("apikey", t)
if(fields_string) req.header('X-Fields', fields_string)
const res = await req.send()
switch(res.statusCode) {
case 401:
case 403:
case 404:
{
throw new this.StableHordeError(await res.json().then(res => res), res.coreRes)
}
}
const data = await res.json() as Pick<WorkerDetailsStable, T>
if(this.#cache_config.workers) {
const data_with_id = data as Pick<WorkerDetailsStable, 'id'>
if('id' in data_with_id) this.#cache.workers?.set(data_with_id.id + fields_string, data)
}
return data
}
/**
* Retrieve the status of an Asynchronous generation request without images
* Use this method to check the status of a currently running asynchronous request without consuming bandwidth.
* @param id - The id of the generation
* @param options.force - Set to true to skip cache
* @returns RequestStatusCheck - The Check data of the Generation
*/
async getGenerationCheck(id: string, options?: {force?: boolean}): Promise<RequestStatusCheck> {
const temp = !options?.force && this.#cache.generations_check?.get(id)
if(temp) return temp
const res = await Centra(`${this.#api_route}/generate/check/${id}`, "GET")
.send()
if(res.statusCode === 404) throw new this.StableHordeError(await res.json().then(res => res), res.coreRes)
const data = await res.json() as RequestStatusCheck
if(this.#cache_config.generations_check) this.#cache.generations_check?.set(id, data)
return data
}
/**
* Retrieve the full status of an Asynchronous generation request
* This method will include all already generated images in base64 encoded .webp files.
* As such, you are requested to not retrieve this data often. Instead use the getGenerationCheck method first
* This method is limited to 1 request per minute
* @param id - The id of the generation
* @param options.force - Set to true to skip cache
* @returns RequestStatusStable - The Status of the Generation
*/
async getGenerationStatus(id: string, options?: {force?: boolean}): Promise<RequestStatusStable> {
const temp = !options?.force && this.#cache.generations_status?.get(id)
if(temp) return temp
const res = await Centra(`${this.#api_route}/generate/status/${id}`, "GET")
.send()
if(res.statusCode === 404) throw new this.StableHordeError(await res.json().then(res => res), res.coreRes)
const data = await res.json() as RequestStatusStable
if(this.#cache_config.generations_status) this.#cache.generations_status?.set(id, data)
return data
}
/**
* Returns a list of models active currently in this horde
* @param options.force - Set to true to skip cache
* @returns ActiveModel[] - Array of Active Models
*/
async getModels(options?: {force?: boolean}): Promise<ActiveModel[]> {
const temp = !options?.force && this.#cache.models?.get("CACHE-MODELS")
if(temp) return temp
const res = await Centra(`${this.#api_route}/status/models`, "GET")
.send()
const data = await res.json() as ActiveModel[]
if(this.#cache_config.models) this.#cache.models?.set("CACHE-MODELS", data)
return data
}
/**
* Horde Maintenance Mode Status
* Use this method to quicky determine if this horde is in maintenance, invite_only or raid mode
* @param options.token - Requires Admin or Owner API key
* @param options.force - Set to true to skip cache
* @returns HordeModes - The current modes of the horde
*/
async getModes(options?: {token?: string, force?: boolean}): Promise<HordeModes> {
const t = this.#getToken(options?.token)
const temp = !options?.force && this.#cache.modes?.get("CACHE-MODES")
if(temp) return temp
if(this.#cache_config.modes && this.#cache.modes?.has("CACHE-MODES")) return this.#cache.modes?.get("CACHE-MODES")!
const res = await Centra(`${this.#api_route}/status/modes`, "GET")
.header("apikey", t)
.send()
const data = await res.json() as HordeModes
if(this.#cache_config.modes) this.#cache.modes?.set("CACHE-MODES", data)
return data
}
/**
* Read the latest happenings on the horde
* @param options.force - Set to true to skip cache
* @returns Newspiece[] - Array of all news articles
*/
async getNews(options?: {force?: boolean}): Promise<Newspiece[]> {
const temp = !options?.force && this.#cache.news?.get("CACHE-NEWS")
if(temp) return temp
const res = await Centra(`${this.#api_route}/status/news`, "GET")
.send()
const data = await res.json() as Newspiece[]
if(this.#cache_config.news) this.#cache.news?.set("CACHE-NEWS", data)
return data
}
/**
* Details about the current performance of this Horde
* @param options.force - Set to true to skip cache
* @returns HordePerformanceStable - The hordes current performance
*/
async getPerformance(options?: {force?: boolean}): Promise<HordePerformanceStable> {
const temp = !options?.force && this.#cache.performance?.get("CACHE-PERFORMANCE")
if(temp) return temp
const res = await Centra(`${this.#api_route}/status/performance`, "GET")
.send()
const data = await res.json() as HordePerformanceStable
if(this.#cache_config.performance) this.#cache.performance?.set("CACHE-PERFORMANCE", data)
return data
}
/**
* A List with the details and statistic of all registered users
* @returns UserDetailsStable[] - An array of all users data
*/
async getUsers(): Promise<UserDetailsStable[]> {
const res = await Centra(`${this.#api_route}/users`, "GET")
.send()
const data = await res.json() as UserDetailsStable[]
if(this.#cache_config.users) data.forEach(d => this.#cache.users?.set(d.id!, d))
return data
}
/**
* A List with the details of all registered and active workers
* @param fields - Array of fields that will be included in the worker object
* @returns An array of all workers data
*/
async getWorkers<
T extends keyof WorkerDetailsStable
>(fields?: T[]): Promise<Pick<WorkerDetailsStable, T>[]> {
const fields_string = fields?.length ? fields.join(',') : ''
const req = Centra(`${this.#api_route}/workers`, "GET")
if(fields_string) req.header('X-Fields', fields_string)
const res = await req.send()
const data = await res.json() as Pick<WorkerDetailsStable, T>[]
if(this.#cache_config.workers) data.forEach(d => {
const data_with_id = data as Pick<WorkerDetailsStable, 'id'>
if('id' in data_with_id) this.#cache.workers?.set(data_with_id.id + fields_string, d)
})
return data
}
/**
* Filter workers by performance (and query)
* @param min_pixels - minimal value of max_pixels for worker
* @param filter - (optional) details of the query and filter parameters
* @returns ids of workers to use in the request to generate
*/
async getWorkersByPerformance(min_pixels: number, filter = {} as WorkersPerformanceFilter) {
const fields: (keyof WorkerDetailsStable)[] = [
"id",
"performance",
"max_pixels",
"img2img",
"models"
]
if(!filter.size) filter.size = 5
if(!filter.performance) filter.performance = 1.5
const workers = await this.getWorkers(fields)
const sorted = workers.map(worker => ({
...worker,
p: worker.performance ? parseFloat(worker.performance) : 0
})).filter(worker => {
if(!worker.max_pixels || worker.max_pixels < min_pixels) return
if(filter?.models?.length && worker.models?.length) {
if(!worker.models.some(model => filter.models?.includes(model))) return
}
if(filter.img2img && !worker.img2img) return
return true
}).sort((a, b) => b.p - a.p)
const filtered = sorted.filter(el => el.p > (filter.performance as number))
return (filtered.length >= filter.size ? filtered : sorted.slice(0, filter.size)).map(worker => worker.id!)
}
/**
* A List with the details of all teams
* @returns TeamDetailsStable[] - Array of Team Details
*/
async getTeams(): Promise<TeamDetailsStable[]> {
const res = await Centra(`${this.#api_route}/teams`, "GET")
.send()
const data = await res.json() as TeamDetailsStable[]
if(this.#cache_config.teams) data.forEach(d => this.#cache.teams?.set(d.id!, d))
return data
}
/* POST REQUESTS */
/**
* Initiate an Asynchronous request to generate images
* This method will immediately return with the UUID of the request for generation.
* This method will always be accepted, even if there are no workers available currently to fulfill this request.
* Perhaps some will appear in the next 10 minutes.
* Asynchronous requests live for 10 minutes before being considered stale and being deleted.
* @param generation_data - The data to generate the image
* @param options.token - The token of the requesting user
* @returns RequestAsync - The id and message for the async generation request
*/
async postAsyncGenerate(generation_data: GenerationInput, options?: {token?: string}): Promise<RequestAsync> {
const t = this.#getToken(options?.token)
const res = await Centra(`${this.#api_route}/generate/async`, "POST")
.header("apikey", t)
.body(generation_data, "json")
.send()
switch(res.statusCode) {
case 400:
case 401:
case 429:
case 503:
{
throw new this.StableHordeError(await res.json().then(res => res), res.coreRes, generation_data)
}
}
return await res.json() as RequestAsync
}
/**
* Initiate a Synchronous request to generate images
* This connection will only terminate when the images have been generated, or an error occured.
* If your connection is interrupted, you will not have the request UUID, so you cannot retrieve the images asynchronously.
* @param generation_data - The data to generate the image
* @param options.token - The token of the requesting user
* @returns RequestStatusStable - The result of the generation. This is the same as calling getGenerationStatus after using postAsyncGenerate
*/
async postSyncGenerate(generation_data: GenerationInput, options?: {token?: string}): Promise<RequestStatusStable> {
const t = this.#getToken(options?.token)
const res = await Centra(`${this.#api_route}/generate/sync`, "POST")
.header("apikey", t)
.body(generation_data, "json")
.send()
switch(res.statusCode) {
case 400:
case 401:
case 429:
case 503:
{
throw new this.StableHordeError(await res.json().then(res => res), res.coreRes, generation_data)
}
}
return await res.json() as RequestStatusStable
}
/**
* Check if there are generation requests queued for fulfillment
* This endpoint is used by registered workers only
* @param pop_input
* @param options.token - The token of the registered user
* @returns GenerationPayload
*/
async postGenerationPop(pop_input: PopInputStable, options?: {token?: string}): Promise<GenerationPayload> {
const t = this.#getToken(options?.token)
const res = await Centra(`${this.#api_route}/generate/pop`, "POST")
.header("apikey", t)
.body(pop_input, "json")
.send()
switch(res.statusCode) {
case 401:
case 403:
{
throw new this.StableHordeError(await res.json().then(res => res), res.coreRes, pop_input)
}
}
return await res.json() as GenerationPayload
}
/**
* Submit a generated image
* This endpoint is used by registered workers only
* @param generation_submit
* @param options.token - The workers owner API key
* @returns GenerationSubmitted
*/
async postGenerationSubmit(generation_submit: {id: string, generation: string, seed: string}, options?: {token?: string}): Promise<GenerationSubmitted> {
const t = this.#getToken(options?.token)
const res = await Centra(`${this.#api_route}/generate/submit`, "POST")
.header("apikey", t)
.body(generation_submit, "json")
.send()
switch(res.statusCode) {
case 400:
case 401:
case 402:
case 404:
{
throw new this.StableHordeError(await res.json().then(res => res), res.coreRes, generation_submit)
}
}
return await res.json() as GenerationSubmitted
}
/**
* Transfer Kudos to a registered user
* @param transfer_data - The data specifiying who to send how many kudos
* @param options.token - The sending users API key
* @returns KudosTransferred
*/
async postKudosTransfer(transfer_data: {username: string, amount: number}, options?: {token?: string}): Promise<KudosTransferred> {
const t = this.#getToken(options?.token)
const res = await Centra(`${this.#api_route}/kudos/transfer`, "POST")
.header("apikey", t)
.body(transfer_data, "json")
.send()
switch(res.statusCode) {
case 400:
case 401:
{
throw new this.StableHordeError(await res.json().then(res => res), res.coreRes, transfer_data)
}
}
return await res.json() as KudosTransferred
}
/**
* Create a new team
* Only trusted users can create new teams.
* @param create_payload - The data to create the team with
* @param options.token - The API key of a trusted user
* @returns ModifyTeam
*/
async createTeam(create_payload: CreateTeamInput, options?: {token?: string}): Promise<ModifyTeam> {
const t = this.#getToken(options?.token)
const res = await Centra(`${this.#api_route}/teams`, "POST")
.header("apikey", t)
.body(create_payload, "json")
.send()
switch(res.statusCode) {
case 400:
case 401:
case 403:
{
throw new this.StableHordeError(await res.json().then(res => res), res.coreRes, create_payload)
}
}
return await res.json() as ModifyTeam
}
/** POST */
/**
* Change Horde Modes
* @param modes - The new status of the Horde
* @param options.token - Requires Admin API key
* @returns HordeModes
*/
async putStatusModes(modes: {maintenance: boolean, shutdown: number, invite_only: boolean, raid: boolean}, options?: {token?: string}): Promise<HordeModes> {
const t = this.#getToken(options?.token)
const res = await Centra(`${this.#api_route}/status/modes`, "PUT")
.header("apikey", t)
.body(modes, "json")
.send()
switch(res.statusCode) {
case 401:
case 402:
{
throw new this.StableHordeError(await res.json().then(res => res), res.coreRes, modes)
}
}
return await res.json() as HordeModes
}
/**
* Method for horde admins to perform operations on users
* @param update_payload - The data to change on the target user
* @param id - The targeted users ID
* @param options.token - Requires Admin API key
* @returns ModifyUser
*/
async updateUser(update_payload: ModifyUserInput, id: number, options?: {token?: string}): Promise<ModifyUser> {
const t = this.#getToken(options?.token)
const res = await Centra(`${this.#api_route}/users/${id}`, "PUT")
.header("apikey", t)
.body(update_payload, "json")
.send()
switch(res.statusCode) {
case 400:
case 401:
case 402:
case 404:
{
throw new this.StableHordeError(await res.json().then(res => res), res.coreRes, update_payload)
}
}
if(this.#cache_config.users) this.#cache.users?.delete(id)
return await res.json() as ModifyUser
}
/**
* Put the worker into maintenance or pause mode
* Maintenance can be set by the owner of the serve or an admin.
* When in maintenance, the worker will receive a 503 request when trying to retrieve new requests. Use this to avoid disconnecting your worker in the middle of a generation
* Paused can be set only by the admins of this Horde.
* When in paused mode, the worker will not be given any requests to generate.
* @param update_payload - The data to change on the target worker
* @param id - The targeted workers ID
* @param options.token - The worker owners API key or Admin API key
* @returns ModifyWorker
*/
async updateWorker(update_payload: ModifyWorkerInput, id: string, options?: {token?: string}): Promise<ModifyWorker> {
const t = this.#getToken(options?.token)
const res = await Centra(`${this.#api_route}/workers/${id}`, "PUT")
.header("apikey", t)
.body(update_payload, "json")
.send()
switch(res.statusCode) {
case 400:
case 401:
case 402:
case 404:
{
throw new this.StableHordeError(await res.json().then(res => res), res.coreRes, update_payload)
}
}
if(this.#cache_config.workers) this.#cache.workers?.delete(id)
return await res.json() as ModifyWorker
}
/**
* Updates a Team's information
* @param update_payload - The data to update the team with
* @param options.token - The Moderator or Creator API key
* @returns ModifyTeam
*/
async updateTeam(update_payload: ModifyTeamInput, id: string, options?: {token?: string}): Promise<ModifyTeam> {
const t = this.#getToken(options?.token)
const res = await Centra(`${this.#api_route}/teams/${id}`, "PATCH")
.header("apikey", t)
.body(update_payload, "json")
.send()
switch(res.statusCode) {
case 400:
case 401:
case 403:
case 404:
{
throw new this.StableHordeError(await res.json().then(res => res), res.coreRes, update_payload)
}
}
if(this.#cache_config.teams) this.#cache.teams?.delete(id)
return await res.json() as ModifyTeam
}
/**
* Cancel an unfinished request
* This request will include all already generated images in base64 encoded .webp files.
* @param id - The targeted generations ID
* @returns RequestStatusStable
*/
async deleteGenerationRequest(id: string, options?: {token?: string}): Promise<RequestStatusStable> {
const t = this.#getToken(options?.token)
const res = await Centra(`${this.#api_route}/generate/status/${id}`, "DELETE")
.header("apikey", t)
.send()
switch(res.statusCode) {
case 404:
{
throw new this.StableHordeError(await res.json().then(res => res), res.coreRes)
}
}
const data = await res.json() as RequestStatusStable
if(this.#cache_config.generations_status) this.#cache.generations_status?.set(id, data)
return data
}
/**
* Delete the worker entry
* This will delete the worker and their statistics. Will not affect the kudos generated by that worker for their owner.
* Only the worker's owner and an admin can use this endpoint.
* This action is unrecoverable!
* @param id - The targeted workers ID
* @param options.token - The worker owners API key or a Moderators API key
* @returns DeletedWorker
*/
async deleteWorker(id: string, options?: {token?: string}): Promise<DeletedWorker> {
const t = this.#getToken(options?.token)
const res = await Centra(`${this.#api_route}/workers/${id}`, "DELETE")
.header("apikey", t)
.send()
switch(res.statusCode) {
case 401:
case 402:
case 404:
{
throw new this.StableHordeError(await res.json().then(res => res), res.coreRes)
}
}
const data = await res.json() as DeletedWorker
this.#cache.workers?.delete(id)
return data
}
/**
* Delete the team entry
* Only the team's creator or a horde moderator can use this endpoint.
* This action is unrecoverable!
* @param id - The targeted teams ID
* @param options.token - The worker owners API key or a Moderators API key
* @returns DeletedTeam
*/
async deleteTeam(id: string, options?: {token?: string}): Promise<DeletedTeam> {
const t = this.#getToken(options?.token)
const res = await Centra(`${this.#api_route}/teams/${id}`, "DELETE")
.header("apikey", t)
.send()
switch(res.statusCode) {
case 401:
case 403:
case 404:
{
throw new this.StableHordeError(await res.json().then(res => res), res.coreRes)
}
}
const data = await res.json() as DeletedTeam
this.#cache.teams?.delete(id)
return data
}
/**
* Remove an IP from timeout
* Only usable by horde moderators
* @param ip - The IP address
* @param options.token - Moderators API key
* @returns DeletedTeam
*/
async deleteIPTimeout(delete_payload: DeleteTimeoutIPInput, options?: {token?: string}): Promise<SimpleResponse> {
const t = this.#getToken(options?.token)
const res = await Centra(`${this.#api_route}/operations/ipaddr`, "DELETE")
.header("apikey", t)
.body(delete_payload, "json")
.send()
switch(res.statusCode) {
case 400:
case 401:
case 403:
{
throw new this.StableHordeError(await res.json().then(res => res), res.coreRes, delete_payload)
}
}
const data = await res.json() as SimpleResponse
return data
}
}
// @ts-expect-error
export = StableHorde
/* INTERNAL TYPES */
export interface StableHordeInitOptions {
/** The configuration for caching results */
cache?: StableHordeCacheConfiguration,
/**
* The interval to check expired data in the cache
* @default 1000
*/
cache_interval?: number
/** The default token to use for requests */
default_token?: string,
/** The base api domain + route to use for requests */
api_route?: string
}
export interface StableHordeCacheConfiguration {
/** How long to cache a specific user for in Milliseconds */
users?: number,
/** How long to cache generation check data for in Milliseconds */
generations_check?: number,
/** How long to cache generation status data for in Milliseconds */
generations_status?: number,
/** How long to cache models for in Milliseconds */
models?: number,
/** How long to cache modes for in Milliseconds */
modes?: number,
/** How long to cache news for in Milliseconds */
news?: number,
/** How long to cache performance for in Milliseconds */
performance?: number,
/** How long to cache workers for in Milliseconds */
workers?: number,
/** How long to cache teams for in Milliseconds */
teams?: number,
}
interface StableHordeCache {
users?: SuperMap<number, UserDetailsStable>,
generations_check?: SuperMap<string, RequestStatusCheck>,
generations_status?: SuperMap<string, RequestStatusStable>,
models?: SuperMap<string, ActiveModel[]>,
modes?: SuperMap<string, HordeModes>,
news?: SuperMap<string, Newspiece[]>,
performance?: SuperMap<string, HordePerformanceStable>,
workers?: SuperMap<string, WorkerDetailsStable>,
teams?: SuperMap<string, TeamDetails>
}
export interface ModifyUserInput {
/** The amount of kudos to modify (can be negative) */
kudos?: number,
/**
* The amount of concurrent request this user can have
* @minimum 0
* @maximum 100
*/
concurrency?: number,
/**
* The amount by which to multiply the users kudos consumption
* @minimum 0.1
* @maximum 10
*/
usage_multiplier?: number,
/** Set to the amount of workers this user is allowed to join to the horde when in worker invite-only mode. */
worker_invited?: number,
/**
* Set to true to Make this user a horde moderator
* @example false
*/
moderator?: boolean,
/**
* Set to true to Make this user a display their worker IDs
* @example false
*/
public_workers?: boolean,
/**
* When specified, will start assigning the user monthly kudos, starting now!
* @minimum 0
*/
monthly_kudos?: number,
/**
* When specified, will change the username. No profanity allowed!
* @minLength 3
* @maxLength 100
*/
username?: string,
/**
* When set to true,the user and their servers will not be affected by suspicion
* @example false
*/
trusted?: boolean,
/** Set the user's suspicion back to 0 */
reset_suspicion?: boolean,
/**
* Contact details for the horde admins to reach the user in case of emergency. This is only visible to horde moderators.
* @example [email protected]
* @minLength 5
* @maxLength 500
*/
contact?: string
}
export interface ModifyWorkerInput {
/** (Mods only) Set to true to put this worker into maintenance. */
maintenance?: boolean,
/** (Mods only) Set to true to pause this worker. */
paused?: boolean,
/**
* You can optionally provide a server note which will be seen in the server details. No profanity allowed!
* @minLength 5
* @maxLength 1000
*/
info?: string,
/**
* When this is set, it will change the worker's name. No profanity allowed!
* @minLength 5
* @maxLength 100
*/
name?: string
/**
* The team towards which this worker contributes kudos. No profanity allowed!
* @example 0bed257b-e57c-4327-ac64-40cdfb1ac5e6
* @minLength 3
* @maxLength 100
*/
team?: string
}
/* API TYPES */
/**
* @link https://stablehorde.net/api/
*/
export interface GenerationInput {
/** The prompt which will be sent to Stable Diffusion to generate an image */
prompt: string,
/** The parameters for the generation */
params?: ModelGenerationInputStable,
/**
* Set to true if this request is NSFW. This will skip workers which censor images.
* @default false
*/
nsfw?: boolean,
/**
* When true, only trusted workers will serve this request. When False, Evaluating workers will also be used which can increase speed but adds more risk!
* @default true
*/
trusted_workers?: boolean,
/**
* If the request is SFW, and the worker accidentaly generates NSFW, it will send back a censored image.
* @default false
*/
censor_nsfw?: boolean,
/** Specify which workers are allowed to service this request */
workers?: string[],
/** Specify which models are allowed to be used for this request */
models?: string[],
/** The Base64-encoded webp to use for img2img, max siue 3072 * 3072 */
source_image?: string,
/** If source_image is provided, specifies how to process it. */
source_processing?: typeof StableHorde.SourceImageProcessingTypes[keyof typeof StableHorde.SourceImageProcessingTypes],
/** If source_processing is set to 'inpainting' or 'outpainting', this parameter can be optionally provided as the Base64-encoded webp mask of the areas to inpaint. If this arg is not passed, the inpainting/outpainting mask has to be embedded as alpha channel */
source_mask?: string,
}
export interface ModelGenerationInputStable {
/**
* @default k_euler
*/
sampler_name?: typeof StableHorde.ModelGenerationInputStableSamplers[keyof typeof StableHorde.ModelGenerationInputStableSamplers],
/**
* Special Toggles used in the SD Webui. To be documented.
*/
toggles?: number[],
/**
* its how much the AI listens to your prompt, essentially.
* @default 5
* @minimum -40
* @maximum 30
*
* Multiple of 0.5
*/
cfg_scale?: number,
/**
* The strength of denoising
* @minimum 0
* @maximum 1
*
* Multiple of 0.01
*/