diff --git a/Cargo.lock b/Cargo.lock index 4194f0c..51415a8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -662,6 +662,7 @@ dependencies = [ "base64 0.22.1", "chrono", "clap", + "futures", "libc", "reqwest", "serde", diff --git a/Dockerfile b/Dockerfile index 0d97a20..0183742 100644 --- a/Dockerfile +++ b/Dockerfile @@ -10,10 +10,17 @@ COPY --from=builder /src/target/release/freya-operator /usr/local/bin/freya-oper USER nonroot:nonroot ENTRYPOINT ["/usr/local/bin/freya-operator"] -FROM gcr.io/distroless/cc-debian12:nonroot AS api +# debian slim (not distroless) so gif modality can run ffmpeg. +# UID 65532 matches the previous distroless nonroot and gallery PVC ownership. +FROM debian:bookworm-slim AS api +RUN apt-get update \ + && apt-get install -y --no-install-recommends ffmpeg \ + && rm -rf /var/lib/apt/lists/* \ + && groupadd --gid 65532 nonroot \ + && useradd --uid 65532 --gid 65532 --no-create-home --shell /usr/sbin/nologin nonroot COPY --from=builder /src/target/release/freya-api /usr/local/bin/freya-api COPY packs /packs -USER nonroot:nonroot +USER 65532:65532 ENV FREYA_PACKS_DIR=/packs ENTRYPOINT ["/usr/local/bin/freya-api"] diff --git a/Makefile b/Makefile index 7f7dee3..70595c8 100644 --- a/Makefile +++ b/Makefile @@ -59,6 +59,10 @@ run-worker: ## Run diffusion worker locally (stub PNG unless FREYA_ENGINE_URL se run-local-worker: ## Build/run Docker freya-local-worker with GPU + Diffusers ./scripts/run-local-worker.sh +.PHONY: update-local-worker +update-local-worker: ## Pull CR/image tag and recreate freya-local-worker (GPU host) + ./scripts/update-local-worker.sh + run-operator: ## Run operator (needs kubeconfig) $(CARGO) run -p freya-operator --bin freya-operator diff --git a/config/samples/freya_v1alpha1_freyadiffusionworker_external.yaml b/config/samples/freya_v1alpha1_freyadiffusionworker_external.yaml index 81a5de4..a129462 100644 --- a/config/samples/freya_v1alpha1_freyadiffusionworker_external.yaml +++ b/config/samples/freya_v1alpha1_freyadiffusionworker_external.yaml @@ -23,6 +23,12 @@ spec: # Public / LAN URL of freya-local-worker (or vLLM-Omni-compatible) — not the Freya UI host. externalEndpoint: https://vllm.dataknife.net engine: vllm-omni + # Desired worker image — patch tag here, then on the GPU host run: + # ./scripts/update-local-worker.sh --from-cr freya-gpu + image: + repository: harbor.dataknife.net/library/freya-diffusion-worker + tag: "f2be1eb" + pullPolicy: Always # Must match FREYA_WORKER_TOKEN on the remote worker process authSecretRef: name: freya-worker-token diff --git a/config/samples/freya_v1alpha1_freyadiffusionworker_incluster.yaml b/config/samples/freya_v1alpha1_freyadiffusionworker_incluster.yaml index 9bfa0a4..f129071 100644 --- a/config/samples/freya_v1alpha1_freyadiffusionworker_incluster.yaml +++ b/config/samples/freya_v1alpha1_freyadiffusionworker_incluster.yaml @@ -8,6 +8,10 @@ metadata: spec: placement: incluster engine: vllm-omni + image: + repository: harbor.dataknife.net/library/freya-diffusion-worker + tag: "4a17ec9" + pullPolicy: IfNotPresent model: stabilityai/stable-diffusion-xl-base-1.0 gpuCount: 1 modelsPvcSize: 100Gi diff --git a/config/samples/freya_v1alpha1_freyastudio.yaml b/config/samples/freya_v1alpha1_freyastudio.yaml index 2a2edf0..5a10bf9 100644 --- a/config/samples/freya_v1alpha1_freyastudio.yaml +++ b/config/samples/freya_v1alpha1_freyastudio.yaml @@ -60,7 +60,6 @@ spec: # wildcard-dataknife-net-tls (TLS; make kind-tls or gitops cert-sync) # Architecture: Studio/operator/MCP/Ingress in k8s (shared cluster OK); GPU worker on host via URL. # kind is a local dev path — same CRs work production-shaped on shared k8s. See docs/ARCHITECTURE.md. -# Optional style pack sample: freya_v1alpha1_freyastyle.yaml (freya.png NL example) # Public UI: https://freya.dataknife.net — for kind, run ./scripts/kind-hosts.sh # Public MCP (Streamable HTTP): https://freya.dataknife.net/mcp # Cursor MCP config example: diff --git a/config/samples/freya_v1alpha1_freyastyle.yaml b/config/samples/freya_v1alpha1_freyastyle.yaml deleted file mode 100644 index af4d579..0000000 --- a/config/samples/freya_v1alpha1_freyastyle.yaml +++ /dev/null @@ -1,15 +0,0 @@ -# Curated style pack — NL example from freya.png brand art (not SD tag soup) -apiVersion: freya.dataknife.ai/v1alpha1 -kind: FreyaStyle -metadata: - name: freya-winged-warrior - namespace: freya -spec: - displayName: Freya (brand art) - tags: [character, fantasy, wings] - examplePrompt: > - A young woman with large brown eagle wings and fantasy leather armor, - standing in a green canyon with a waterfall behind her - backend: openrouter - openRouterModel: black-forest-labs/flux.2-klein-4b - recommendedSize: "1024x1024" diff --git a/crates/freya-api/Cargo.toml b/crates/freya-api/Cargo.toml index 0cbc9d4..b845c8d 100644 --- a/crates/freya-api/Cargo.toml +++ b/crates/freya-api/Cargo.toml @@ -12,6 +12,7 @@ path = "src/main.rs" [dependencies] anyhow = { workspace = true } axum = { workspace = true } +futures = { workspace = true } base64 = { workspace = true } chrono = { workspace = true } clap = { workspace = true } diff --git a/crates/freya-api/src/civitai.rs b/crates/freya-api/src/civitai.rs index 89b8789..8d325d8 100644 --- a/crates/freya-api/src/civitai.rs +++ b/crates/freya-api/src/civitai.rs @@ -3,6 +3,8 @@ use anyhow::{anyhow, Context, Result}; use serde::{Deserialize, Serialize}; use serde_json::Value; +use std::collections::HashSet; +use tracing::debug; /// Installable weight types Freya surfaces by default (not every Civitai ModelType). pub const DEFAULT_SEARCH_TYPES: &[&str] = &[ @@ -14,6 +16,74 @@ pub const DEFAULT_SEARCH_TYPES: &[&str] = &[ "VAE", ]; +/// One Civitai model type per agent search. `Model` is a file role / Styles bucket, not a type. +pub const AGENT_SEARCH_TYPES: &[&str] = &[ + "LORA", + "LoCon", + "DoRA", + "LyCORIS", + "Checkpoint", + "TextualInversion", + "VAE", +]; + +pub const AGENT_SEARCH_TYPES_LABEL: &str = + "LORA, LoCon, DoRA, LyCORIS, Checkpoint, TextualInversion, VAE"; + +/// Map a tool/UI type word onto one Civitai `types=` value. +/// Embedding is TextualInversion. Model is rejected (not a model type). +pub fn canonical_search_type(raw: &str) -> Result<&'static str, String> { + if raw.contains(',') { + return Err(format!( + "search one type per call. type is one of {AGENT_SEARCH_TYPES_LABEL}. Embedding is TextualInversion. Model is not a Civitai type." + )); + } + let key: String = raw + .chars() + .filter(|c| c.is_ascii_alphanumeric()) + .flat_map(|c| c.to_lowercase()) + .collect(); + if key.is_empty() { + return Err(format!( + "type is required, one of {AGENT_SEARCH_TYPES_LABEL}. Embedding is TextualInversion. Model is not a Civitai type. Call once per type. Does not pin or download." + )); + } + if key == "model" || key == "models" { + return Err( + "Model is not a Civitai model type (file role Model is the weight file; Styles uses Model for untyped files). Search Checkpoint for a base, or one of LORA, LoCon, DoRA, LyCORIS, TextualInversion, VAE." + .into(), + ); + } + let canon = match key.as_str() { + "lora" | "loras" => "LORA", + "locon" => "LoCon", + "dora" => "DoRA", + "lycoris" | "lyco" => "LyCORIS", + "checkpoint" | "checkpoints" => "Checkpoint", + "textualinversion" | "embedding" | "embeddings" => "TextualInversion", + "vae" | "vaes" => "VAE", + _ => { + return Err(format!( + "unknown Civitai type {raw:?}. Search one of {AGENT_SEARCH_TYPES_LABEL}. Embedding is TextualInversion." + )); + } + }; + if !AGENT_SEARCH_TYPES.contains(&canon) { + return Err(format!( + "unknown Civitai type {raw:?}. Search one of {AGENT_SEARCH_TYPES_LABEL}." + )); + } + Ok(canon) +} + +/// True when a Civitai card `type` is the requested agent search type. +pub fn same_search_type(model_type: &str, canon: &str) -> bool { + match canonical_search_type(model_type) { + Ok(got) => got == canon, + Err(_) => false, + } +} + /// True when `model_type` is a Freya-supported installable asset. pub fn is_freya_asset_type(model_type: &str) -> bool { let t = model_type.trim(); @@ -45,6 +115,17 @@ pub struct CivitaiClient { api_key: String, } +/// One page from `GET /api/v1/images`. The next cursor or page is Civitai's, not a local cap. +#[derive(Debug, Clone)] +pub struct CommunityImagePage { + pub items: Vec, + pub next_cursor: Option, + pub next_page: Option, +} + +/// First page is about 20. Civitai accepts up to 200; keep a smaller ceiling. +const COMMUNITY_IMAGE_LIMIT_MAX: u32 = 100; + impl CivitaiClient { pub fn new(api_key: impl Into) -> Self { Self { @@ -57,33 +138,55 @@ impl CivitaiClient { !self.api_key.trim().is_empty() } - pub async fn search(&self, query: &str, limit: u32) -> Result> { - self.search_types(query, limit, DEFAULT_SEARCH_TYPES).await + /// Stream bytes from an allowlisted Civitai image/video CDN URL (follows redirects). + pub async fn fetch_media(&self, url: &str) -> Result<(Vec, String)> { + if !civitai_media_url_ok(url) { + return Err(anyhow!("media url not allowed")); + } + let resp = self + .http + .get(url.trim()) + .send() + .await + .context("civitai media upstream")?; + if !resp.status().is_success() { + return Err(anyhow!("civitai media upstream {}", resp.status())); + } + let ct = resp + .headers() + .get(reqwest::header::CONTENT_TYPE) + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream") + .to_string(); + let bytes = resp.bytes().await.context("civitai media body")?; + Ok((bytes.to_vec(), ct)) + } + + pub async fn search( + &self, + query: &str, + limit: u32, + nsfw: bool, + ) -> Result> { + self.search_types(query, limit, DEFAULT_SEARCH_TYPES, nsfw) + .await } /// Search Civitai, optionally restricting to `types` (passed as repeated `types=` params). + /// `nsfw` sets Civitai's `nsfw` query. False is their SFW catalog; true includes mature models. pub async fn search_types( &self, query: &str, limit: u32, types: &[&str], + nsfw: bool, ) -> Result> { if !self.configured() { return Err(anyhow!( "Civitai API key not set — add it in Freya Settings or CIVITAI_API_KEY" )); } - let mut url = format!( - "https://civitai.com/api/v1/models?limit={limit}&query={}", - urlencoding_lite(query) - ); - for t in types { - let trimmed = t.trim(); - if !trimmed.is_empty() { - url.push_str("&types="); - url.push_str(&urlencoding_lite(trimmed)); - } - } + let url = models_search_url(query, limit, types, nsfw); let v = self.get_json(&url).await.context("civitai search")?; let mut out = Vec::new(); if let Some(items) = v.get("items").and_then(|i| i.as_array()) { @@ -95,7 +198,9 @@ impl CivitaiClient { } /// Full model detail (+ related checkpoints for non-checkpoint assets when baseModel is known). - pub async fn get_model(&self, id: i64) -> Result { + /// `allow_nsfw` is Freya's Show NSFW preference. Recommended resources that are themselves + /// NSFW are omitted when it is off. + pub async fn get_model(&self, id: i64, allow_nsfw: bool) -> Result { if !self.configured() { return Err(anyhow!( "Civitai API key not set — add it in Freya Settings or CIVITAI_API_KEY" @@ -113,8 +218,14 @@ impl CivitaiClient { )); } let mut detail = parse_model_detail(&v); - // Civitai has no first-class dependency graph; use version baseModel → popular checkpoints. - if !detail.model_type.eq_ignore_ascii_case("Checkpoint") { + self.attach_recommended(&mut detail, allow_nsfw).await; + // Public v1 has no dependency graph. When the model lists recommended checkpoints, + // those are the suggestion rows. Otherwise fall back to popular checkpoints for the family. + let has_recommended_ckpt = detail + .recommended_resources + .iter() + .any(|r| r.resource_type.eq_ignore_ascii_case("Checkpoint")); + if !has_recommended_ckpt && !detail.model_type.eq_ignore_ascii_case("Checkpoint") { if let Some(base) = detail .base_model .as_deref() @@ -122,10 +233,8 @@ impl CivitaiClient { { match self.related_checkpoints(base, 4).await { Ok(related) => { - detail.related = related - .into_iter() - .filter(|c| c.id != detail.id) - .collect(); + detail.related = + related.into_iter().filter(|c| c.id != detail.id).collect(); if detail.needs_base.is_none() { detail.needs_base = Some(format!("Needs base model family: {base}")); } @@ -139,13 +248,20 @@ impl CivitaiClient { Ok(detail) } - async fn related_checkpoints(&self, base_model: &str, limit: u32) -> Result> { + async fn related_checkpoints( + &self, + base_model: &str, + limit: u32, + ) -> Result> { let url = format!( "https://civitai.com/api/v1/models?limit={limit}&types=Checkpoint&baseModels={}&sort={}", urlencoding_lite(base_model), urlencoding_lite("Most Downloaded") ); - let v = self.get_json(&url).await.context("civitai related checkpoints")?; + let v = self + .get_json(&url) + .await + .context("civitai related checkpoints")?; let mut out = Vec::new(); if let Some(items) = v.get("items").and_then(|i| i.as_array()) { for item in items { @@ -160,6 +276,7 @@ impl CivitaiClient { &self, version_id: i64, file_id: Option, + file_hash: Option<&str>, ) -> Result { if !self.configured() { return Err(anyhow!( @@ -188,14 +305,16 @@ impl CivitaiClient { .iter() .find(|f| f.id == Some(fid)) .or_else(|| pick_primary_file(&version.files)) + } else if let Some(hash) = file_hash.and_then(hash_token) { + pick_file_by_hash(&version.files, &hash) + .or_else(|| pick_primary_file(&version.files)) } else { pick_primary_file(&version.files) } .ok_or_else(|| anyhow!("civitai model version {version_id}: no files"))?; - let download_url = file - .download_url - .clone() - .ok_or_else(|| anyhow!("civitai model version {version_id}: file has no downloadUrl"))?; + let download_url = file.download_url.clone().ok_or_else(|| { + anyhow!("civitai model version {version_id}: file has no downloadUrl") + })?; Ok(ResolvedDownload { download_url, version_id: version.id, @@ -213,7 +332,11 @@ impl CivitaiClient { } /// Resolve a version id → full model detail (for Installed cards that only have versionId). - pub async fn get_model_by_version(&self, version_id: i64) -> Result { + pub async fn get_model_by_version( + &self, + version_id: i64, + allow_nsfw: bool, + ) -> Result { if !self.configured() { return Err(anyhow!( "Civitai API key not set — add it in Freya Settings or CIVITAI_API_KEY" @@ -237,13 +360,9 @@ impl CivitaiClient { .get("modelId") .and_then(|x| x.as_i64()) .ok_or_else(|| anyhow!("civitai model version {version_id}: missing modelId"))?; - let mut detail = self.get_model(model_id).await?; + let mut detail = self.get_model(model_id, allow_nsfw).await?; // Prefer the installed version when present on the model. - if detail - .model_versions - .iter() - .any(|ver| ver.id == version_id) - { + if detail.model_versions.iter().any(|ver| ver.id == version_id) { if let Some(ver) = detail .model_versions .iter() @@ -271,15 +390,330 @@ impl CivitaiClient { detail.file_format = file.format.clone().or_else(|| file.file_type.clone()); detail.download_url = file.download_url.clone(); } + detail.recommended_resources = ver.recommended_resources.clone(); + if let Some(url) = detail.civitai_url.clone() { + detail.civitai_url = Some(with_version_query(&url, ver.id)); + } } } Ok(detail) } + /// `GET /api/v1/models/{id}` omits `recommendedResources`. Civitai MCP `get_model` and + /// `get_model_version` wrap that same REST document and do not return the list either. + /// `model.getById` on tRPC does. Failures leave the detail usable — we never invent a + /// resource that was not in that payload. + async fn attach_recommended(&self, detail: &mut CivitaiModelDetail, allow_nsfw: bool) { + let mut any = false; + for ver in &mut detail.model_versions { + ver.recommended_resources = filter_recommended(&ver.recommended_resources, allow_nsfw); + if !ver.recommended_resources.is_empty() { + any = true; + } + } + if !any && detail.id > 0 { + match self.fetch_trpc_recommended(detail.id).await { + Ok(rows) => { + for ver in &mut detail.model_versions { + if let Some((_, list)) = rows.iter().find(|(id, _)| *id == ver.id) { + ver.recommended_resources = filter_recommended(list, allow_nsfw); + } + } + } + Err(err) => debug!("recommended resources skipped: {err}"), + } + } + detail.recommended_resources = detail + .model_versions + .iter() + .find(|ver| Some(ver.id) == detail.version_id) + .map(|ver| ver.recommended_resources.clone()) + .unwrap_or_default(); + } + + async fn fetch_trpc_recommended( + &self, + model_id: i64, + ) -> Result)>> { + let input = format!(r#"{{"json":{{"id":{model_id}}}}}"#); + let url = format!( + "https://civitai.com/api/trpc/model.getById?input={}", + urlencoding_lite(&input) + ); + let resp = self + .http + .get(&url) + .timeout(std::time::Duration::from_secs(8)) + .header("Authorization", format!("Bearer {}", self.api_key)) + .send() + .await + .context("civitai recommended resources")?; + let status = resp.status(); + let text = resp.text().await.unwrap_or_default(); + if !status.is_success() { + return Err(anyhow!("civitai recommended resources: {status}")); + } + let v: Value = serde_json::from_str(&text).context("civitai recommended resources json")?; + let versions = v + .pointer("/result/data/json/modelVersions") + .and_then(|x| x.as_array()) + .cloned() + .unwrap_or_default(); + Ok(versions + .iter() + .filter_map(|ver| { + let id = ver.get("id").and_then(|x| x.as_i64()).unwrap_or(0); + let list = parse_recommended_resources(ver); + if id > 0 && !list.is_empty() { + Some((id, list)) + } else { + None + } + }) + .collect()) + } + + /// One version payload, including example-image meta. Does not walk related models. + pub async fn version_example(&self, version_id: i64) -> Result { + if !self.configured() { + return Err(anyhow!( + "Civitai API key not set — add it in Freya Settings or CIVITAI_API_KEY" + )); + } + let url = format!("https://civitai.com/api/v1/model-versions/{version_id}"); + let v = self + .get_json_timeout(&url, std::time::Duration::from_secs(8)) + .await + .context("civitai get model version meta")?; + if v.get("error").is_some() { + return Err(anyhow!( + "civitai model version {}: {}", + version_id, + v.get("error") + .and_then(|e| e.as_str()) + .unwrap_or("not found") + )); + } + let ver = parse_model_version(&v, 12); + let model_name = v + .pointer("/model/name") + .and_then(|n| n.as_str()) + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_string); + Ok(VersionExample { + version_id: ver.id, + version_name: ver.name, + model_name, + base_model: ver.base_model, + example: ver.example_meta, + }) + } + + /// Community posts made with a model or version. + /// + /// `search_images` / `get_image` on `https://mcp.civitai.com/mcp` are public reads, but the + /// tool result keeps only image id, post id, and version ids. The text prompt is cut to + /// 120 characters and omits negative, sampler, steps, CFG, seed, and resources. `get_image` + /// looks at `meta.prompt`, while `GET /images?imageId=` nests that object under `meta.meta`, + /// so the prompt is dropped. Those tools also have no NSFW argument: browsing level follows + /// the API key only when Cloudflare country headers are present, which this server does not + /// invent. The images list with `withMeta=true` is the payload that has the fields, and + /// `nsfw` / `browsingLevel` is how Show NSFW is asked. No API key: the read is public. + /// File download URLs stay on the version REST used by install. + pub async fn community_images( + &self, + model_id: Option, + version_id: Option, + allow_nsfw: bool, + limit: u32, + cursor: Option<&str>, + page: Option, + ) -> Result { + let model_id = model_id.filter(|n| *n > 0); + let version_id = version_id.filter(|n| *n > 0); + if model_id.is_none() && version_id.is_none() { + return Err(anyhow!("modelId or modelVersionId is required")); + } + let limit = limit.clamp(1, COMMUNITY_IMAGE_LIMIT_MAX); + let cursor = clean_image_cursor(cursor); + let page = if cursor.is_some() { + None + } else { + page.filter(|n| *n > 0 && *n <= 10_000) + }; + let url = images_list_url( + model_id, + version_id, + allow_nsfw, + limit, + cursor.as_deref(), + page, + ); + let v = self + .get_public_json(&url) + .await + .context("civitai community images")?; + let mut items = parse_community_images_limited(&v, version_id, allow_nsfw, limit as usize); + items = dedupe_community_images(items); + self.fill_resource_ids(&mut items).await; + let (next_cursor, next_page) = if items.is_empty() { + (None, None) + } else { + images_next(&v) + }; + Ok(CommunityImagePage { + items, + next_cursor, + next_page, + }) + } + + /// Fill Civitai version ids for generation resources that only named a hash, + /// and names for version ids that arrived without one. A miss stays as a + /// filename or hash — callers must not invent a download for those. + async fn fill_resource_ids(&self, images: &mut [CommunityImage]) { + let mut hashes = Vec::new(); + for image in images.iter() { + for resource in &image.resources { + if resource.model_version_id.is_some_and(|n| n > 0) { + continue; + } + let Some(hash) = resource.hash.clone() else { + continue; + }; + if !hashes.iter().any(|h: &String| h == &hash) { + hashes.push(hash); + } + } + } + hashes.truncate(24); + for chunk in hashes.chunks(4) { + let pending = chunk.iter().cloned().map(|hash| { + let client = self.clone(); + async move { + let found = client.version_by_hash(&hash).await.ok(); + (hash, found) + } + }); + for (hash, found) in futures::future::join_all(pending).await { + let Some(found) = found else { + continue; + }; + for image in images.iter_mut() { + for resource in &mut image.resources { + if resource.hash.as_deref() == Some(hash.as_str()) + && resource.model_version_id.is_none() + { + apply_resolved_version(resource, &found); + } + } + } + } + } + + let mut version_ids = Vec::new(); + for image in images.iter() { + for resource in &image.resources { + if !resource.name.trim().is_empty() { + continue; + } + let Some(id) = resource.model_version_id.filter(|n| *n > 0) else { + continue; + }; + if !version_ids.contains(&id) { + version_ids.push(id); + } + } + } + version_ids.truncate(24); + for chunk in version_ids.chunks(4) { + let pending = chunk.iter().copied().map(|id| { + let client = self.clone(); + async move { + let found = client.version_by_id_brief(id).await.ok(); + (id, found) + } + }); + for (id, found) in futures::future::join_all(pending).await { + let Some(found) = found else { + continue; + }; + for image in images.iter_mut() { + for resource in &mut image.resources { + if resource.model_version_id == Some(id) && resource.name.trim().is_empty() + { + apply_resolved_version(resource, &found); + } + } + } + } + } + } + + async fn version_by_hash(&self, hash: &str) -> Result { + let hash = hash_token(hash).ok_or_else(|| anyhow!("bad civitai hash"))?; + let url = format!("https://civitai.com/api/v1/model-versions/by-hash/{hash}"); + let v = self.catalog_json(&url).await?; + parse_resolved_version(&v).ok_or_else(|| anyhow!("civitai hash {hash}: not a version")) + } + + async fn version_by_id_brief(&self, version_id: i64) -> Result { + let url = format!("https://civitai.com/api/v1/model-versions/{version_id}"); + let v = self.catalog_json(&url).await?; + parse_resolved_version(&v) + .ok_or_else(|| anyhow!("civitai version {version_id}: unreadable")) + } + + /// Public catalog first. Retry with the API key only when the public read + /// is refused, so a 404 does not wait on a second call. + async fn catalog_json(&self, url: &str) -> Result { + let timeout = std::time::Duration::from_secs(8); + match self.get_public_json_timeout(url, timeout).await { + Ok(v) => Ok(v), + Err(err) if self.configured() && catalog_retry_with_key(&err) => { + self.get_json_timeout(url, timeout).await + } + Err(err) => Err(err), + } + } + + /// Latest version's primary file. Used when a generation resource has a model id only. + pub async fn resolve_model_download(&self, model_id: i64) -> Result { + if !self.configured() { + return Err(anyhow!( + "Civitai API key not set — add it in Freya Settings or CIVITAI_API_KEY" + )); + } + let url = format!("https://civitai.com/api/v1/models/{model_id}"); + let v = self.get_json(&url).await.context("civitai get model")?; + if v.get("error").is_some() { + return Err(anyhow!( + "civitai model {}: {}", + model_id, + v.get("error") + .and_then(|e| e.as_str()) + .unwrap_or("not found") + )); + } + let detail = parse_model_detail(&v); + let version_id = detail + .version_id + .ok_or_else(|| anyhow!("civitai model {model_id}: no version"))?; + self.resolve_version_download(version_id, detail.file_id, None) + .await + } + async fn get_json(&self, url: &str) -> Result { + self.get_json_timeout(url, std::time::Duration::from_secs(30)) + .await + } + + async fn get_json_timeout(&self, url: &str, timeout: std::time::Duration) -> Result { let resp = self .http .get(url) + .timeout(timeout) .header("Authorization", format!("Bearer {}", self.api_key)) .send() .await @@ -291,6 +725,34 @@ impl CivitaiClient { } serde_json::from_str(&text).context("civitai json") } + + /// Public catalog read. Omits `Authorization` so an account browsing level cannot + /// override the explicit `nsfw` / `browsingLevel` query. + async fn get_public_json(&self, url: &str) -> Result { + self.get_public_json_timeout(url, std::time::Duration::from_secs(20)) + .await + } + + async fn get_public_json_timeout( + &self, + url: &str, + timeout: std::time::Duration, + ) -> Result { + let resp = self + .http + .get(url) + .timeout(timeout) + .header("Accept", "application/json") + .send() + .await + .context("civitai http")?; + let status = resp.status(); + let text = resp.text().await.unwrap_or_default(); + if !status.is_success() { + return Err(anyhow!("civitai {status}: {text}")); + } + serde_json::from_str(&text).context("civitai json") + } } /// Download target resolved from a version (+ optional file) id. @@ -342,6 +804,15 @@ fn parse_model_file(f: &Value) -> CivitaiModelFile { .get("type") .and_then(|x| x.as_str()) .map(|s| s.to_string()); + let hashes = f + .get("hashes") + .and_then(|h| h.as_object()) + .map(|obj| { + obj.iter() + .filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string()))) + .collect() + }) + .unwrap_or_default(); CivitaiModelFile { id: f.get("id").and_then(|x| x.as_i64()), name: f @@ -357,7 +828,129 @@ fn parse_model_file(f: &Value) -> CivitaiModelFile { .get("downloadUrl") .and_then(|u| u.as_str()) .map(|s| s.to_string()), + hashes, + } +} + +fn civitai_model_page(id: i64, version_id: Option, nsfw: bool) -> String { + let host = if nsfw { + "https://civitai.red" + } else { + "https://civitai.com" + }; + match version_id { + Some(v) if v > 0 => format!("{host}/models/{id}?modelVersionId={v}"), + _ => format!("{host}/models/{id}"), + } +} + +fn with_version_query(url: &str, version_id: i64) -> String { + let base = url.split('?').next().unwrap_or(url); + if version_id > 0 { + format!("{base}?modelVersionId={version_id}") + } else { + base.to_string() + } +} + +fn value_is_nsfw(v: &Value) -> bool { + v.get("nsfw").and_then(|x| x.as_bool()).unwrap_or(false) + || v.get("nsfwLevel") + .and_then(|x| x.as_i64()) + .map(|n| n > 1) + .unwrap_or(false) +} + +/// Map Civitai `recommendedResources` (nested `model.getById` shape, or a flat +/// `{id,name,type,modelVersionId,baseModel}` object) onto the detail payload. +/// Does not add resources that are absent from the object. +fn parse_recommended_resources(ver: &Value) -> Vec { + let Some(arr) = ver.get("recommendedResources").and_then(|v| v.as_array()) else { + return Vec::new(); + }; + let mut out = Vec::new(); + for item in arr { + if let Some(rec) = parse_recommended_resource(item) { + let key = (rec.id, rec.model_version_id); + if !out + .iter() + .any(|e: &CivitaiRecommendedResource| (e.id, e.model_version_id) == key) + { + out.push(rec); + } + } + } + out +} + +fn parse_recommended_resource(item: &Value) -> Option { + if let Some(model) = item.get("model").filter(|m| m.get("id").is_some()) { + let id = model.get("id").and_then(|x| x.as_i64())?; + let name = model + .get("name") + .and_then(|x| x.as_str()) + .map(str::trim) + .filter(|s| !s.is_empty())?; + let resource_type = model + .get("type") + .and_then(|x| x.as_str()) + .filter(|s| !s.is_empty()) + .unwrap_or("Checkpoint") + .to_string(); + let model_version_id = item + .get("modelVersionId") + .and_then(|x| x.as_i64()) + .or_else(|| item.get("id").and_then(|x| x.as_i64())); + let base_model = item + .get("baseModel") + .and_then(|x| x.as_str()) + .or_else(|| model.get("baseModel").and_then(|x| x.as_str())) + .map(|s| s.to_string()); + return Some(CivitaiRecommendedResource { + id, + name: name.to_string(), + resource_type, + model_version_id, + base_model, + nsfw: value_is_nsfw(model) || value_is_nsfw(item), + }); } + let id = item + .get("id") + .and_then(|x| x.as_i64()) + .or_else(|| item.get("modelId").and_then(|x| x.as_i64()))?; + let name = item + .get("name") + .and_then(|x| x.as_str()) + .map(str::trim) + .filter(|s| !s.is_empty())?; + let resource_type = item + .get("type") + .and_then(|x| x.as_str()) + .filter(|s| !s.is_empty()) + .unwrap_or("Checkpoint") + .to_string(); + Some(CivitaiRecommendedResource { + id, + name: name.to_string(), + resource_type, + model_version_id: item.get("modelVersionId").and_then(|x| x.as_i64()), + base_model: item + .get("baseModel") + .and_then(|x| x.as_str()) + .map(|s| s.to_string()), + nsfw: value_is_nsfw(item), + }) +} + +fn filter_recommended( + list: &[CivitaiRecommendedResource], + allow_nsfw: bool, +) -> Vec { + list.iter() + .filter(|r| allow_nsfw || !r.nsfw) + .cloned() + .collect() } fn parse_model_version(ver: &Value, image_limit: usize) -> CivitaiModelVersion { @@ -369,7 +962,8 @@ fn parse_model_version(ver: &Value, image_limit: usize) -> CivitaiModelVersion { .unwrap_or_default(); let mut image_urls = Vec::new(); let mut example_prompt = None; - if let Some(images) = ver.get("images").and_then(|i| i.as_array()) { + let images = ver.get("images").and_then(|i| i.as_array()); + if let Some(images) = images { for img in images.iter().take(image_limit) { if let Some(u) = img.get("url").and_then(|u| u.as_str()) { image_urls.push(u.to_string()); @@ -382,6 +976,10 @@ fn parse_model_version(ver: &Value, image_limit: usize) -> CivitaiModelVersion { } } } + let example_meta = ver + .get("images") + .and_then(|i| i.as_array()) + .and_then(|images| crate::genmeta::example_from_images(images.iter().take(24))); CivitaiModelVersion { id: ver.get("id").and_then(|x| x.as_i64()).unwrap_or(0), name: ver @@ -409,14 +1007,21 @@ fn parse_model_version(ver: &Value, image_limit: usize) -> CivitaiModelVersion { Some(image_urls) }, example_prompt, + example_meta, + recommended_resources: parse_recommended_resources(ver), } } fn pick_primary_file(files: &[CivitaiModelFile]) -> Option<&CivitaiModelFile> { - files - .iter() - .find(|f| f.primary) - .or_else(|| files.first()) + files.iter().find(|f| f.primary).or_else(|| files.first()) +} + +fn pick_file_by_hash<'a>(files: &'a [CivitaiModelFile], hash: &str) -> Option<&'a CivitaiModelFile> { + files.iter().find(|f| { + f.hashes + .values() + .any(|h| hashes_match(h, hash)) + }) } fn parse_model_card(item: &Value, detailed: bool) -> CivitaiModelCard { @@ -511,12 +1116,9 @@ fn parse_model_card(item: &Value, detailed: bool) -> CivitaiModelCard { None }; + let nsfw_level = item.get("nsfwLevel").and_then(|x| x.as_i64()); let nsfw = item.get("nsfw").and_then(|x| x.as_bool()).unwrap_or(false) - || item - .get("nsfwLevel") - .and_then(|x| x.as_i64()) - .map(|n| n > 1) - .unwrap_or(false) + || nsfw_level.map(|n| n > 1).unwrap_or(false) || crate::prefs::looks_nsfw_label(&name); CivitaiModelCard { @@ -548,8 +1150,9 @@ fn parse_model_card(item: &Value, detailed: bool) -> CivitaiModelCard { } else { Some(image_urls) }, - civitai_url: Some(format!("https://civitai.com/models/{id}")), + civitai_url: Some(civitai_model_page(id, version_id, nsfw)), nsfw, + nsfw_level, model_versions, } } @@ -584,8 +1187,16 @@ fn parse_model_detail(item: &Value) -> CivitaiModelDetail { thumbs_up: card.thumbs_up, image_urls: card.image_urls, civitai_url: card.civitai_url, + nsfw: card.nsfw, + nsfw_level: card.nsfw_level, needs_base, - model_versions: card.model_versions, + model_versions: card.model_versions.clone(), + recommended_resources: card + .model_versions + .iter() + .find(|ver| Some(ver.id) == card.version_id) + .map(|ver| ver.recommended_resources.clone()) + .unwrap_or_default(), related: Vec::new(), } } @@ -611,17 +1222,979 @@ fn strip_html_brief(html: &str) -> String { } } -fn urlencoding_lite(s: &str) -> String { - // Percent-encode UTF-8 bytes (not truncated chars) for non-ASCII queries. - let mut out = String::with_capacity(s.len() * 3); - for &b in s.as_bytes() { - match b { - b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { - out.push(b as char); - } - b' ' => out.push_str("%20"), - _ => out.push_str(&format!("%{b:02X}")), - } +/// Community images for one model or version. +/// +/// Show NSFW off: `nsfw=false` and browsing level 1 (PG). On: browsing level 31 +/// (PG through XXX) so mature posts are included. `nsfw=true` on this endpoint +/// returns only mature posts, which would hide SFW examples of the same version. +fn images_list_url( + model_id: Option, + version_id: Option, + allow_nsfw: bool, + limit: u32, + cursor: Option<&str>, + page: Option, +) -> String { + let limit = limit.clamp(1, COMMUNITY_IMAGE_LIMIT_MAX); + let mut url = + format!("https://civitai.com/api/v1/images?limit={limit}&withMeta=true&type=image"); + if allow_nsfw { + url.push_str("&browsingLevel=31"); + } else { + url.push_str("&nsfw=false&browsingLevel=1"); + } + if let Some(id) = model_id { + url.push_str(&format!("&modelId={id}")); + } + if let Some(id) = version_id { + url.push_str(&format!("&modelVersionId={id}")); + } + if let Some(cursor) = clean_image_cursor(cursor) { + url.push_str("&cursor="); + url.push_str(&urlencoding_lite(&cursor)); + } else if let Some(page) = page.filter(|n| *n > 0 && *n <= 10_000) { + url.push_str(&format!("&page={page}")); + } + url +} + +fn parse_community_images( + payload: &Value, + context_version: Option, + allow_nsfw: bool, +) -> Vec { + parse_community_images_limited( + payload, + context_version, + allow_nsfw, + COMMUNITY_IMAGE_LIMIT_MAX as usize, + ) +} + +fn parse_community_images_limited( + payload: &Value, + context_version: Option, + allow_nsfw: bool, + limit: usize, +) -> Vec { + let Some(items) = payload.get("items").and_then(|i| i.as_array()) else { + return Vec::new(); + }; + let limit = limit.clamp(1, COMMUNITY_IMAGE_LIMIT_MAX as usize); + let mut out = Vec::new(); + for item in items { + if item.get("type").and_then(|t| t.as_str()) == Some("video") { + let has_url = item + .get("url") + .and_then(|u| u.as_str()) + .map(|s| s.starts_with("https://")) + .unwrap_or(false); + if !has_url { + continue; + } + } + let nsfw = image_is_nsfw(item); + if nsfw && !allow_nsfw { + continue; + } + let Some(image) = parse_community_image(item, context_version, nsfw) else { + continue; + }; + out.push(image); + if out.len() >= limit { + break; + } + } + out +} + +fn clean_image_cursor(cursor: Option<&str>) -> Option { + let raw = cursor?.trim(); + if raw.is_empty() || raw.len() > 512 { + return None; + } + if raw.chars().any(|c| c.is_control() || c.is_whitespace()) { + return None; + } + Some(raw.to_string()) +} + +/// `metadata.nextCursor`, or `cursor` / `page` on `metadata.nextPage`. +fn images_next(payload: &Value) -> (Option, Option) { + let Some(meta) = payload.get("metadata") else { + return (None, None); + }; + let cursor = match meta.get("nextCursor") { + Some(Value::String(s)) => clean_image_cursor(Some(s)), + Some(Value::Number(n)) => n.as_i64().filter(|n| *n >= 0).map(|n| n.to_string()), + _ => None, + }; + let next_url = meta.get("nextPage").and_then(|v| v.as_str()).unwrap_or(""); + let cursor = cursor + .or_else(|| query_param(next_url, "cursor").and_then(|s| clean_image_cursor(Some(&s)))); + if cursor.is_some() { + return (cursor, None); + } + let page = query_param(next_url, "page") + .and_then(|s| s.parse::().ok()) + .filter(|n| *n > 0 && *n <= 10_000); + (None, page) +} + +fn query_param(url: &str, key: &str) -> Option { + let parsed = reqwest::Url::parse(url).ok()?; + parsed + .query_pairs() + .find(|(k, _)| k == key) + .map(|(_, v)| v.into_owned()) +} + +/// Grid preview. The original `url` stays the download and the detail image. +fn civitai_preview_url(url: &str) -> String { + if civitai_video_url(url) { + return url.to_string(); + } + if let Some(start) = url.find("/width=") { + let after = &url[start + "/width=".len()..]; + if let Some(slash) = after.find('/') { + let mut out = String::with_capacity(url.len() + 8); + out.push_str(&url[..start]); + out.push_str("/width=768"); + out.push_str(&after[slash..]); + return out; + } + } + url.replace("/original=true/", "/width=768/") +} + +fn civitai_video_url(url: &str) -> bool { + let u = url.to_ascii_lowercase(); + u.contains(".mp4") || u.contains(".webm") || u.contains(".mov") +} + +/// Stable dedupe key: same Civitai file with thumbnail vs original paths counts once. +pub fn canonical_community_media_key(raw: Option<&str>) -> Option { + let s = raw?.trim(); + if s.is_empty() || !s.starts_with("https://") { + return None; + } + let parsed = reqwest::Url::parse(s).ok()?; + let host = parsed.host_str()?.to_ascii_lowercase(); + if !civitai_media_host_ok(&host) { + return None; + } + let path = parsed + .path() + .replace("/width=768/", "/original=true/") + .replace("/width=512/", "/original=true/"); + let file = path.rsplit('/').next()?.trim(); + if file.is_empty() { + return None; + } + Some(format!("{host}/{file}").to_ascii_lowercase()) +} + +pub fn civitai_media_host_ok(host: &str) -> bool { + let h = host.trim().to_ascii_lowercase(); + h == "image.civitai.com" + || h == "image.civitai.red" + || h == "blobs-b2.civitai.com" + || h.ends_with(".image.civitai.com") +} + +/// Allowlisted Civitai CDN hosts for studio media proxy (`