Debian Codegraph @

gallery_dl/extractor/civitai.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2024-2026 Mike Fährmann
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License version 2 as
7 # published by the Free Software Foundation.
8
9 """Extractors for https://civitai.com/ and https://civitai.red/"""
10
11 from .common import Extractor, Message, Dispatch
12 from .. import text, util
13 import itertools
14 import time
15
16 BASE_PATTERN = r"(?:https?://)?civitai\.(?:red|com)"
17 USER_PATTERN = BASE_PATTERN + r"/user/([^/?#]+)"
18
19
20 class CivitaiExtractor(Extractor):
21 """Base class for civitai extractors"""
22 category = "civitai"
23 root = "https://civitai.red"
24 directory_fmt = ("{category}", "{user[username]}", "images")
25 filename_fmt = "{file[id]}.{extension}"
26 archive_fmt = "{file[uuid]}"
27 request_interval = (0.5, 1.5)
28
29 def _init(self):
30 if self.config("api") == "rest":
31 self.log.debug("Using REST API")
32 self.api = CivitaiRestAPI(self)
33 else:
34 self.log.debug("Using tRPC API")
35 self.api = CivitaiTrpcAPI(self)
36
37 if quality := self.config("quality"):
38 if not isinstance(quality, str):
39 quality = ",".join(quality)
40 self._image_quality = quality
41 self._image_ext = ("png" if quality == "original=true" else "jpg")
42 else:
43 self._image_quality = "original=true"
44 self._image_ext = "png"
45
46 if quality_video := self.config("quality-videos"):
47 if not isinstance(quality_video, str):
48 quality_video = ",".join(quality_video)
49 if quality_video[0] == "+":
50 quality_video = (self._image_quality + "," +
51 quality_video.lstrip("+,"))
52 self._video_quality = quality_video
53 elif quality_video is not None and quality:
54 self._video_quality = self._image_quality
55 else:
56 self._video_quality = "original"
57 self._video_quality_fb = self.config(
58 "quality-fallback", "transcode=true,original=true,quality=100")
59 self._video_ext = "webm"
60
61 if metadata := self.config("metadata"):
62 if isinstance(metadata, str):
63 metadata = metadata.split(",")
64 elif not isinstance(metadata, (list, tuple)):
65 metadata = {"generation", "version", "post", "tags"}
66 self._meta_generation = ("generation" in metadata)
67 self._meta_version = ("version" in metadata)
68 self._meta_post = ("post" in metadata)
69 self._meta_tags = ("tags" in metadata)
70 else:
71 self._meta_generation = self._meta_version = self._meta_post = \
72 self._meta_tags = False
73
74 def items(self):
75 if models := self.models():
76 data = {"_extractor": CivitaiModelExtractor}
77 for model in models:
78 url = f"{self.root}/models/{model['id']}"
79 yield Message.Queue, url, data
80 return
81
82 if posts := self.posts():
83 for post in posts:
84
85 if "images" in post:
86 images = post["images"]
87 else:
88 images = self.api.images_post(post["id"])
89
90 post = self.api.post(post["id"])
91 post["date"] = self.parse_datetime_iso(post["publishedAt"])
92 data = {
93 "post": post,
94 "user": post.pop("user"),
95 }
96 if self._meta_version:
97 data["model"], data["version"] = \
98 self._extract_meta_version(post)
99
100 yield Message.Directory, "", data
101 for file in self._image_results(images):
102 file.update(data)
103 yield Message.Url, file["url"], file
104 return
105
106 if images := self.images():
107 for file in images:
108
109 data = {
110 "file": file,
111 "user": file.pop("user"),
112 }
113
114 if self._meta_generation:
115 data["generation"] = self._extract_meta_generation(file)
116 if self._meta_tags:
117 data["tags"] = self._extract_meta_tags(file)
118 if self._meta_version:
119 data["model"], data["version"] = \
120 self._extract_meta_version(file, False)
121 if "post" in file:
122 data["post"] = file.pop("post")
123 if self._meta_post and "post" not in data:
124 data["post"] = post = self._extract_meta_post(file)
125 if post:
126 post.pop("user", None)
127 file["date"] = self.parse_datetime_iso(file["createdAt"])
128
129 data["url"] = url = self._url(file)
130 text.nameext_from_url(url, data)
131 if not data["extension"]:
132 data["extension"] = (
133 self._video_ext if file.get("type") == "video" else
134 self._image_ext)
135 if "_fallback" in file:
136 data["_fallback"] = file.pop("_fallback")
137 yield Message.Directory, "", data
138 yield Message.Url, url, data
139 return
140
141 def models(self):
142 return ()
143
144 def posts(self):
145 return ()
146
147 def images(self):
148 return ()
149
150 def _url(self, image):
151 url = image["url"]
152 video = image.get("type") == "video"
153 quality = self._video_quality if video else self._image_quality
154
155 if "/" in url:
156 parts = url.rsplit("/", 3)
157 image["uuid"] = parts[1]
158 parts[2] = quality
159 return "/".join(parts)
160
161 image["uuid"] = url
162 name = image.get("name")
163 if not name:
164 if mime := image.get("mimeType"):
165 name = f"{image.get('id')}.{mime.rpartition('/')[2]}"
166 else:
167 ext = self._video_ext if video else self._image_ext
168 name = f"{image.get('id')}.{ext}"
169
170 base = f"https://image.civitai.com/xG1nkqKTMzGDvpLrqFT7WA/{url}/"
171 if not video:
172 return f"{base}{quality}/{name}"
173 image["_fallback"] = (f"{base}{self._video_quality_fb}/{name}",)
174 return (f"https://image-b2.civitai.com/file/civitai-media-cache"
175 f"/{url}/{quality}")
176
177 def _image_results(self, images):
178 for num, file in enumerate(images, 1):
179 data = text.nameext_from_url(file["url"], {
180 "num" : num,
181 "file": file,
182 "url" : self._url(file),
183 })
184 if not data["extension"]:
185 data["extension"] = (
186 self._video_ext if file.get("type") == "video" else
187 self._image_ext)
188 if "_fallback" in file:
189 data["_fallback"] = file.pop("_fallback")
190 if "id" not in file and data["filename"].isdecimal():
191 file["id"] = text.parse_int(data["filename"])
192 if "date" not in file and "createdAt" in file:
193 file["date"] = self.parse_datetime_iso(file["createdAt"])
194 if self._meta_generation:
195 file["generation"] = self._extract_meta_generation(file)
196 if self._meta_tags:
197 file["tags"] = self._extract_meta_tags(file)
198 yield data
199
200 def _image_reactions(self):
201 self._require_auth()
202
203 params = self.params
204 params["authed"] = True
205 params["useIndex"] = False
206 if "reactions" not in params:
207 params["reactions"] = ("Like", "Dislike", "Heart", "Laugh", "Cry")
208 return self.api.images(params)
209
210 def _require_auth(self):
211 if "Authorization" not in self.api.headers and \
212 not self.cookies.get(
213 "__Secure-civitai-token", domain=".civitai.red"):
214 raise self.extractor.exc.AuthRequired(
215 ("api-key", "authenticated cookies"))
216
217 def _parse_query(self, value):
218 return text.parse_query_list(
219 value, {"tags", "reactions", "baseModels", "tools", "techniques",
220 "types", "fileFormats"})
221
222 def _extract_meta_generation(self, image):
223 try:
224 return self.api.image_generationdata(image["id"])
225 except Exception as exc:
226 return self.log.traceback(exc)
227
228 def _extract_meta_post(self, image):
229 try:
230 post = self.api.post(image["postId"])
231 post["date"] = self.parse_datetime_iso(post["publishedAt"])
232 return post
233 except Exception as exc:
234 return self.log.traceback(exc)
235
236 def _extract_meta_tags(self, image):
237 try:
238 return self.api.tag_getvotabletags(image["id"])
239 except Exception as exc:
240 return self.log.traceback(exc)
241
242 def _extract_meta_version(self, item, is_post=True):
243 try:
244 if version_id := self._extract_version_id(item, is_post):
245 version = self.cache(self.api.model_version, version_id).copy()
246 return version.pop("model", None), version
247 except Exception as exc:
248 self.log.traceback(exc)
249 return None, None
250
251 def _extract_version_id(self, item, is_post=True):
252 if version_id := item.get("modelVersionId"):
253 return version_id
254 if version_ids := item.get("modelVersionIds"):
255 return version_ids[0]
256 if version_ids := item.get("modelVersionIdsManual"):
257 return version_ids[0]
258
259 if is_post:
260 return None
261
262 item["post"] = post = self.api.post(item["postId"])
263 post.pop("user", None)
264 return self._extract_version_id(post)
265
266
267 class CivitaiModelExtractor(CivitaiExtractor):
268 subcategory = "model"
269 directory_fmt = ("{category}", "{user[username]}",
270 "{model[id]}{model[name]:? //}",
271 "{version[id]}{version[name]:? //}")
272 pattern = BASE_PATTERN + r"/models/(\d+)(?:/?\?modelVersionId=(\d+))?"
273 example = "https://civitai.red/models/12345/TITLE"
274
275 def items(self):
276 model_id, version_id = self.groups
277 model = self.api.model(model_id)
278
279 if "user" in model:
280 user = model["user"]
281 del model["user"]
282 else:
283 user = model["creator"]
284 del model["creator"]
285 versions = model["modelVersions"]
286 del model["modelVersions"]
287
288 if version_id:
289 version_id = int(version_id)
290 for version in versions:
291 if version["id"] == version_id:
292 break
293 else:
294 version = self.cache(self.api.model_version, version_id)
295 versions = (version,)
296
297 for version in versions:
298 version["date"] = self.parse_datetime_iso(version["createdAt"])
299
300 data = {
301 "model" : model,
302 "version": version,
303 "user" : user,
304 }
305
306 yield Message.Directory, "", data
307 for file in self._extract_files(model, version, user):
308 file.update(data)
309 yield Message.Url, file["url"], file
310
311 def _extract_files(self, model, version, user):
312 filetypes = self.config("files")
313 if filetypes is None:
314 return self._extract_files_image(model, version, user)
315
316 generators = {
317 "model" : self._extract_files_model,
318 "image" : self._extract_files_image,
319 "gallery" : self._extract_files_gallery,
320 "gallerie": self._extract_files_gallery,
321 }
322 if isinstance(filetypes, str):
323 filetypes = filetypes.split(",")
324
325 return itertools.chain.from_iterable(
326 generators[ft.rstrip("s")](model, version, user)
327 for ft in filetypes
328 )
329
330 def _extract_files_model(self, model, version, user):
331 files = []
332
333 for num, file in enumerate(version["files"], 1):
334 name, sep, ext = file["name"].rpartition(".")
335 if not sep:
336 name = ext
337 ext = "bin"
338 file["uuid"] = f"model-{model['id']}-{version['id']}-{file['id']}"
339 files.append({
340 "num" : num,
341 "file" : file,
342 "filename" : name,
343 "extension": ext,
344 "url" : (
345 file.get("downloadUrl") or
346 f"{self.root}/api/download/models/{version['id']}"),
347 "_http_headers" : {
348 "Authorization": self.api.headers.get("Authorization")},
349 "_http_validate": self._validate_file_model,
350 })
351
352 return files
353
354 def _extract_files_image(self, model, version, user):
355 if "images" in version:
356 images = version["images"]
357 else:
358 params = {
359 "modelVersionId": version["id"],
360 "prioritizedUserIds": (user["id"],),
361 "period" : self.api._param_period(),
362 "sort" : self.api._param_sort(),
363 "limit" : 20,
364 "pending": True,
365 }
366 images = self.api.images(params, defaults=False)
367
368 return self._image_results(images)
369
370 def _extract_files_gallery(self, model, version, user):
371 images = self.api.images_gallery(model, version, user)
372 return self._image_results(images)
373
374 def _validate_file_model(self, response):
375 if response.headers.get("Content-Type", "").startswith("text/html"):
376 alert = text.extr(
377 response.text, 'mantine-Alert-message">', "</div></div></div>")
378 if alert:
379 msg = f"\"{text.remove_html(alert)}\" - 'api-key' required"
380 else:
381 msg = "'api-key' required to download this file"
382 self.log.warning(msg)
383 return False
384 return True
385
386
387 class CivitaiImageExtractor(CivitaiExtractor):
388 subcategory = "image"
389 pattern = BASE_PATTERN + r"/images/(\d+)"
390 example = "https://civitai.red/images/12345"
391
392 def images(self):
393 return self.api.image(self.groups[0])
394
395
396 class CivitaiCollectionExtractor(CivitaiExtractor):
397 subcategory = "collection"
398 directory_fmt = ("{category}", "{user_collection[username]}",
399 "collections", "{collection[id]}{collection[name]:? //}")
400 pattern = BASE_PATTERN + r"/collections/(\d+)"
401 example = "https://civitai.red/collections/12345"
402
403 def images(self):
404 cid = int(self.groups[0])
405 self.kwdict["collection"] = col = self.api.collection(cid)
406 self.kwdict["user_collection"] = col.pop("user", None)
407
408 params = {
409 "collectionId" : cid,
410 "period" : self.api._param_period(),
411 "sort" : self.api._param_sort(),
412 "browsingLevel" : self.api.nsfw,
413 "include" : ("cosmetics",),
414 }
415 return self.api.images(params, defaults=False)
416
417
418 class CivitaiPostExtractor(CivitaiExtractor):
419 subcategory = "post"
420 directory_fmt = ("{category}", "{username|user[username]}", "posts",
421 "{post[id]}{post[title]:? //}")
422 pattern = BASE_PATTERN + r"/posts/(\d+)"
423 example = "https://civitai.red/posts/12345"
424
425 def posts(self):
426 return ({"id": int(self.groups[0])},)
427
428
429 class CivitaiTagExtractor(CivitaiExtractor):
430 subcategory = "tag"
431 pattern = BASE_PATTERN + r"/tag/([^/?&#]+)"
432 example = "https://civitai.red/tag/TAG"
433
434 def models(self):
435 tag = text.unquote(self.groups[0])
436 return self.api.models_tag(tag)
437
438
439 class CivitaiSearchModelsExtractor(CivitaiExtractor):
440 subcategory = "search-models"
441 pattern = BASE_PATTERN + r"/search/models\?([^#]+)"
442 example = "https://civitai.red/search/models?query=QUERY"
443
444 def models(self):
445 params = self._parse_query(self.groups[0])
446 return CivitaiSearchAPI(self).search_models(
447 params.get("query"), params.get("sortBy"), self.api.nsfw)
448
449
450 class CivitaiSearchImagesExtractor(CivitaiExtractor):
451 subcategory = "search-images"
452 pattern = BASE_PATTERN + r"/search/images\?([^#]+)"
453 example = "https://civitai.red/search/images?query=QUERY"
454
455 def images(self):
456 params = self._parse_query(self.groups[0])
457 return CivitaiSearchAPI(self).search_images(
458 params.get("query"), params.get("sortBy"), self.api.nsfw)
459
460
461 class CivitaiModelsExtractor(CivitaiExtractor):
462 subcategory = "models"
463 pattern = BASE_PATTERN + r"/models(?:/?\?([^#]+))?(?:$|#)"
464 example = "https://civitai.red/models"
465
466 def models(self):
467 params = self._parse_query(self.groups[0])
468 return self.api.models(params)
469
470
471 class CivitaiImagesExtractor(CivitaiExtractor):
472 subcategory = "images"
473 pattern = BASE_PATTERN + r"/images(?:/?\?([^#]+))?(?:$|#)"
474 example = "https://civitai.red/images"
475
476 def images(self):
477 params = self._parse_query(self.groups[0])
478 params["types"] = ("image",)
479 return self.api.images(params)
480
481
482 class CivitaiVideosExtractor(CivitaiExtractor):
483 subcategory = "videos"
484 pattern = BASE_PATTERN + r"/videos(?:/?\?([^#]+))?(?:$|#)"
485 example = "https://civitai.red/videos"
486
487 def images(self):
488 params = self._parse_query(self.groups[0])
489 params["types"] = ("video",)
490 return self.api.images(params)
491
492
493 class CivitaiPostsExtractor(CivitaiExtractor):
494 subcategory = "posts"
495 pattern = BASE_PATTERN + r"/posts(?:/?\?([^#]+))?(?:$|#)"
496 example = "https://civitai.red/posts"
497
498 def posts(self):
499 params = self._parse_query(self.groups[0])
500 return self.api.posts(params)
501
502
503 class CivitaiUserExtractor(Dispatch, CivitaiExtractor):
504 pattern = USER_PATTERN + r"/?(?:$|\?|#)"
505 example = "https://civitai.red/user/USER"
506
507 def items(self):
508 base = f"{self.root}/user/{self.groups[0]}/"
509 return self._dispatch_extractors((
510 (CivitaiUserModelsExtractor, base + "models"),
511 (CivitaiUserPostsExtractor , base + "posts"),
512 (CivitaiUserImagesExtractor, base + "images"),
513 (CivitaiUserVideosExtractor, base + "videos"),
514 (CivitaiUserCollectionsExtractor, base + "collections"),
515 ), ("user-images", "user-videos"))
516
517
518 class CivitaiUserModelsExtractor(CivitaiExtractor):
519 subcategory = "user-models"
520 pattern = USER_PATTERN + r"/models/?(?:\?([^#]+))?"
521 example = "https://civitai.red/user/USER/models"
522
523 def models(self):
524 user, query = self.groups
525 params = self._parse_query(query)
526 params["username"] = text.unquote(user)
527 return self.api.models(params)
528
529
530 class CivitaiUserPostsExtractor(CivitaiExtractor):
531 subcategory = "user-posts"
532 directory_fmt = ("{category}", "{username|user[username]}", "posts",
533 "{post[id]}{post[title]:? //}")
534 pattern = USER_PATTERN + r"/posts/?(?:\?([^#]+))?"
535 example = "https://civitai.red/user/USER/posts"
536
537 def posts(self):
538 user, query = self.groups
539 params = self._parse_query(query)
540 params["username"] = text.unquote(user)
541 return self.api.posts(params)
542
543
544 class CivitaiUserImagesExtractor(CivitaiExtractor):
545 subcategory = "user-images"
546 pattern = USER_PATTERN + r"/images/?(?:\?([^#]+))?"
547 example = "https://civitai.red/user/USER/images"
548
549 def __init__(self, match):
550 user, query = match.groups()
551 self.params = self._parse_query(query)
552 self.params["types"] = ("image",)
553 if self.params.get("section") == "reactions":
554 self.subcategory = "reactions-images"
555 self.images = self._image_reactions
556 else:
557 self.params["username"] = text.unquote(user)
558 CivitaiExtractor.__init__(self, match)
559
560 def images(self):
561 return self.api.images(self.params)
562
563
564 class CivitaiUserVideosExtractor(CivitaiExtractor):
565 subcategory = "user-videos"
566 directory_fmt = ("{category}", "{username|user[username]}", "videos")
567 pattern = USER_PATTERN + r"/videos/?(?:\?([^#]+))?"
568 example = "https://civitai.red/user/USER/videos"
569
570 def __init__(self, match):
571 user, query = match.groups()
572 self.params = self._parse_query(query)
573 self.params["types"] = ("video",)
574 if self.params.get("section") == "reactions":
575 self.subcategory = "reactions-videos"
576 self.images = self._image_reactions
577 else:
578 self.params["username"] = text.unquote(user)
579 CivitaiExtractor.__init__(self, match)
580
581 images = CivitaiUserImagesExtractor.images
582
583
584 class CivitaiUserCollectionsExtractor(CivitaiExtractor):
585 subcategory = "user-collections"
586 pattern = USER_PATTERN + r"/collections/?(?:\?([^#]+))?"
587 example = "https://civitai.red/user/USER/collections"
588
589 def items(self):
590 user, query = self.groups
591 params = self._parse_query(query)
592 params["userId"] = self.api.user(text.unquote(user))[0]["id"]
593
594 base = self.root + "/collections/"
595 for collection in self.api.collections(params):
596 collection["_extractor"] = CivitaiCollectionExtractor
597 yield Message.Queue, base + str(collection["id"]), collection
598
599
600 class CivitaiGeneratedExtractor(CivitaiExtractor):
601 """Extractor for your generated files feed"""
602 subcategory = "generated"
603 filename_fmt = "{filename}.{extension}"
604 directory_fmt = ("{category}", "generated")
605 pattern = BASE_PATTERN + "/generate"
606 example = "https://civitai.red/generate"
607
608 def items(self):
609 self._require_auth()
610
611 for gen in self.api.orchestrator_queryGeneratedImages():
612 gen["date"] = self.parse_datetime_iso(gen["createdAt"])
613 yield Message.Directory, "", gen
614 for step in gen.pop("steps", ()):
615 for image in step.pop("images", ()):
616 data = {"file": image, **step, **gen}
617 url = image["url"]
618 yield Message.Url, url, text.nameext_from_url(url, data)
619
620
621 class CivitaiRestAPI():
622 """Interface for the Civitai Public REST API
623
624 https://developer.civitai.com/docs/api/public-rest
625 """
626
627 def __init__(self, extractor):
628 self.extractor = extractor
629 self.root = extractor.root + "/api"
630 self.headers = {"Content-Type": "application/json"}
631
632 if api_key := extractor.config("api-key"):
633 extractor.log.debug("Using api_key authentication")
634 self.headers["Authorization"] = "Bearer " + api_key
635
636 nsfw = extractor.config("nsfw")
637 if nsfw is None or nsfw is True:
638 nsfw = "X"
639 elif not nsfw:
640 nsfw = "Safe"
641 self.nsfw = nsfw
642
643 def image(self, image_id):
644 return self.images({
645 "imageId": image_id,
646 })
647
648 def images(self, params):
649 endpoint = "/v1/images"
650 if "nsfw" not in params:
651 params["nsfw"] = self.nsfw
652 return self._pagination(endpoint, params)
653
654 def images_gallery(self, model, version, user):
655 return self.images({
656 "modelId" : model["id"],
657 "modelVersionId": version["id"],
658 })
659
660 def model(self, model_id):
661 endpoint = "/v1/models/" + str(model_id)
662 return self._call(endpoint)
663
664 def model_version(self, model_version_id):
665 endpoint = "/v1/model-versions/" + str(model_version_id)
666 return self._call(endpoint)
667
668 def models(self, params):
669 return self._pagination("/v1/models", params)
670
671 def models_tag(self, tag):
672 return self.models({"tag": tag})
673
674 def _call(self, endpoint, params=None):
675 if endpoint[0] == "/":
676 url = self.root + endpoint
677 else:
678 url = endpoint
679
680 response = self.extractor.request(
681 url, params=params, headers=self.headers)
682 return response.json()
683
684 def _pagination(self, endpoint, params):
685 while True:
686 data = self._call(endpoint, params)
687 yield from data["items"]
688
689 try:
690 endpoint = data["metadata"]["nextPage"]
691 except KeyError:
692 return
693 params = None
694
695
696 class CivitaiTrpcAPI():
697 """Interface for the Civitai tRPC API"""
698
699 def __init__(self, extractor):
700 self.extractor = extractor
701 self.root = extractor.root + "/api/trpc/"
702 self.headers = {
703 "content-type" : "application/json",
704 "x-client-version": "5.0.2142",
705 "x-client-date" : "",
706 "x-client" : "web",
707 "x-fingerprint" : "undefined",
708 }
709 if api_key := extractor.config("api-key"):
710 extractor.log.debug("Using api_key authentication")
711 self.headers["Authorization"] = "Bearer " + api_key
712
713 nsfw = extractor.config("nsfw")
714 if nsfw is None or nsfw is True:
715 nsfw = 31
716 elif not nsfw:
717 nsfw = 1
718 self.nsfw = nsfw
719
720 def image(self, image_id):
721 endpoint = "image.get"
722 params = {"id": int(image_id)}
723 return (self._call(endpoint, params),)
724
725 def image_generationdata(self, image_id):
726 endpoint = "image.getGenerationData"
727 params = {"id": int(image_id)}
728 return self._call(endpoint, params)
729
730 def images(self, params, defaults=True):
731 endpoint = "image.getInfinite"
732
733 if defaults:
734 params = self._merge_params(params, {
735 "useIndex" : True,
736 "period" : self._param_period(),
737 "sort" : self._param_sort(),
738 "withMeta" : False, # Metadata Only
739 "fromPlatform" : False, # Made On-Site
740 "browsingLevel": self.nsfw,
741 "include" : ("cosmetics",),
742 })
743
744 params = self._type_params(params)
745 return self._pagination(endpoint, params)
746
747 def images_gallery(self, model, version, user):
748 endpoint = "image.getImagesAsPostsInfinite"
749 params = {
750 "period" : self._param_period(),
751 "sort" : self._param_sort(),
752 "modelVersionId": version["id"],
753 "modelId" : model["id"],
754 "hidden" : False,
755 "limit" : 50,
756 "browsingLevel" : self.nsfw,
757 }
758
759 for post in self._pagination(endpoint, params):
760 yield from post["images"]
761
762 def images_post(self, post_id):
763 params = {
764 "postId" : int(post_id),
765 "pending": True,
766 }
767 return self.images(params)
768
769 def model(self, model_id):
770 endpoint = "model.getById"
771 params = {"id": int(model_id)}
772 return self._call(endpoint, params)
773
774 def model_version(self, model_version_id):
775 endpoint = "modelVersion.getById"
776 params = {"id": int(model_version_id)}
777 return self._call(endpoint, params)
778
779 def models(self, params, defaults=True):
780 endpoint = "model.getAll"
781
782 if defaults:
783 params = self._merge_params(params, {
784 "period" : self._param_period(),
785 "periodMode" : "published",
786 "sort" : self._param_sort(),
787 "pending" : False,
788 "hidden" : False,
789 "followed" : False,
790 "earlyAccess" : False,
791 "fromPlatform" : False,
792 "supportsGeneration": False,
793 "browsingLevel": self.nsfw,
794 })
795
796 return self._pagination(endpoint, params)
797
798 def models_tag(self, tag):
799 return self.models({"tagname": tag})
800
801 def post(self, post_id):
802 endpoint = "post.get"
803 params = {"id": int(post_id)}
804 return self._call(endpoint, params)
805
806 def posts(self, params, defaults=True):
807 endpoint = "post.getInfinite"
808
809 if defaults:
810 params = self._merge_params(params, {
811 "browsingLevel": self.nsfw,
812 "period" : self._param_period(),
813 "periodMode" : "published",
814 "sort" : self._param_sort(),
815 "followed" : False,
816 "draftOnly" : False,
817 "pending" : True,
818 "include" : ("cosmetics",),
819 })
820
821 params = self._type_params(params)
822 return self._pagination(endpoint, params, user=("username" in params))
823
824 def collection(self, collection_id):
825 endpoint = "collection.getById"
826 params = {"id": int(collection_id)}
827 return self._call(endpoint, params)["collection"]
828
829 def collections(self, params, defaults=True):
830 endpoint = "collection.getInfinite"
831
832 if defaults:
833 params = self._merge_params(params, {
834 "browsingLevel": self.nsfw,
835 "sort" : self._param_sort(),
836 })
837
838 params = self._type_params(params)
839 return self._pagination(endpoint, params)
840
841 def tag_getvotabletags(self, image_id):
842 endpoint = "tag.getVotableTags"
843 params = {"id": int(image_id), "type": "image"}
844 return self._call(endpoint, params)
845
846 def user(self, username):
847 endpoint = "user.getCreator"
848 params = {"username": username}
849 return (self._call(endpoint, params),)
850
851 def orchestrator_queryGeneratedImages(self):
852 endpoint = "orchestrator.queryGeneratedImages"
853 params = {
854 "ascending": True if self._param_sort() == "Oldest" else False,
855 "tags" : ("gen",),
856 "authed" : True,
857 }
858 return self._pagination(endpoint, params)
859
860 def _call(self, endpoint, params, meta=None):
861 url = self.root + endpoint
862 headers = self.headers
863
864 if meta:
865 input = {"json": params, "meta": {"values": meta}}
866 else:
867 input = {"json": params}
868
869 params = {"input": util.json_dumps(input)}
870 headers["x-client-date"] = str(int(time.time() * 1000))
871
872 data = self.extractor.request_json(
873 url, params=params, headers=headers)["result"]["data"]
874
875 return (self._unpack(util.json_loads(data))
876 if isinstance(data, str) else data["json"])
877
878 def _unpack(self, pack):
879 def resolve(item):
880 if isinstance(item, dict):
881 if all(isinstance(v, int) for v in item.values()):
882 for key, value in item.items():
883 item[key] = (resolve(pack[value])
884 if value >= 0 else None)
885 elif isinstance(item, list):
886 if all(isinstance(v, int) for v in item):
887 for idx, value in enumerate(item):
888 item[idx] = (resolve(pack[value])
889 if value >= 0 else None)
890 return item
891 return resolve(pack[0])
892
893 def _pagination(self, endpoint, params, meta=None, user=False):
894 if "cursor" not in params:
895 params["cursor"] = None
896 meta_ = {"cursor": ("undefined",)}
897
898 data = self._call(endpoint, params, meta_)
899 if user and data["items"] and \
900 data["items"][0]["user"]["username"] != params["username"]:
901 return ()
902
903 while True:
904 yield from data["items"]
905
906 try:
907 if not data["nextCursor"]:
908 return
909 except KeyError:
910 return
911
912 params["cursor"] = data["nextCursor"]
913 meta_ = meta
914 data = self._call(endpoint, params, meta_)
915
916 def _merge_params(self, params_user, params_default):
917 """Combine 'params_user' with 'params_default'"""
918 params_default.update(params_user)
919 return params_default
920
921 def _type_params(self, params):
922 """Convert 'params' values to expected types"""
923 types = {
924 "tags" : int,
925 "tools" : int,
926 "techniques" : int,
927 "modelId" : int,
928 "modelVersionId": int,
929 "remixesOnly" : _bool,
930 "nonRemixesOnly": _bool,
931 "withMeta" : _bool,
932 "fromPlatform" : _bool,
933 "supportsGeneration": _bool,
934 }
935
936 for name, value in params.items():
937 if name not in types:
938 continue
939 elif isinstance(value, str):
940 params[name] = types[name](value)
941 elif isinstance(value, list):
942 type = types[name]
943 params[name] = [type(item) for item in value]
944 return params
945
946 def _param_period(self):
947 if period := self.extractor.config("period"):
948 return period
949 return "AllTime"
950
951 def _param_sort(self):
952 if sort := self.extractor.config("sort"):
953 s = sort[0].lower()
954 if s in "drn":
955 return "Newest"
956 if s in "ao":
957 return "Oldest"
958 return sort
959 return "Newest"
960
961
962 def _bool(value):
963 return value == "true"
964
965
966 class CivitaiSearchAPI():
967
968 def __init__(self, extractor):
969 self.extractor = extractor
970 self.root = "https://search-new.civitai.com"
971
972 if auth := extractor.config("token"):
973 if " " not in auth:
974 auth = "Bearer " + auth
975 else:
976 auth = ("Bearer 8c46eb2508e21db1e9828a97968d"
977 "91ab1ca1caa5f70a00e88a2ba1e286603b61")
978
979 self.headers = {
980 "Authorization": auth,
981 "Content-Type": "application/json",
982 "X-Meilisearch-Client": "Meilisearch instant-meilisearch (v0.13.5)"
983 " ; Meilisearch JavaScript (v0.34.0)",
984 "Priority": "u=4",
985 }
986
987 def search(self, query, type, facets, nsfw=31):
988 endpoint = "/multi-search"
989
990 query = {
991 "q" : query,
992 "indexUid": type,
993 "facets" : facets,
994 "attributesToHighlight": (),
995 "highlightPreTag" : "__ais-highlight__",
996 "highlightPostTag": "__/ais-highlight__",
997 "limit" : 51,
998 "offset": 0,
999 "filter": (self._generate_filter(nsfw),),
1000 }
1001
1002 return self._pagination(endpoint, query)
1003
1004 def search_models(self, query, type=None, nsfw=31):
1005 facets = (
1006 "category.name",
1007 "checkpointType",
1008 "fileFormats",
1009 "lastVersionAtUnix",
1010 "tags.name",
1011 "type",
1012 "user.username",
1013 "version.baseModel",
1014 )
1015 return self.search(query, type or "models_v9", facets, nsfw)
1016
1017 def search_images(self, query, type=None, nsfw=31):
1018 facets = (
1019 "aspectRatio",
1020 "baseModel",
1021 "createdAtUnix",
1022 "tagNames",
1023 "techniqueNames",
1024 "toolNames",
1025 "type",
1026 "user.username",
1027 )
1028 return self.search(query, type or "images_v6", facets, nsfw)
1029
1030 def _call(self, endpoint, query):
1031 url = self.root + endpoint
1032 params = util.json_dumps({"queries": (query,)})
1033
1034 data = self.extractor.request_json(
1035 url, method="POST", headers=self.headers, data=params)
1036
1037 return data["results"][0]
1038
1039 def _pagination(self, endpoint, query):
1040 limit = query["limit"] - 1
1041 threshold = limit // 2
1042
1043 while True:
1044 data = self._call(endpoint, query)
1045
1046 items = data["hits"]
1047 yield from items
1048
1049 if len(items) < threshold:
1050 return
1051 query["offset"] += limit
1052
1053 def _generate_filter(self, level):
1054 fltr = []
1055
1056 if level & 1:
1057 fltr.append("1")
1058 if level & 2:
1059 fltr.append("2")
1060 if level & 4:
1061 fltr.append("4")
1062 if level & 8:
1063 fltr.append("8")
1064 if level & 16:
1065 fltr.append("16")
1066
1067 if not fltr:
1068 return "()"
1069 return "(nsfwLevel=" + " OR nsfwLevel=".join(fltr) + ")"