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 items(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
416 ctype = (col.get("type") or "").lower()
417 if ctype == "image":
418 self.images = lambda: self.api.images(params, defaults=False)
419 elif ctype == "post":
420 self.posts = lambda: self.api.posts(params, defaults=False)
421 elif ctype == "model":
422 self.models = lambda: self.api.models(params, defaults=False)
423 else:
424 self.log.warning("Unsupported collection type '%s'", ctype)
425
426 return CivitaiExtractor.items(self)
427
428
429 class CivitaiPostExtractor(CivitaiExtractor):
430 subcategory = "post"
431 directory_fmt = ("{category}", "{username|user[username]}", "posts",
432 "{post[id]}{post[title]:? //}")
433 pattern = BASE_PATTERN + r"/posts/(\d+)"
434 example = "https://civitai.red/posts/12345"
435
436 def posts(self):
437 return ({"id": int(self.groups[0])},)
438
439
440 class CivitaiTagExtractor(CivitaiExtractor):
441 subcategory = "tag"
442 pattern = BASE_PATTERN + r"/tag/([^/?&#]+)"
443 example = "https://civitai.red/tag/TAG"
444
445 def models(self):
446 tag = text.unquote(self.groups[0])
447 return self.api.models_tag(tag)
448
449
450 class CivitaiSearchModelsExtractor(CivitaiExtractor):
451 subcategory = "search-models"
452 pattern = BASE_PATTERN + r"/search/models\?([^#]+)"
453 example = "https://civitai.red/search/models?query=QUERY"
454
455 def models(self):
456 params = self._parse_query(self.groups[0])
457 return CivitaiSearchAPI(self).search_models(
458 params.get("query"), params.get("sortBy"), self.api.nsfw)
459
460
461 class CivitaiSearchImagesExtractor(CivitaiExtractor):
462 subcategory = "search-images"
463 pattern = BASE_PATTERN + r"/search/images\?([^#]+)"
464 example = "https://civitai.red/search/images?query=QUERY"
465
466 def images(self):
467 params = self._parse_query(self.groups[0])
468 return CivitaiSearchAPI(self).search_images(
469 params.get("query"), params.get("sortBy"), self.api.nsfw)
470
471
472 class CivitaiModelsExtractor(CivitaiExtractor):
473 subcategory = "models"
474 pattern = BASE_PATTERN + r"/models(?:/?\?([^#]+))?(?:$|#)"
475 example = "https://civitai.red/models"
476
477 def models(self):
478 params = self._parse_query(self.groups[0])
479 return self.api.models(params)
480
481
482 class CivitaiImagesExtractor(CivitaiExtractor):
483 subcategory = "images"
484 pattern = BASE_PATTERN + r"/images(?:/?\?([^#]+))?(?:$|#)"
485 example = "https://civitai.red/images"
486
487 def images(self):
488 params = self._parse_query(self.groups[0])
489 params["types"] = ("image",)
490 return self.api.images(params)
491
492
493 class CivitaiVideosExtractor(CivitaiExtractor):
494 subcategory = "videos"
495 pattern = BASE_PATTERN + r"/videos(?:/?\?([^#]+))?(?:$|#)"
496 example = "https://civitai.red/videos"
497
498 def images(self):
499 params = self._parse_query(self.groups[0])
500 params["types"] = ("video",)
501 return self.api.images(params)
502
503
504 class CivitaiPostsExtractor(CivitaiExtractor):
505 subcategory = "posts"
506 pattern = BASE_PATTERN + r"/posts(?:/?\?([^#]+))?(?:$|#)"
507 example = "https://civitai.red/posts"
508
509 def posts(self):
510 params = self._parse_query(self.groups[0])
511 return self.api.posts(params)
512
513
514 class CivitaiUserExtractor(Dispatch, CivitaiExtractor):
515 pattern = USER_PATTERN + r"/?(?:$|\?|#)"
516 example = "https://civitai.red/user/USER"
517
518 def items(self):
519 base = f"{self.root}/user/{self.groups[0]}/"
520 return self._dispatch_extractors((
521 (CivitaiUserModelsExtractor, base + "models"),
522 (CivitaiUserPostsExtractor , base + "posts"),
523 (CivitaiUserImagesExtractor, base + "images"),
524 (CivitaiUserVideosExtractor, base + "videos"),
525 (CivitaiUserCollectionsExtractor, base + "collections"),
526 ), ("user-images", "user-videos"))
527
528
529 class CivitaiUserModelsExtractor(CivitaiExtractor):
530 subcategory = "user-models"
531 pattern = USER_PATTERN + r"/models/?(?:\?([^#]+))?"
532 example = "https://civitai.red/user/USER/models"
533
534 def models(self):
535 user, query = self.groups
536 params = self._parse_query(query)
537 params["username"] = text.unquote(user)
538 return self.api.models(params)
539
540
541 class CivitaiUserPostsExtractor(CivitaiExtractor):
542 subcategory = "user-posts"
543 directory_fmt = ("{category}", "{username|user[username]}", "posts",
544 "{post[id]}{post[title]:? //}")
545 pattern = USER_PATTERN + r"/posts/?(?:\?([^#]+))?"
546 example = "https://civitai.red/user/USER/posts"
547
548 def posts(self):
549 user, query = self.groups
550 params = self._parse_query(query)
551 params["username"] = text.unquote(user)
552 return self.api.posts(params)
553
554
555 class CivitaiUserImagesExtractor(CivitaiExtractor):
556 subcategory = "user-images"
557 pattern = USER_PATTERN + r"/images/?(?:\?([^#]+))?"
558 example = "https://civitai.red/user/USER/images"
559
560 def __init__(self, match):
561 user, query = match.groups()
562 self.params = self._parse_query(query)
563 self.params["types"] = ("image",)
564 if self.params.get("section") == "reactions":
565 self.subcategory = "reactions-images"
566 self.images = self._image_reactions
567 else:
568 self.params["username"] = text.unquote(user)
569 CivitaiExtractor.__init__(self, match)
570
571 def images(self):
572 return self.api.images(self.params)
573
574
575 class CivitaiUserVideosExtractor(CivitaiExtractor):
576 subcategory = "user-videos"
577 directory_fmt = ("{category}", "{username|user[username]}", "videos")
578 pattern = USER_PATTERN + r"/videos/?(?:\?([^#]+))?"
579 example = "https://civitai.red/user/USER/videos"
580
581 def __init__(self, match):
582 user, query = match.groups()
583 self.params = self._parse_query(query)
584 self.params["types"] = ("video",)
585 if self.params.get("section") == "reactions":
586 self.subcategory = "reactions-videos"
587 self.images = self._image_reactions
588 else:
589 self.params["username"] = text.unquote(user)
590 CivitaiExtractor.__init__(self, match)
591
592 images = CivitaiUserImagesExtractor.images
593
594
595 class CivitaiUserCollectionsExtractor(CivitaiExtractor):
596 subcategory = "user-collections"
597 pattern = USER_PATTERN + r"/collections/?(?:\?([^#]+))?"
598 example = "https://civitai.red/user/USER/collections"
599
600 def items(self):
601 user, query = self.groups
602 params = self._parse_query(query)
603 params["userId"] = self.api.user(text.unquote(user))[0]["id"]
604
605 base = self.root + "/collections/"
606 for collection in self.api.collections(params):
607 collection["_extractor"] = CivitaiCollectionExtractor
608 yield Message.Queue, base + str(collection["id"]), collection
609
610
611 class CivitaiGeneratedExtractor(CivitaiExtractor):
612 """Extractor for your generated files feed"""
613 subcategory = "generated"
614 filename_fmt = "{filename}.{extension}"
615 directory_fmt = ("{category}", "generated")
616 pattern = BASE_PATTERN + "/generate"
617 example = "https://civitai.red/generate"
618
619 def items(self):
620 self._require_auth()
621
622 for gen in self.api.orchestrator_queryGeneratedImages():
623 gen["date"] = self.parse_datetime_iso(gen["createdAt"])
624 yield Message.Directory, "", gen
625 for step in gen.pop("steps", ()):
626 for image in step.pop("images", ()):
627 data = {"file": image, **step, **gen}
628 url = image["url"]
629 yield Message.Url, url, text.nameext_from_url(url, data)
630
631
632 class CivitaiRestAPI():
633 """Interface for the Civitai Public REST API
634
635 https://developer.civitai.com/docs/api/public-rest
636 """
637
638 def __init__(self, extractor):
639 self.extractor = extractor
640 self.root = extractor.root + "/api"
641 self.headers = {"Content-Type": "application/json"}
642
643 if api_key := extractor.config("api-key"):
644 extractor.log.debug("Using api_key authentication")
645 self.headers["Authorization"] = "Bearer " + api_key
646
647 nsfw = extractor.config("nsfw")
648 if nsfw is None or nsfw is True:
649 nsfw = "X"
650 elif not nsfw:
651 nsfw = "Safe"
652 self.nsfw = nsfw
653
654 def image(self, image_id):
655 return self.images({
656 "imageId": image_id,
657 })
658
659 def images(self, params):
660 endpoint = "/v1/images"
661 if "nsfw" not in params:
662 params["nsfw"] = self.nsfw
663 return self._pagination(endpoint, params)
664
665 def images_gallery(self, model, version, user):
666 return self.images({
667 "modelId" : model["id"],
668 "modelVersionId": version["id"],
669 })
670
671 def model(self, model_id):
672 endpoint = "/v1/models/" + str(model_id)
673 return self._call(endpoint)
674
675 def model_version(self, model_version_id):
676 endpoint = "/v1/model-versions/" + str(model_version_id)
677 return self._call(endpoint)
678
679 def models(self, params):
680 return self._pagination("/v1/models", params)
681
682 def models_tag(self, tag):
683 return self.models({"tag": tag})
684
685 def _call(self, endpoint, params=None):
686 if endpoint[0] == "/":
687 url = self.root + endpoint
688 else:
689 url = endpoint
690
691 response = self.extractor.request(
692 url, params=params, headers=self.headers)
693 return response.json()
694
695 def _pagination(self, endpoint, params):
696 while True:
697 data = self._call(endpoint, params)
698 yield from data["items"]
699
700 try:
701 endpoint = data["metadata"]["nextPage"]
702 except KeyError:
703 return
704 params = None
705
706
707 class CivitaiTrpcAPI():
708 """Interface for the Civitai tRPC API"""
709
710 def __init__(self, extractor):
711 self.extractor = extractor
712 self.root = extractor.root + "/api/trpc/"
713 self.headers = {
714 "content-type" : "application/json",
715 "x-client-version": "5.0.2142",
716 "x-client-date" : "",
717 "x-client" : "web",
718 "x-fingerprint" : "undefined",
719 }
720 if api_key := extractor.config("api-key"):
721 extractor.log.debug("Using api_key authentication")
722 self.headers["Authorization"] = "Bearer " + api_key
723
724 nsfw = extractor.config("nsfw")
725 if nsfw is None or nsfw is True:
726 nsfw = 31
727 elif not nsfw:
728 nsfw = 1
729 self.nsfw = nsfw
730
731 def image(self, image_id):
732 endpoint = "image.get"
733 params = {"id": int(image_id)}
734 return (self._call(endpoint, params),)
735
736 def image_generationdata(self, image_id):
737 endpoint = "image.getGenerationData"
738 params = {"id": int(image_id)}
739 return self._call(endpoint, params)
740
741 def images(self, params, defaults=True):
742 endpoint = "image.getInfinite"
743
744 if defaults:
745 params = self._merge_params(params, {
746 "useIndex" : True,
747 "period" : self._param_period(),
748 "sort" : self._param_sort(),
749 "withMeta" : False, # Metadata Only
750 "fromPlatform" : False, # Made On-Site
751 "browsingLevel": self.nsfw,
752 "include" : ("cosmetics",),
753 })
754
755 params = self._type_params(params)
756 return self._pagination(endpoint, params)
757
758 def images_gallery(self, model, version, user):
759 endpoint = "image.getImagesAsPostsInfinite"
760 params = {
761 "period" : self._param_period(),
762 "sort" : self._param_sort(),
763 "modelVersionId": version["id"],
764 "modelId" : model["id"],
765 "hidden" : False,
766 "limit" : 50,
767 "browsingLevel" : self.nsfw,
768 }
769
770 for post in self._pagination(endpoint, params):
771 yield from post["images"]
772
773 def images_post(self, post_id):
774 params = {
775 "postId" : int(post_id),
776 "pending": True,
777 }
778 return self.images(params)
779
780 def model(self, model_id):
781 endpoint = "model.getById"
782 params = {"id": int(model_id)}
783 return self._call(endpoint, params)
784
785 def model_version(self, model_version_id):
786 endpoint = "modelVersion.getById"
787 params = {"id": int(model_version_id)}
788 return self._call(endpoint, params)
789
790 def models(self, params, defaults=True):
791 endpoint = "model.getAll"
792
793 if defaults:
794 params = self._merge_params(params, {
795 "period" : self._param_period(),
796 "periodMode" : "published",
797 "sort" : self._param_sort(),
798 "pending" : False,
799 "hidden" : False,
800 "followed" : False,
801 "earlyAccess" : False,
802 "fromPlatform" : False,
803 "supportsGeneration": False,
804 "browsingLevel": self.nsfw,
805 })
806
807 return self._pagination(endpoint, params)
808
809 def models_tag(self, tag):
810 return self.models({"tagname": tag})
811
812 def post(self, post_id):
813 endpoint = "post.get"
814 params = {"id": int(post_id)}
815 return self._call(endpoint, params)
816
817 def posts(self, params, defaults=True):
818 endpoint = "post.getInfinite"
819
820 if defaults:
821 params = self._merge_params(params, {
822 "browsingLevel": self.nsfw,
823 "period" : self._param_period(),
824 "periodMode" : "published",
825 "sort" : self._param_sort(),
826 "followed" : False,
827 "draftOnly" : False,
828 "pending" : True,
829 "include" : ("cosmetics",),
830 })
831
832 params = self._type_params(params)
833 return self._pagination(endpoint, params, user=("username" in params))
834
835 def collection(self, collection_id):
836 endpoint = "collection.getById"
837 params = {"id": int(collection_id)}
838 return self._call(endpoint, params)["collection"]
839
840 def collections(self, params, defaults=True):
841 endpoint = "collection.getInfinite"
842
843 if defaults:
844 params = self._merge_params(params, {
845 "browsingLevel": self.nsfw,
846 "sort" : self._param_sort(),
847 })
848
849 params = self._type_params(params)
850 return self._pagination(endpoint, params)
851
852 def tag_getvotabletags(self, image_id):
853 endpoint = "tag.getVotableTags"
854 params = {"id": int(image_id), "type": "image"}
855 return self._call(endpoint, params)
856
857 def user(self, username):
858 endpoint = "user.getCreator"
859 params = {"username": username}
860 return (self._call(endpoint, params),)
861
862 def orchestrator_queryGeneratedImages(self):
863 endpoint = "orchestrator.queryGeneratedImages"
864 params = {
865 "ascending": True if self._param_sort() == "Oldest" else False,
866 "tags" : ("gen",),
867 "authed" : True,
868 }
869 return self._pagination(endpoint, params)
870
871 def _call(self, endpoint, params, meta=None):
872 url = self.root + endpoint
873 headers = self.headers
874
875 if meta:
876 input = {"json": params, "meta": {"values": meta}}
877 else:
878 input = {"json": params}
879
880 params = {"input": util.json_dumps(input)}
881 headers["x-client-date"] = str(int(time.time() * 1000))
882
883 data = self.extractor.request_json(
884 url, params=params, headers=headers)["result"]["data"]
885
886 return (self._unpack(util.json_loads(data))
887 if isinstance(data, str) else data["json"])
888
889 def _unpack(self, pack):
890 def resolve(item):
891 if isinstance(item, dict):
892 if all(isinstance(v, int) for v in item.values()):
893 for key, value in item.items():
894 item[key] = (resolve(pack[value])
895 if value >= 0 else None)
896 elif isinstance(item, list):
897 if all(isinstance(v, int) for v in item):
898 for idx, value in enumerate(item):
899 item[idx] = (resolve(pack[value])
900 if value >= 0 else None)
901 return item
902 return resolve(pack[0])
903
904 def _pagination(self, endpoint, params, meta=None, user=False):
905 if "cursor" not in params:
906 params["cursor"] = None
907 meta_ = {"cursor": ("undefined",)}
908
909 data = self._call(endpoint, params, meta_)
910 if user and data["items"] and \
911 data["items"][0]["user"]["username"] != params["username"]:
912 return ()
913
914 while True:
915 yield from data["items"]
916
917 try:
918 if not data["nextCursor"]:
919 return
920 except KeyError:
921 return
922
923 params["cursor"] = data["nextCursor"]
924 meta_ = meta
925 data = self._call(endpoint, params, meta_)
926
927 def _merge_params(self, params_user, params_default):
928 """Combine 'params_user' with 'params_default'"""
929 params_default.update(params_user)
930 return params_default
931
932 def _type_params(self, params):
933 """Convert 'params' values to expected types"""
934 types = {
935 "tags" : int,
936 "tools" : int,
937 "techniques" : int,
938 "modelId" : int,
939 "modelVersionId": int,
940 "remixesOnly" : _bool,
941 "nonRemixesOnly": _bool,
942 "withMeta" : _bool,
943 "fromPlatform" : _bool,
944 "supportsGeneration": _bool,
945 }
946
947 for name, value in params.items():
948 if name not in types:
949 continue
950 elif isinstance(value, str):
951 params[name] = types[name](value)
952 elif isinstance(value, list):
953 type = types[name]
954 params[name] = [type(item) for item in value]
955 return params
956
957 def _param_period(self):
958 if period := self.extractor.config("period"):
959 return period
960 return "AllTime"
961
962 def _param_sort(self):
963 if sort := self.extractor.config("sort"):
964 s = sort[0].lower()
965 if s in "drn":
966 return "Newest"
967 if s in "ao":
968 return "Oldest"
969 return sort
970 return "Newest"
971
972
973 def _bool(value):
974 return value == "true"
975
976
977 class CivitaiSearchAPI():
978
979 def __init__(self, extractor):
980 self.extractor = extractor
981 self.root = "https://search-new.civitai.com"
982
983 if auth := extractor.config("token"):
984 if " " not in auth:
985 auth = "Bearer " + auth
986 else:
987 auth = ("Bearer 8c46eb2508e21db1e9828a97968d"
988 "91ab1ca1caa5f70a00e88a2ba1e286603b61")
989
990 self.headers = {
991 "Authorization": auth,
992 "Content-Type": "application/json",
993 "X-Meilisearch-Client": "Meilisearch instant-meilisearch (v0.13.5)"
994 " ; Meilisearch JavaScript (v0.34.0)",
995 "Priority": "u=4",
996 }
997
998 def search(self, query, type, facets, nsfw=31):
999 endpoint = "/multi-search"
1000
1001 query = {
1002 "q" : query,
1003 "indexUid": type,
1004 "facets" : facets,
1005 "attributesToHighlight": (),
1006 "highlightPreTag" : "__ais-highlight__",
1007 "highlightPostTag": "__/ais-highlight__",
1008 "limit" : 51,
1009 "offset": 0,
1010 "filter": (self._generate_filter(nsfw),),
1011 }
1012
1013 return self._pagination(endpoint, query)
1014
1015 def search_models(self, query, type=None, nsfw=31):
1016 facets = (
1017 "category.name",
1018 "checkpointType",
1019 "fileFormats",
1020 "lastVersionAtUnix",
1021 "tags.name",
1022 "type",
1023 "user.username",
1024 "version.baseModel",
1025 )
1026 return self.search(query, type or "models_v9", facets, nsfw)
1027
1028 def search_images(self, query, type=None, nsfw=31):
1029 facets = (
1030 "aspectRatio",
1031 "baseModel",
1032 "createdAtUnix",
1033 "tagNames",
1034 "techniqueNames",
1035 "toolNames",
1036 "type",
1037 "user.username",
1038 )
1039 return self.search(query, type or "images_v6", facets, nsfw)
1040
1041 def _call(self, endpoint, query):
1042 url = self.root + endpoint
1043 params = util.json_dumps({"queries": (query,)})
1044
1045 data = self.extractor.request_json(
1046 url, method="POST", headers=self.headers, data=params)
1047
1048 return data["results"][0]
1049
1050 def _pagination(self, endpoint, query):
1051 limit = query["limit"] - 1
1052 threshold = limit // 2
1053
1054 while True:
1055 data = self._call(endpoint, query)
1056
1057 items = data["hits"]
1058 yield from items
1059
1060 if len(items) < threshold:
1061 return
1062 query["offset"] += limit
1063
1064 def _generate_filter(self, level):
1065 fltr = []
1066
1067 if level & 1:
1068 fltr.append("1")
1069 if level & 2:
1070 fltr.append("2")
1071 if level & 4:
1072 fltr.append("4")
1073 if level & 8:
1074 fltr.append("8")
1075 if level & 16:
1076 fltr.append("16")
1077
1078 if not fltr:
1079 return "()"
1080 return "(nsfwLevel=" + " OR nsfwLevel=".join(fltr) + ")"