cloudaiman commited on
Commit
bd2cfbf
·
verified ·
1 Parent(s): 91c027b

Publish CSD LDA-only artist pack and standalone author/image search

Browse files
DATA-NOTICE.txt ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Style Scout CSD LDA — data and third-party notice (2026-10-25)
2
+
3
+ This numerical retrieval pack aggregates CSD image descriptors from the pinned
4
+ nyanko-devs/danbooru2026 archive (ebb02a630201c7b51487e45fb90b3fcf4cbedc20).
5
+ Its repository card declares MIT. That label is not treated as proof of clearance
6
+ of the copyrights, privacy rights or other rights in every underlying work.
7
+ No blanket MIT/CC0 license is asserted for these aggregate artist coordinates.
8
+ Images and individual image descriptors are not redistributed here.
9
+
10
+ CSD ViT-L: tomg-group-umd/CSD-ViT-L,
11
+ revision 5bc26a6fb0487f3f00a2a7313135103a005b1b67.
12
+ Model card: CC BY 4.0, https://creativecommons.org/licenses/by/4.0/
13
+ Citation: Gowthami Somepalli, Anubhav Gupta, Kamal Gupta, Shramay Palta,
14
+ Micah Goldblum, Jonas Geiping, Abhinav Shrivastava, Tom Goldstein.
15
+ Measuring Style Similarity in Diffusion Models (2024), arXiv:2404.01292.
16
+ https://github.com/learn2phoenix/CSD
17
+ Weights are downloaded from the official pinned repository, not rehosted.
18
+ The loader selects the visual backbone and trained style projection; weights
19
+ are not retrained. LDA and artist aggregation are additions by this project.
20
+ The official repository warns of differences between released weights and paper
21
+ results. No endorsement by CSD authors or depicted artists is implied.
22
+
23
+ The packaged CLIP architecture and CSD adapter attribution/license notices are
24
+ in vendor/CLIP-LICENSE and vendor/CSD-LICENSE. Independent code uses LICENSE-CODE.
25
+ That code license does not license the feature pack or underlying artwork.
26
+ Danbooru/Pixiv/Twitter links are public metadata, not identity verification.
27
+
28
+ Rights holders may contact cloudaiman through the Hugging Face repository
29
+ Community. Removal requests will be reviewed. Attribution and a removal policy
30
+ are not substitutes for permission; third-party downloaded copies cannot be
31
+ recalled. Check applicable rights before redistribution or downstream use.
LICENSE-CODE ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2026 cloudaiman
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
23
+ Scope: independent code only. Does not cover features/, third-party model
24
+ weights, or underlying artwork. See DATA-NOTICE.txt and vendor licenses.
README.md ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ pretty_name: Style Scout CSD — LDA Artist Similarity Search
3
+ language:
4
+ - ja
5
+ - en
6
+ task_categories:
7
+ - feature-extraction
8
+ size_categories:
9
+ - 10K<n<100K
10
+ tags:
11
+ - csd
12
+ - lda
13
+ - art
14
+ - anime
15
+ - image-retrieval
16
+ - style-similarity
17
+ ---
18
+
19
+ # Style Scout CSD — LDA
20
+
21
+ **62,051作者のCSD特徴をLDA空間で比較する、ローカル画風検索ツールです。**
22
+ 作者名、画像ファイル、画像フォルダから類似作者を検索できます。
23
+ **LDAのみ使用します。PLDA・SVD・一般タグの除外射影は使いません。**
24
+ 従来のDINOv3/SVD版とは別のデータセットで、互換性はありません。
25
+
26
+ ## 1本のスクリプトから起動
27
+
28
+ Python 3.10以上が必要です(推奨3.12)。Python本体は事前にインストールしてください。
29
+ macOS / Linux:
30
+
31
+ ```bash
32
+ curl -fL https://huggingface.co/datasets/cloudaiman/style-scout-csd-lda/resolve/main/run.sh -o run.sh
33
+ chmod +x run.sh
34
+ ./run.sh --artist mochizuki_kei
35
+ ```
36
+
37
+ `run.sh` はPythonスクリプトです。`python3 run.sh ...` でも起動できます。
38
+ Windowsでは [run_style_scout_csd.py](run_style_scout_csd.py) をダウンロードして
39
+ `py run_style_scout_csd.py --artist mochizuki_kei` と実行してください。
40
+ macOSで実測検証済み。Windows/Linuxはこのリリースで実機検証していません。
41
+
42
+ ```bash
43
+ # 作者名はDanbooruの完全一致タグ。括弧や = を含む場合は引用符で囲む
44
+ ./run.sh --artist 'dino_(dinoartforame)'
45
+ ./run.sh --artist '1=2' --artist nixeu
46
+
47
+ # 画像1枚、複数ファイル、フォルダ(サブフォルダも再帰的に探索)
48
+ ./run.sh --images '/path/to/picture.png'
49
+ ./run.sh --images '/path/to/a.jpg' '/path/to/b.webp'
50
+ ./run.sh --images '/path/to/reference-folder'
51
+
52
+ # 結果のブラウザ表示を止める/プロフィールAPIを呼ばない
53
+ ./run.sh --artist mochizuki_kei --no-open
54
+ ./run.sh --artist mochizuki_kei --no-links
55
+
56
+ # 初期表示で32枚以上の作者に絞る(変換行列は再計算しない)
57
+ ./run.sh --artist mochizuki_kei --min-count 32 --top 20
58
+
59
+ # Mac GPU自動選択。明示指定も可能
60
+ ./run.sh --images '/path/to/folder' --device mps
61
+ ./run.sh --images '/path/to/folder' --device cpu
62
+ # NVIDIA環境(適切なCUDA版PyTorchが必要)
63
+ ./run.sh --images '/path/to/folder' --device cuda
64
+
65
+ # 保存済みCSD重みを利用
66
+ ./run.sh --images '/path/to/folder' --model-dir '/path/to/csd-vit-l'
67
+ ```
68
+
69
+ ### 初回に行うこと
70
+
71
+ 1. `~/style-scout-csd/.venv` に専用の仮想環境を作る。手動のactivateは不要。
72
+ 2. 必要なライブラリと、約182MBの作者特徴量パックをダウンロードする。
73
+ 3. 画像検索を指定したときだけPyTorch等とCSD ViT-Lの公式重み(約2.4GB)を取得する。
74
+ 4. 検索結果を**実行場所の `./results/<日時>/`** に保存し、HTMLを自動で開く。
75
+
76
+ `--install-dir` で仮想環境の場所、`--cache-dir` で画像特徴・リンク・CSDモデルの
77
+ キャッシュ先を変えられます。特徴量パックと実行コードはHugging Faceの標準キャッシュを利用します。
78
+ `--output DIR` は結果保存先を指定します。既存ディレクトリは上書きしません。
79
+
80
+ 起動時は公開 `release.json` から検証済みコミットを選び、固定リビジョンでコードとパックを取得して
81
+ SHA-256を確認します。同じバージョンはキャッシュを再利用します。
82
+ このCSD版ランチャーは公開リリース情報を毎回確認します。旧DINOv3版ランチャーはCSDへ自動移行しません。
83
+ 通信不能なら保存済みのリリース情報を使います。`--offline` は初期セットアップ後に使えます。
84
+ 画像検索の完全オフライン実行にはCSD重みまたは対象画像の特徴キャッシュも必要です。
85
+
86
+ 作者名検索だけならPyTorch・GPU・CSD重みは不要です。初回のネットワーク接続は
87
+ パック取得と、指定に応じたモデル・プロフィールメタデータ取得に限ります。
88
+ **入力画像は端末外へアップロードしません。画像生成APIも呼びません。**
89
+
90
+ ## 出力
91
+
92
+ - `report.html`: LDA上位ランキング、距離グラフ、採用枚数フィルター
93
+ (全作者/8・16・32・64枚以上)、Danbooru・Pixiv・Twitter/Xのリンク。
94
+ - `results.json`: 距離、採用枚数、参照条件、使用パックのハッシュとリンク。
95
+ - 標準出力: 順位・作者名・距離・枚数と、HTMLのURL1本。長いSNS URLは並べません。
96
+
97
+ HTMLには画像もサムネイルも含みません。取得済みのHTMLはネット接続なしで読めます。
98
+ SNSリンクはDanbooruに登録された公開プロフィールだけを使い、7日間キャッシュします。
99
+ 未登録・取得失敗・古いキャッシュは区別して表示します。リンク先の現在の所有者は保証しません。
100
+ `--no-links` ならDanbooru検索リンクだけを作成します。
101
+
102
+ ## ��学的な処理
103
+
104
+ 画像ごとにCSDの768次元特徴をL2正規化して $x_i$ とします。
105
+ 作家平均は $\mu_a = n_a^{-1}\sum_i x_i$。**この平均は再正規化しません。**
106
+
107
+ 作家を等しく重み付けした中心化共分散を用います。
108
+
109
+ $$S_w = \frac1A\sum_a\left(\frac1{n_a}\sum_i x_i x_i^T-\mu_a\mu_a^T\right),\qquad
110
+ S_b=\frac1A\sum_a(\mu_a-\bar\mu)(\mu_a-\bar\mu)^T.$$
111
+
112
+ $$S_w^{-1/2}S_bS_w^{-1/2}=V\Lambda V^T,\qquad W=V^TS_w^{-1/2},\qquad u_a=W(\mu_a-\bar\mu).$$
113
+
114
+ 画像集合の検索は、各画像のCSD特徴を平均した $\mu_q$ を同じ変換に通します。
115
+ 順位は $\|W(\mu_q-\bar\mu)-u_a\|_2$ の昇順です。作者名検索は保存済み $u_a$ を使い、本人を除きます。
116
+ 距離は一致率・確率ではありません。
117
+
118
+ 768軸、shrinkage=0、固有値floorは作家内共分散の平均固有値の $10^{-6}$ 倍です。
119
+ 旧実験の共通変換を再利用しています。設定は14 validation作者・360枚で、歴史的にはPLDAの
120
+ macro MRRにより選択されたものです。**この配布版はLDAだけを実行し、LDA専用に設定を最適化し直したものではありません。**
121
+ テスト用クイズでのパラメータ選択はしていません。
122
+
123
+ ## CSD抽出と互換性
124
+
125
+ [Somepalli et al., Measuring Style Similarity in Diffusion Models (2024)](https://arxiv.org/abs/2404.01292) の
126
+ [CSD ViT-L](https://huggingface.co/tomg-group-umd/CSD-ViT-L) を使用。
127
+ リビジョン `5bc26a6fb0487f3f00a2a7313135103a005b1b67` に固定します。
128
+
129
+ EXIF補正、透明背景を白で合成、RGB化 → 長辺1024px以下 → JPEG quality=88 →
130
+ 短辺224pxへbicubicリサイズ → 224×224中央切り出し → CLIP標準化 →
131
+ 視覚バックボーンと `last_layer_style` → L2正規化です。
132
+ content projectionやCLIP本来のprojectionは使いません。前処理を変えるとパックとの互換性が崩れます。
133
+
134
+ JPEG・PNG・WebP・GIF・BMPに対応。GIFは先頭フレームです。
135
+ 1ファイル100MiB、2億画素まで(上限内でも大画像には数GBのRAMが必要な場合があります)。
136
+ 同一バイト列の重複は1枚にまとめます。入力画像の近似重複は自動除去しないため、
137
+ 表情差分などを大量投入するとその内容に平均が偏ります。少数画像でも動きますが不確かさは増えます。
138
+
139
+ 公開CSD実装には、公開重みと論文の値に差異がある旨の注意書きがあります。
140
+ このツールの評価値を論文の性能と同一視しないでください。
141
+
142
+ ## データの由来・収録条件
143
+
144
+ - [nyanko-devs/danbooru2026](https://huggingface.co/datasets/nyanko-devs/danbooru2026), revision
145
+ `ebb02a630201c7b51487e45fb90b3fcf4cbedc20` のアーカイブと投稿メタデータから作成。
146
+ - 元の35,705作者名簿に、アーカイブに32枚以上ある未登録26,672タグを追加。
147
+ 名簿62,377のうち特徴量がある62,051作者を配布。326作者は採用画像なし。
148
+ - 計3,344,456枚の作者への採用レコード。同一画像が複数作者に紐付く場合もあり、
149
+ 全世界で一意な画像数という意味ではありません。
150
+ - 作者ごと最大64枚。g=22、s=21、q/e合計21を目標とし、不足区分は他区分で補完。
151
+ 各区分内では新しい**投稿日時**を優先(作品制作日時とは限らない)。
152
+ - SFW=g、NSFW=s/q/e。検索パックには両方を含み、画像内容での絞り込みは提供しません。
153
+ - 評価画像はID・親子関係・Pixiv ID・MD5と視覚照合で除外。作者内の近似重複も除外。
154
+ 作者間の全共有画像を除外する処理はしていません。
155
+ - 32枚は追加対象を選ぶ前段階の条件。重複除外後に32枚未満になる作者や、旧名簿の少数作者も含みます。
156
+ - この配布物に元画像、画像別特徴量、画像ID一覧、私的ファイル、APIキーは含みません。
157
+ 作者座標・採用枚数・共通変換だけの検索用集約パックです。作家別に再学習するためのフル画像特徴データではありません。
158
+
159
+ ## 検証と限界
160
+
161
+ 固定クイズ(候補62,051作者)のLDA Top-1:
162
+
163
+ | クイズ | 1枚 | 5枚 | 10枚 |
164
+ |---|---:|---:|---:|
165
+ | 180作者・1,800画像 | 42.4% | 79.7% | 86.1% |
166
+ | nude50・250画像 | 31.2% | 84.0% | — |
167
+
168
+ これらは既存の研究中に繰り返し評価したクイズで、新規に収集した盲検ベンチマークではありません。
169
+ 候補数や作者構成が違う実験との単純比較はできません。64枚が全作者で十分収束したという意味でもありません。
170
+ 内容・構図・色・年代の影響は残ります。本人特定や作者の権利確認には使わないでください。
171
+
172
+ ## 権利・帰属
173
+
174
+ この配布コードの独自部分はMIT。CLIP/CSD由来のコードは `vendor/` 内のMITライセンスを保持しています。
175
+ CSDモデルカードはCC BY 4.0を表示しています。重みは���配布せず公式リポジトリから取得します。
176
+ [元アーカイブ](https://huggingface.co/datasets/nyanko-devs/danbooru2026) のカードはMITを表示していますが、
177
+ 各作品の著作権や第三者の権利までその表示で解決したとは扱いません。
178
+ **集約特徴量パックをMITやCC0として一括許諾する主張はしません。** 詳細は [DATA-NOTICE.txt](DATA-NOTICE.txt)。
179
+ 帰属や削除窓口の用意は許諾の代わりではありません。権利者の連絡はこのリポジトリのCommunityへ。
180
+ 必要に応じて収録・配布内容を見直し、削除します。過去に第三者が取得したコピーの回収は保証できません。
181
+
182
+ ## 手動実行・テスト
183
+
184
+ リポジトリ一式を取得して `pip install -r requirements.txt`、画像検索なら
185
+ `pip install -r requirements-images.txt` の後、`python search.py --artist mochizuki_kei`。
186
+ 合成データのテストは `python tests.py -v`(画像処理テストにはPillowが必要)。
187
+ CSD版は作者名のLDA検索にPyTorchを要求しません。
artist_links.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Public artist-profile links only; never fetch images or guess account names."""
2
+ import json
3
+ import time
4
+ import html
5
+ import re
6
+ from pathlib import Path
7
+ from urllib.parse import urlencode, urlparse, parse_qs
8
+ from urllib.request import Request, urlopen
9
+
10
+
11
+ def profile_urls(records):
12
+ found = {'pixiv': [], 'twitter': []}
13
+ for record in records:
14
+ if not isinstance(record, dict) or record.get('is_active') is False:
15
+ continue
16
+ url = record.get('url', '')
17
+ p = urlparse(url)
18
+ if p.scheme not in ('https', 'http') or p.username or p.password:
19
+ continue
20
+ host = (p.hostname or '').lower()
21
+ normalized = None
22
+ if host in ('pixiv.net', 'www.pixiv.net'):
23
+ m = re.fullmatch(r'/(?:[a-z]{2}/)?users/(\d+)/?', p.path)
24
+ ident = m.group(1) if m else (parse_qs(p.query).get('id', [''])[0] if p.path == '/member.php' else '')
25
+ if ident.isdigit():normalized = ('pixiv', 'https://www.pixiv.net/users/' + ident)
26
+ elif host in ('twitter.com', 'www.twitter.com', 'mobile.twitter.com', 'x.com', 'www.x.com'):
27
+ path = p.path.rstrip('/')
28
+ m = re.fullmatch(r'/([A-Za-z0-9_]{1,15})', path)
29
+ if (m and m.group(1).lower() not in {'home','search','explore','intent','share','settings','login','signup','i'}) or re.fullmatch(r'/i/user/\d+', path):
30
+ normalized = ('twitter', 'https://x.com' + path)
31
+ if normalized and normalized[1] not in found[normalized[0]]:
32
+ found[normalized[0]].append(normalized[1])
33
+ return found
34
+
35
+
36
+ def fetch_artist_links(artist, cache_dir):
37
+ import hashlib
38
+ cache_dir = Path(cache_dir);cache_dir.mkdir(parents=True, exist_ok=True)
39
+ file = cache_dir / (hashlib.sha256(artist.encode()).hexdigest() + '.json')
40
+ cached = None
41
+ try:
42
+ cached = json.loads(file.read_text())
43
+ if cached.get('artist') == artist and time.time() - cached['fetched_at'] < 7 * 86400:
44
+ return cached
45
+ except (OSError, ValueError, KeyError, TypeError):pass
46
+ result = {'artist': artist, 'danbooru': 'https://danbooru.donmai.us/posts?' + urlencode({'tags': artist}), 'pixiv': [], 'twitter': [], 'source': 'Danbooru artist API', 'status': 'unavailable'}
47
+ try:
48
+ api = 'https://danbooru.donmai.us/artists.json?' + urlencode({'search[name]': artist, 'only': 'name,urls,is_deleted', 'limit': 5})
49
+ req = Request(api, headers={'User-Agent': 'StyleScout/2 (artist-profile-link lookup)', 'Accept': 'application/json'})
50
+ with urlopen(req, timeout=8) as response:data = json.load(response)
51
+ exact = next((r for r in data if r.get('name') == artist and not r.get('is_deleted')), None)
52
+ result.update(profile_urls(exact.get('urls', [])) if exact else {})
53
+ result.update(status='ok' if exact else 'not_found', fetched_at=time.time())
54
+ file.write_text(json.dumps(result, ensure_ascii=False) + '\n')
55
+ except Exception as e:
56
+ if cached and cached.get('artist') == artist:
57
+ result = dict(cached);result['status'] = 'stale_cache'
58
+ else:result['error'] = type(e).__name__
59
+ return result
60
+
csd_features.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CSD-ViT-L style descriptors. No silent fallback to appearance statistics."""
2
+ import io
3
+ import argparse
4
+ import os
5
+ import threading
6
+ from pathlib import Path
7
+
8
+ import numpy as np
9
+ from PIL import Image, ImageOps
10
+
11
+ MODEL_REPO = 'tomg-group-umd/CSD-ViT-L'
12
+ MODEL_REVISION = '5bc26a6fb0487f3f00a2a7313135103a005b1b67'
13
+ VERSION = f'csd-vit-l:{MODEL_REVISION}:preview1024-clip224-v1'
14
+ MODEL_DIR = Path(__file__).resolve().parent / 'models' / 'csd-vit-l'
15
+ Image.MAX_IMAGE_PIXELS = 200_000_000
16
+ _lock = threading.RLock()
17
+ _model = None
18
+ _transform = None
19
+ _status = {'name': 'CSD ViT-L', 'version': VERSION, 'state': 'unloaded', 'device': None, 'error': None}
20
+
21
+
22
+ def model_status():
23
+ # Reading status must not wait for a model download/inference lock.
24
+ return dict(_status)
25
+
26
+
27
+ def normalize(v):
28
+ v = np.asarray(v, dtype=np.float64)
29
+ return v / max(float(np.linalg.norm(v)), 1e-12)
30
+
31
+
32
+ def choose_device(torch):
33
+ requested = os.getenv('STYLE_SCOUT_DEVICE', 'auto').lower()
34
+ if requested not in ('auto', 'mps', 'cpu', 'cuda'):
35
+ raise ValueError('STYLE_SCOUT_DEVICE は auto / mps / cpu / cuda です')
36
+ if requested == 'cuda':
37
+ if not torch.cuda.is_available(): raise ValueError('CUDA is unavailable')
38
+ return 'cuda'
39
+ if requested == 'auto' and torch.cuda.is_available(): return 'cuda'
40
+ available = torch.backends.mps.is_available()
41
+ if requested == 'mps' and not available:
42
+ raise ValueError('この実行環境ではMac GPU(MPS)を利用できません')
43
+ return 'mps' if available and requested != 'cpu' else 'cpu'
44
+
45
+
46
+ def load_visual_weights(model, checkpoint):
47
+ """Official CSD output is backbone feature @ last_layer_style, not CLIP's head."""
48
+ state = checkpoint.get('model_state_dict', checkpoint)
49
+ state = {k.removeprefix('module.'): v for k, v in state.items()}
50
+ style = state.get('last_layer_style')
51
+ if style is None or tuple(style.shape) != (1024, 768):
52
+ raise ValueError('CSDのstyle projectionがありません。公式の重みを確認してください')
53
+ weights = {k.removeprefix('backbone.'): v for k, v in state.items() if k.startswith('backbone.')}
54
+ weights['proj'] = style
55
+ # Every visual backbone tensor must match; never use partially random weights.
56
+ model.load_state_dict(weights, strict=True)
57
+
58
+
59
+ def ensure_ready():
60
+ global _model, _transform
61
+ with _lock:
62
+ if _model is not None:
63
+ return
64
+ _status.update(state='loading', error=None)
65
+ try:
66
+ import torch
67
+ from torchvision import transforms
68
+ from vendor.clip_model import VisionTransformer
69
+ device = choose_device(torch)
70
+ _status['device'] = device
71
+ path = MODEL_DIR / 'pytorch_model.bin'
72
+ if not path.is_file():
73
+ _status['state'] = 'downloading'
74
+ from huggingface_hub import hf_hub_download
75
+ hf_hub_download(MODEL_REPO, 'pytorch_model.bin', revision=MODEL_REVISION, local_dir=MODEL_DIR)
76
+ _status['state'] = 'loading'
77
+ # Official checkpoint includes harmless training metadata. Keep restricted loading.
78
+ from numpy._core.multiarray import scalar
79
+ allowed = [(scalar, 'numpy.core.multiarray.scalar'), np.dtype, np.dtypes.Float64DType, argparse.Namespace]
80
+ with torch.serialization.safe_globals(allowed):
81
+ checkpoint = torch.load(path, map_location='cpu', weights_only=True, mmap=True)
82
+ model = VisionTransformer(224, 14, 1024, 24, 16, 768)
83
+ load_visual_weights(model, checkpoint)
84
+ del checkpoint
85
+ model.eval().requires_grad_(False).float().to(device)
86
+ transform = transforms.Compose([
87
+ transforms.Resize(224, interpolation=transforms.InterpolationMode.BICUBIC),
88
+ transforms.CenterCrop(224), transforms.ToTensor(),
89
+ transforms.Normalize((.48145466, .4578275, .40821073), (.26862954, .26130258, .27577711)),
90
+ ])
91
+ # Actually execute the selected device before announcing it as ready.
92
+ with torch.inference_mode():
93
+ probe = model(torch.zeros(1, 3, 224, 224, device=device))
94
+ if probe.shape != (1, 768) or not torch.isfinite(probe).all().item():
95
+ raise ValueError('CSDの推論結果が不正です')
96
+ _model, _transform = model, transform
97
+ _status.update(state='ready', error=None)
98
+ except Exception as exc:
99
+ _status.update(state='error', error=str(exc))
100
+ raise ValueError(f'CSDを準備できませんでした: {exc}') from exc
101
+
102
+
103
+ def prepare_image(raw):
104
+ if len(raw) > 100 * 1024 * 1024: raise ValueError('画像は100 MiBまでです')
105
+ with Image.open(io.BytesIO(raw)) as src:
106
+ if src.width * src.height > 200_000_000: raise ValueError('画像は2億画素までです')
107
+ if src.format not in {'JPEG', 'PNG', 'WEBP', 'GIF', 'BMP'}:
108
+ raise ValueError('JPEG / PNG / WebP / GIF / BMP を指定してください')
109
+ src.seek(0)
110
+ rgba = ImageOps.exif_transpose(src).convert('RGBA')
111
+ im = Image.new('RGBA', rgba.size, 'white')
112
+ im.alpha_composite(rgba)
113
+ im = im.convert('RGB')
114
+ im.thumbnail((1024, 1024))
115
+ out = io.BytesIO()
116
+ im.save(out, 'JPEG', quality=88)
117
+ return out.getvalue()
118
+
119
+
120
+ def embed_jpeg(jpeg):
121
+ import torch
122
+ ensure_ready()
123
+ with _lock, torch.inference_mode():
124
+ with Image.open(io.BytesIO(jpeg)) as im:
125
+ tensor = _transform(im.convert('RGB')).unsqueeze(0).to(_status['device'])
126
+ result = _model(tensor).float()
127
+ if not torch.isfinite(result).all().item() or result.norm().item() < 1e-8:
128
+ raise ValueError('CSDの特徴量が不正です')
129
+ result = torch.nn.functional.normalize(result, dim=1)
130
+ return result[0].cpu().tolist()
131
+
132
+
133
+ def extract(raw):
134
+ jpeg = prepare_image(raw)
135
+ return embed_jpeg(jpeg), jpeg
136
+
137
+
138
+ def extract_many(raw_images, *, preprocessed=False, precision="fp32"):
139
+ """Bounded, RAM-only batch extraction using the same preprocessing/style head."""
140
+ import torch
141
+ if not 1 <= len(raw_images) <= 64:
142
+ raise ValueError('CSD batch must contain 1–64 images')
143
+ if precision not in ('fp32', 'fp16'): raise ValueError('Invalid precision')
144
+ ensure_ready()
145
+ with _lock, torch.inference_mode():
146
+ tensors = []
147
+ for raw in raw_images:
148
+ if preprocessed:
149
+ array = np.asarray(raw, dtype=np.float32)
150
+ if array.shape != (3, 224, 224): raise ValueError('Expected CHW 224 array')
151
+ tensors.append(torch.from_numpy(array.copy()))
152
+ continue
153
+ with Image.open(io.BytesIO(prepare_image(raw))) as im:
154
+ tensors.append(_transform(im.convert('RGB')))
155
+ with torch.autocast(device_type=_status['device'], dtype=torch.float16, enabled=precision == 'fp16'):
156
+ result = _model(torch.stack(tensors).to(_status['device'])).float()
157
+ if not torch.isfinite(result).all().item() or (result.norm(dim=1) < 1e-8).any().item():
158
+ raise ValueError('CSDの推論結果が不正です')
159
+ return torch.nn.functional.normalize(result, dim=1).cpu().numpy()
160
+
downloads/style-scout-csd-code.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:36a94c2fad9cc4da09b8f0c5afdf3745b41f47f5265f69d5fb6c4d282597aadd
3
+ size 32484
features/artists.json ADDED
The diff for this file is too large to render. See raw diff
 
features/lda.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:22f50b5563f858fdae365e0e26f8616884c9527593ee6c7463d6488987118cab
3
+ size 179752985
features/manifest.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "format": "style-scout-csd-lda-v1",
3
+ "artist_count": 62051,
4
+ "dimension": 768,
5
+ "reference_images": 3344456,
6
+ "feature_version": "csd-vit-l:5bc26a6fb0487f3f00a2a7313135103a005b1b67:preview1024-clip224-v1",
7
+ "extractor_repo": "tomg-group-umd/CSD-ViT-L",
8
+ "extractor_revision": "5bc26a6fb0487f3f00a2a7313135103a005b1b67",
9
+ "method": "LDA: Euclidean distance in centered within-artist-whitened coordinates; no artist/query-mean L2 renormalization",
10
+ "dimensions": 768,
11
+ "shrinkage": 0.0,
12
+ "floor_relative": 1e-06,
13
+ "selection": "Frozen 14 validation authors, 360 probes. Existing shared transform selected by historical PLDA macro MRR; no retuning on quiz. PLDA is not included in this distribution.",
14
+ "source_model_sha256": "e1aa272002595ad2be57e854325fe9777dde1044d24a4e98078ad9e5872da371",
15
+ "files": {
16
+ "lda.npz": {
17
+ "sha256": "22f50b5563f858fdae365e0e26f8616884c9527593ee6c7463d6488987118cab",
18
+ "bytes": 179752985
19
+ },
20
+ "artists.json": {
21
+ "sha256": "deb48275a0c5eec401b45ce41cf694980f1c36435424facc141d0a7b3060fc27",
22
+ "bytes": 2252683
23
+ }
24
+ }
25
+ }
lda_core.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ """LDA-only operations reused from Style Scout plda_core."""
2
+ import numpy as np
3
+
4
+ def coordinates(means, model):
5
+ return (np.asarray(means, float)-model['center']) @ model['W'].T
6
+
7
+
8
+ def lda_scores(query, artist_coordinates):
9
+ return -np.sum((np.asarray(artist_coordinates)-query)**2, axis=1)
10
+
requirements-images.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ -r requirements.txt
2
+ torch>=2.6,<3
3
+ torchvision>=0.21,<1
4
+ Pillow>=11,<13
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ numpy>=2.0,<3
2
+ huggingface_hub>=0.30,<2
run.sh ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """One-file bootstrap: isolated venv, pinned runtime/feature pack, local LDA search."""
3
+ import argparse,hashlib,json,os,re,subprocess,sys,urllib.request,venv
4
+ from pathlib import Path
5
+ REPO='cloudaiman/style-scout-csd-lda'
6
+ BASE=['numpy>=2.0,<3','huggingface_hub>=0.30,<2']
7
+ IMAGES=['torch>=2.6,<3','torchvision>=0.21,<1','Pillow>=11,<13']
8
+
9
+
10
+ def run(cmd):subprocess.run([str(x) for x in cmd],check=True)
11
+
12
+ def main(argv=None):
13
+ args=list(sys.argv[1:] if argv is None else argv)
14
+ if '--' in args:args.remove('--')
15
+ if not args or '--help' in args or '-h' in args:
16
+ print('Style Scout CSD (LDA only)\nPython 3.10+ required (3.12 recommended).\n\npython3 run_style_scout_csd.py --artist mochizuki_kei\npython3 run_style_scout_csd.py --images /path/to/file.png /path/to/folder\n\nOptions: --artist TAG (repeatable), --images PATH... (recursive), --top 20,\n--min-count 1, --device auto|mps|cuda|cpu, --model-dir DIR, --no-open,\n--no-links (no artist-profile API), --output DIR, --cache-dir DIR.\nResults: ./results/<timestamp>/report.html (opens automatically).\nBootstrap: --install-dir DIR, --offline (requires previously downloaded release).\nFirst run downloads the numeric pack; image queries also download official CSD weights.\nLocal images are never uploaded.');return
17
+ p=argparse.ArgumentParser(add_help=False);p.add_argument('--install-dir',type=Path,default=Path.home()/'style-scout-csd');p.add_argument('--offline',action='store_true');p.add_argument('--bundle-dir',type=Path,help=argparse.SUPPRESS)
18
+ a,search=p.parse_known_args(args)
19
+ if sys.version_info<(3,10):raise RuntimeError('Python 3.10以上が必要です(推奨3.12)')
20
+ if not any(x in search for x in ['--artist','--images']):raise ValueError('--artist または --images を指定してください')
21
+ home=a.install_dir.expanduser().resolve();home.mkdir(parents=True,exist_ok=True);env=home/'.venv';python=env/('Scripts/python.exe' if os.name=='nt' else 'bin/python')
22
+ if not python.exists():print('仮想環境を作成:',env,flush=True);venv.EnvBuilder(with_pip=True).create(env)
23
+ def install(packages,label):
24
+ stamp=home/('.installed-'+label+'.json');signature={'packages':packages}
25
+ if stamp.exists() and json.loads(stamp.read_text())==signature:return
26
+ if a.offline:raise RuntimeError('Offline mode requires installed '+label+' dependencies')
27
+ run([python,'-m','pip','install',*packages]);stamp.write_text(json.dumps(signature))
28
+ install(BASE,'base')
29
+ if '--images' in search:install(IMAGES,'images')
30
+ if a.bundle_dir:
31
+ bundle=a.bundle_dir.resolve()
32
+ else:
33
+ cached=home/'release.json';release=None
34
+ if not a.offline:
35
+ try:
36
+ req=urllib.request.Request('https://huggingface.co/datasets/'+REPO+'/resolve/main/release.json',headers={'User-Agent':'StyleScout-CSD/1'})
37
+ with urllib.request.urlopen(req,timeout=30) as r:raw=r.read(1024*1024)
38
+ release=json.loads(raw)
39
+ except Exception:
40
+ if not cached.exists():raise RuntimeError('Release情報を取得できません。通信状況を確認してください')
41
+ print('更新確認に失敗。保存済みのリリースを使用します。',flush=True)
42
+ if release is None:release=json.loads(cached.read_text())
43
+ if release.get('repo')!=REPO or not re.fullmatch('[0-9a-f]{40}',release.get('revision','')) or release.get('format')!='style-scout-csd-release-v1':raise ValueError('Invalid release manifest')
44
+ files=release['files']
45
+ if not files or any(Path(n).is_absolute() or '..' in Path(n).parts or '\\' in n for n in files):raise ValueError('Unsafe release path')
46
+ spec=home/'release-selected.json';spec.write_text(json.dumps(release))
47
+ code='''import hashlib,json,sys\nfrom pathlib import Path\nfrom huggingface_hub import snapshot_download\ns=json.loads(Path(sys.argv[1]).read_text());p=Path(snapshot_download(s['repo'],repo_type='dataset',revision=s['revision'],allow_patterns=list(s['files']),local_files_only=sys.argv[2]=='1'))\nfor name,want in s['files'].items():\n h=hashlib.sha256()\n with (p/name).open('rb') as f:\n for b in iter(lambda:f.read(8*1024*1024),b''):h.update(b)\n if h.hexdigest()!=want:raise ValueError('Checksum mismatch: '+name)\nPath(sys.argv[3]).write_text(str(p))\n'''
48
+ pathfile=home/'runtime-path.txt';run([python,'-c',code,spec,'1' if a.offline else '0',pathfile]);bundle=Path(pathfile.read_text());cached.write_text(json.dumps(release,indent=2))
49
+ if a.offline:
50
+ os.environ['HF_HUB_OFFLINE']='1'
51
+ if '--no-links' not in search:search.append('--no-links')
52
+ run([python,bundle/'search.py',*search])
53
+
54
+ if __name__=='__main__':
55
+ try:main()
56
+ except (OSError,ValueError,RuntimeError,subprocess.CalledProcessError) as exc:sys.exit(str(exc))
run_style_scout_csd.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """One-file bootstrap: isolated venv, pinned runtime/feature pack, local LDA search."""
3
+ import argparse,hashlib,json,os,re,subprocess,sys,urllib.request,venv
4
+ from pathlib import Path
5
+ REPO='cloudaiman/style-scout-csd-lda'
6
+ BASE=['numpy>=2.0,<3','huggingface_hub>=0.30,<2']
7
+ IMAGES=['torch>=2.6,<3','torchvision>=0.21,<1','Pillow>=11,<13']
8
+
9
+
10
+ def run(cmd):subprocess.run([str(x) for x in cmd],check=True)
11
+
12
+ def main(argv=None):
13
+ args=list(sys.argv[1:] if argv is None else argv)
14
+ if '--' in args:args.remove('--')
15
+ if not args or '--help' in args or '-h' in args:
16
+ print('Style Scout CSD (LDA only)\nPython 3.10+ required (3.12 recommended).\n\npython3 run_style_scout_csd.py --artist mochizuki_kei\npython3 run_style_scout_csd.py --images /path/to/file.png /path/to/folder\n\nOptions: --artist TAG (repeatable), --images PATH... (recursive), --top 20,\n--min-count 1, --device auto|mps|cuda|cpu, --model-dir DIR, --no-open,\n--no-links (no artist-profile API), --output DIR, --cache-dir DIR.\nResults: ./results/<timestamp>/report.html (opens automatically).\nBootstrap: --install-dir DIR, --offline (requires previously downloaded release).\nFirst run downloads the numeric pack; image queries also download official CSD weights.\nLocal images are never uploaded.');return
17
+ p=argparse.ArgumentParser(add_help=False);p.add_argument('--install-dir',type=Path,default=Path.home()/'style-scout-csd');p.add_argument('--offline',action='store_true');p.add_argument('--bundle-dir',type=Path,help=argparse.SUPPRESS)
18
+ a,search=p.parse_known_args(args)
19
+ if sys.version_info<(3,10):raise RuntimeError('Python 3.10以上が必要です(推奨3.12)')
20
+ if not any(x in search for x in ['--artist','--images']):raise ValueError('--artist または --images を指定してください')
21
+ home=a.install_dir.expanduser().resolve();home.mkdir(parents=True,exist_ok=True);env=home/'.venv';python=env/('Scripts/python.exe' if os.name=='nt' else 'bin/python')
22
+ if not python.exists():print('仮想環境を作成:',env,flush=True);venv.EnvBuilder(with_pip=True).create(env)
23
+ def install(packages,label):
24
+ stamp=home/('.installed-'+label+'.json');signature={'packages':packages}
25
+ if stamp.exists() and json.loads(stamp.read_text())==signature:return
26
+ if a.offline:raise RuntimeError('Offline mode requires installed '+label+' dependencies')
27
+ run([python,'-m','pip','install',*packages]);stamp.write_text(json.dumps(signature))
28
+ install(BASE,'base')
29
+ if '--images' in search:install(IMAGES,'images')
30
+ if a.bundle_dir:
31
+ bundle=a.bundle_dir.resolve()
32
+ else:
33
+ cached=home/'release.json';release=None
34
+ if not a.offline:
35
+ try:
36
+ req=urllib.request.Request('https://huggingface.co/datasets/'+REPO+'/resolve/main/release.json',headers={'User-Agent':'StyleScout-CSD/1'})
37
+ with urllib.request.urlopen(req,timeout=30) as r:raw=r.read(1024*1024)
38
+ release=json.loads(raw)
39
+ except Exception:
40
+ if not cached.exists():raise RuntimeError('Release情報を取得できません。通信状況を確認してください')
41
+ print('更新確認に失敗。保存済みのリリースを使用します。',flush=True)
42
+ if release is None:release=json.loads(cached.read_text())
43
+ if release.get('repo')!=REPO or not re.fullmatch('[0-9a-f]{40}',release.get('revision','')) or release.get('format')!='style-scout-csd-release-v1':raise ValueError('Invalid release manifest')
44
+ files=release['files']
45
+ if not files or any(Path(n).is_absolute() or '..' in Path(n).parts or '\\' in n for n in files):raise ValueError('Unsafe release path')
46
+ spec=home/'release-selected.json';spec.write_text(json.dumps(release))
47
+ code='''import hashlib,json,sys\nfrom pathlib import Path\nfrom huggingface_hub import snapshot_download\ns=json.loads(Path(sys.argv[1]).read_text());p=Path(snapshot_download(s['repo'],repo_type='dataset',revision=s['revision'],allow_patterns=list(s['files']),local_files_only=sys.argv[2]=='1'))\nfor name,want in s['files'].items():\n h=hashlib.sha256()\n with (p/name).open('rb') as f:\n for b in iter(lambda:f.read(8*1024*1024),b''):h.update(b)\n if h.hexdigest()!=want:raise ValueError('Checksum mismatch: '+name)\nPath(sys.argv[3]).write_text(str(p))\n'''
48
+ pathfile=home/'runtime-path.txt';run([python,'-c',code,spec,'1' if a.offline else '0',pathfile]);bundle=Path(pathfile.read_text());cached.write_text(json.dumps(release,indent=2))
49
+ if a.offline:
50
+ os.environ['HF_HUB_OFFLINE']='1'
51
+ if '--no-links' not in search:search.append('--no-links')
52
+ run([python,bundle/'search.py',*search])
53
+
54
+ if __name__=='__main__':
55
+ try:main()
56
+ except (OSError,ValueError,RuntimeError,subprocess.CalledProcessError) as exc:sys.exit(str(exc))
search.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LDA-only artist or local image-set retrieval. No image upload or generation."""
2
+ import argparse,hashlib,html,json,os,sys,webbrowser
3
+ from datetime import datetime
4
+ from pathlib import Path
5
+ from urllib.parse import urlencode
6
+ import numpy as np
7
+ from lda_core import coordinates,lda_scores
8
+
9
+ ROOT=Path(__file__).resolve().parent
10
+ EXTENSIONS={'.jpg','.jpeg','.png','.webp','.gif','.bmp'}
11
+
12
+ def sha(path):
13
+ h=hashlib.sha256()
14
+ with Path(path).open('rb') as f:
15
+ for b in iter(lambda:f.read(8*1024*1024),b''):h.update(b)
16
+ return h.hexdigest()
17
+
18
+ def load_pack(path):
19
+ path=Path(path);manifest=json.loads((path/'manifest.json').read_text())
20
+ if manifest['format']!='style-scout-csd-lda-v1':raise ValueError('Incompatible feature pack')
21
+ for name in ['lda.npz','artists.json']:
22
+ spec=manifest['files'][name]
23
+ if (path/name).stat().st_size!=spec['bytes'] or sha(path/name)!=spec['sha256']:raise ValueError('Corrupt pack: '+name)
24
+ with np.load(path/'lda.npz',allow_pickle=False) as z:model={k:z[k].copy() for k in z.files}
25
+ artists=json.loads((path/'artists.json').read_text());n=len(artists);dim=manifest['dimension']
26
+ if model['coordinates'].shape!=(n,dim) or model['W'].shape!=(dim,768) or model['center'].shape!=(768,) or model['counts'].shape!=(n,):raise ValueError('Pack shape mismatch')
27
+ if len({a['artist'] for a in artists})!=n or any(a['count']!=model['counts'][i] for i,a in enumerate(artists)):raise ValueError('Artist/count mismatch')
28
+ if any(not np.isfinite(model[k]).all() for k in ['coordinates','W','center']) or np.any(model['counts']<1):raise ValueError('Invalid pack values')
29
+ return model,artists,manifest
30
+
31
+ def collect_images(inputs):
32
+ found=[]
33
+ for item in inputs:
34
+ p=Path(item).expanduser()
35
+ if p.is_dir():found.extend(sorted(x for x in p.rglob('*') if x.is_file() and x.suffix.lower() in EXTENSIONS))
36
+ elif p.is_file() and p.suffix.lower() in EXTENSIONS:found.append(p)
37
+ else:raise ValueError('画像ファイル/フォルダが見つかりません: '+str(p))
38
+ found=list(dict.fromkeys(p.resolve() for p in found))
39
+ if not found:raise ValueError('対応画像がありません(JPEG/PNG/WebP/GIF/BMP)')
40
+ return found
41
+
42
+ def image_query(inputs,model,manifest,cache_dir,model_dir=None,device='auto'):
43
+ import csd_features as f
44
+ os.environ['STYLE_SCOUT_DEVICE']=device
45
+ if model_dir:f.MODEL_DIR=Path(model_dir).expanduser()
46
+ else:
47
+ # Standard local installation locations only; no broad disk scan.
48
+ candidates=[Path.cwd()/'style-scout/models/csd-vit-l',Path.cwd()/'models/csd-vit-l',Path.home()/'style-scout/models/csd-vit-l']
49
+ found=next((p for p in candidates if (p/'pytorch_model.bin').is_file()),None)
50
+ f.MODEL_DIR=found or Path(cache_dir)/'model'
51
+ if f.VERSION!=manifest['feature_version']:raise ValueError('Extractor/pack version mismatch')
52
+ cache=Path(cache_dir)/'image-vectors';cache.mkdir(parents=True,exist_ok=True)
53
+ total=np.zeros(768,np.float64);files=[];seen=set();duplicates=0
54
+ for p in collect_images(inputs):
55
+ if p.stat().st_size>100*1024*1024:raise ValueError('画像は100 MiBまで: '+p.name)
56
+ digest=sha(p)
57
+ if digest in seen:duplicates+=1;continue
58
+ seen.add(digest);key=hashlib.sha256((digest+f.VERSION).encode()).hexdigest();dest=cache/(key+'.npy')
59
+ vector=None
60
+ if dest.exists():
61
+ try:
62
+ v=np.load(dest,allow_pickle=False)
63
+ if v.shape==(768,) and np.isfinite(v).all() and np.isclose(np.linalg.norm(v),1,atol=1e-4):vector=v
64
+ except (OSError,ValueError):pass
65
+ if vector is None:
66
+ try:vector=np.asarray(f.extract(p.read_bytes())[0],np.float32)
67
+ except Exception as exc:raise ValueError('特徴量抽出失敗: '+p.name+' / '+str(exc)) from exc
68
+ if vector.shape!=(768,) or not np.isfinite(vector).all() or not np.isclose(np.linalg.norm(vector),1,atol=1e-4):raise ValueError('Invalid extracted vector')
69
+ tmp=dest.with_suffix('.tmp')
70
+ with tmp.open('wb') as out:np.save(out,vector,allow_pickle=False)
71
+ tmp.replace(dest)
72
+ total+=vector;files.append({'name':p.name,'sha256':digest});print('CSD:',len(files),'枚処理',flush=True)
73
+ # Average unit image vectors; do NOT normalize this mean again.
74
+ mean=total/len(files)
75
+ return coordinates(mean[None],model)[0],{'kind':'images','label':'画像セット','count':len(files),'files':files,'exact_duplicates_skipped':duplicates,'feature_version':f.VERSION}
76
+
77
+ def rank(query,model,artists,exclude=None,minimum=1):
78
+ scores=lda_scores(query,model['coordinates'].astype(np.float64))
79
+ indices=np.flatnonzero(model['counts']>=minimum)
80
+ if exclude is not None:indices=indices[indices!=exclude]
81
+ order=indices[np.lexsort((indices,-scores[indices]))]
82
+ return [{'artist':artists[i]['artist'],'count':int(model['counts'][i]),'distance':float(np.sqrt(max(0,-scores[i]))),'rank':j+1} for j,i in enumerate(order)]
83
+
84
+ def links_for(names,cache_dir,enabled):
85
+ from artist_links import fetch_artist_links
86
+ from concurrent.futures import ThreadPoolExecutor
87
+ base=lambda a:{'artist':a,'danbooru':'https://danbooru.donmai.us/posts?'+urlencode({'tags':a}),'pixiv':[],'twitter':[],'status':'disabled'}
88
+ if not enabled:return {a:base(a) for a in names}
89
+ print('作者プロフィールのリンクを確認:',len(names),'人',flush=True)
90
+ with ThreadPoolExecutor(max_workers=3) as pool:return dict(zip(names,pool.map(lambda a:fetch_artist_links(a,cache_dir),names)))
91
+
92
+ def render(result):
93
+ e=lambda s:html.escape(str(s),quote=True)
94
+ payload=json.dumps(result,ensure_ascii=False,separators=(',',':'),allow_nan=False).replace('<','\\u003c')
95
+ return '''<!doctype html><html lang="ja"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Style Scout CSD・LDA</title>
96
+ <style>body{font:15px/1.6 system-ui;margin:30px auto;padding:0 20px;max-width:1100px;background:#f5f7fb;color:#172235}h1{font-size:28px}table{border-collapse:collapse;background:white;width:100%}td,th{padding:12px;text-align:left;border-bottom:1px solid #dde3ee}th{background:#e8edf5}a{color:#245bb0}select{padding:8px;font-size:15px}small,.muted{color:#596780;font-size:12px}.links{display:flex;gap:12px;flex-wrap:wrap}.controls{display:flex;gap:20px;flex-wrap:wrap;margin:20px 0}canvas{max-width:100%;background:white}figure{margin:20px 0}section{background:white;border-radius:10px;padding:16px;margin:20px 0}.stats{font-size:17px}td:nth-child(2){overflow-wrap:anywhere}</style>
97
+ <h1>Style Scout CSD — LDA類似作者検索</h1><p class="stats">候補 '''+f'{result["candidate_count"]:,}'+'''作者。距離が小さいほど近い結果です。</p>
98
+ <div class="controls"><label>参照 <select id="query"></select></label><label>作者の採用枚数 <select id="minimum"></select></label></div><p id="summary"></p>
99
+ <table><thead><tr><th>順位</th><th>作者・リンク</th><th>採用枚数</th><th>LDA距離 ↓</th></tr></thead><tbody id="rows"></tbody></table>
100
+ <figure><canvas id="chart" width="420" height="420"></canvas><figcaption>Figure 1. 順位とLDA距離。縦軸は0から始まります。距離は一致率ではありません。</figcaption></figure>
101
+ <section><b>比較条件</b><p>CSDの画像単位L2正規化 → 画像集合の平均 → 中心化・LDA変換 → 作者座標とのユークリッド距離。平均の再正規化、SVD、一般タグの除外射影、PLDAは使用しません。作者名検索では本人を除外します。</p><p>参照枚数は画像の採用数です。最低枚数の切り替えは候補だけを絞り、LDA変換は再計算しません。画像セットは被写体・構図の影響も受けます。</p><p>Twitter/X・PixivはDanbooruに登録されたプロフィールです。現在の所有者を保証しません。未登録や取得失敗ではリンクを推測しません。ランキングにSFW/NSFWの区分はありません。画像・サムネイルは含まれません。</p><a href="results.json">結果JSON</a></section>
102
+ <script id="data" type="application/json">'''+payload+'''</script><script>
103
+ const D=JSON.parse(document.getElementById('data').textContent),Q=document.getElementById('query'),M=document.getElementById('minimum');
104
+ for(let i=0;i<D.queries.length;i++)Q.add(new Option(D.queries[i].label,i));
105
+ for(const m of D.minimum_options)M.add(new Option(m===1?'全作者':m+'枚以上',m));M.value=String(D.default_minimum);
106
+ function link(parent,url,label){let u;try{u=new URL(url)}catch{return}if(!['https:','http:'].includes(u.protocol))return;const a=document.createElement('a');a.href=u.href;a.textContent=label;a.target='_blank';a.rel='noopener noreferrer';parent.append(a)}
107
+ function draw(){const q=D.queries[Q.value],rows=q.rankings[M.value]||[],body=document.getElementById('rows');body.replaceChildren();document.getElementById('summary').textContent=q.label+' · 参照 '+q.count+'枚 · 上位 '+rows.length+'人';
108
+ for(const r of rows){const tr=document.createElement('tr');let td=document.createElement('td');td.textContent=r.rank;tr.append(td);td=document.createElement('td');const name=document.createElement('b');name.textContent=r.artist;td.append(name);const div=document.createElement('div');div.className='links';const l=D.links[r.artist];link(div,l.danbooru,'Danbooru');for(const [key,label] of [['pixiv','Pixiv'],['twitter','Twitter/X']]){if(l[key].length){l[key].forEach(u=>link(div,u,label))}else{const s=document.createElement('small');s.textContent=label+':'+(['unavailable','disabled'].includes(l.status)?'未取得':'登録なし');div.append(s)}}if(l.status==='stale_cache'){const s=document.createElement('small');s.textContent='以前取得したリンク';div.append(s)}td.append(div);tr.append(td);for(const v of [r.count,r.distance.toFixed(4)]){td=document.createElement('td');td.textContent=v;tr.append(td)}body.append(tr)}
109
+ const c=document.getElementById('chart'),x=c.getContext('2d');x.clearRect(0,0,420,420);const max=Math.max(1,...rows.map(r=>r.distance))*1.1;x.strokeStyle='#8693a5';x.beginPath();x.moveTo(55,25);x.lineTo(55,365);x.lineTo(400,365);x.stroke();x.font='12px system-ui';x.fillStyle='#34445c';for(let i=0;i<=4;i++){const y=365-i*85;x.fillText((max*i/4).toFixed(1),8,y);x.fillRect(52,y,4,1)}x.fillText('順位 →',180,405);x.fillText('LDA距離',12,16);x.strokeStyle='#245bb0';x.beginPath();rows.forEach((r,i)=>{const px=60+i*330/Math.max(1,rows.length-1),py=365-r.distance/max*340;i?x.lineTo(px,py):x.moveTo(px,py);if(i===0||i===rows.length-1)x.fillText(String(i+1),px,385)});x.stroke()}
110
+ Q.onchange=M.onchange=draw;draw();</script></html>'''
111
+
112
+ def main(argv=None):
113
+ p=argparse.ArgumentParser(description=__doc__);g=p.add_mutually_exclusive_group(required=True);g.add_argument('--artist',action='append');g.add_argument('--images',nargs='+')
114
+ p.add_argument('--pack',type=Path,default=ROOT/'features');p.add_argument('--cache-dir',type=Path,default=Path.home()/'.cache/style-scout-csd');p.add_argument('--model-dir',type=Path);p.add_argument('--device',choices=['auto','cpu','mps','cuda'],default='auto');p.add_argument('--top',type=int,default=20);p.add_argument('--min-count',type=int,default=1);p.add_argument('--output',type=Path);p.add_argument('--no-links',action='store_true');p.add_argument('--no-open',action='store_true');a=p.parse_args(argv)
115
+ if not 1<=a.top<=200 or a.min_count<1:p.error('--top is 1..200; --min-count >= 1')
116
+ out=(a.output or Path.cwd()/'results'/datetime.now().strftime('%Y%m%d-%H%M%S-%f')).resolve()
117
+ if out.exists():raise FileExistsError('出力先は既に存在します: '+str(out))
118
+ model,artists,manifest=load_pack(a.pack);lookup={r['artist']:i for i,r in enumerate(artists)};queries=[];minimums=sorted(set([1,8,16,32,64,a.min_count]))
119
+ if a.artist:
120
+ for name in a.artist:
121
+ if name not in lookup:raise ValueError('未収録の作者タグ: '+name+'(完全一致するタグを指定してください)')
122
+ ix=lookup[name];queries.append((model['coordinates'][ix].astype(float),{'kind':'artist','label':name,'count':int(model['counts'][ix])},ix))
123
+ else:
124
+ q,info=image_query(a.images,model,manifest,a.cache_dir,a.model_dir,a.device);queries.append((q,info,None))
125
+ result={'method':'LDA','candidate_count':len(artists),'dimension':manifest['dimension'],'pack_sha256':sha(a.pack/'lda.npz'),'feature_version':manifest['feature_version'],'minimum_options':minimums,'default_minimum':a.min_count,'top':a.top,'queries':[]}
126
+ names=[]
127
+ for q,info,exclude in queries:
128
+ allrows=rank(q,model,artists,exclude);info['rankings']={}
129
+ for minimum in minimums:
130
+ rows=[dict(r) for r in allrows if r['count']>=minimum][:a.top]
131
+ for i,r in enumerate(rows,1):r['rank']=i
132
+ info['rankings'][str(minimum)]=rows;names.extend(r['artist'] for r in rows)
133
+ result['queries'].append(info)
134
+ result['links']=links_for(list(dict.fromkeys(names)),a.cache_dir/'artist-links',not a.no_links)
135
+ out.mkdir(parents=True,exist_ok=False);(out/'results.json').write_text(json.dumps(result,ensure_ascii=False,indent=2,allow_nan=False),encoding='utf-8');(out/'report.html').write_text(render(result),encoding='utf-8')
136
+ for q in result['queries']:
137
+ print('\n'+q['label']+' ('+str(q['count'])+'枚)')
138
+ for r in q['rankings'][str(a.min_count)]:print(f"{r['rank']:>3} {r['artist']} 距離 {r['distance']:.4f} {r['count']}枚")
139
+ print('\n結果HTML: '+(out/'report.html').as_uri(),flush=True)
140
+ if not a.no_open:webbrowser.open((out/'report.html').as_uri())
141
+ return out
142
+
143
+ if __name__=='__main__':
144
+ try:main()
145
+ except (ValueError,OSError,KeyError) as exc:sys.exit(str(exc))
tests.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hashlib,io,json,tempfile,time,unittest
2
+ from pathlib import Path
3
+ from unittest.mock import patch
4
+ import numpy as np
5
+ import search,artist_links
6
+
7
+ class SearchTests(unittest.TestCase):
8
+ def setUp(self):
9
+ self.artists=[{'artist':'a','count':64},{'artist':'b','count':8},{'artist':'c','count':32}]
10
+ self.model={'coordinates':np.array([[0.,0.],[1.,0.],[1.,0.]],np.float32),'counts':np.array([64,8,32]),'center':np.zeros(768),'W':np.eye(2,768)}
11
+ def test_ties_self_exclusion_minimum(self):
12
+ self.assertEqual([r['artist'] for r in search.rank(np.zeros(2),self.model,self.artists,exclude=0)],['b','c'])
13
+ self.assertEqual(search.rank(np.zeros(2),self.model,self.artists,exclude=0,minimum=32)[0]['artist'],'c')
14
+ def test_mean_not_renormalized(self):
15
+ np.testing.assert_array_equal(search.coordinates(np.eye(2).mean(0)[None],{'center':np.zeros(2),'W':np.eye(2)}),[[.5,.5]])
16
+ def test_profile_urls(self):
17
+ r=artist_links.profile_urls([{'url':'https://www.pixiv.net/users/123'},{'url':'https://twitter.com/artist_1'},{'url':'https://evil.example/users/123'},{'url':'javascript:alert(1)'},{'url':'https://x.com/a/status/1'},{'url':'https://x.com/search'}])
18
+ self.assertEqual(r,{'pixiv':['https://www.pixiv.net/users/123'],'twitter':['https://x.com/artist_1']})
19
+ def test_cache_no_network(self):
20
+ with tempfile.TemporaryDirectory() as t:
21
+ p=Path(t)/(hashlib.sha256(b'a').hexdigest()+'.json');p.write_text(json.dumps({'artist':'a','fetched_at':time.time(),'pixiv':[],'twitter':[]}))
22
+ with patch('artist_links.urlopen',side_effect=AssertionError('network')):self.assertEqual(artist_links.fetch_artist_links('a',t)['artist'],'a')
23
+ def test_offline_links(self):
24
+ with patch('artist_links.urlopen',side_effect=AssertionError('network')):self.assertEqual(search.links_for(['1=2'],Path('/unused'),False)['1=2']['status'],'disabled')
25
+ def test_html_injection(self):
26
+ d={'candidate_count':1,'queries':[{'label':'</script><script>bad()</script>'}],'links':{},'minimum_options':[1],'default_minimum':1}
27
+ h=search.render(d);self.assertNotIn('</script><script>bad()',h);self.assertIn('\\u003c/script>',h)
28
+ def test_collect(self):
29
+ with tempfile.TemporaryDirectory() as t:
30
+ p=Path(t);(p/'x').mkdir();(p/'x/a.PNG').write_bytes(b'test');(p/'b.txt').write_text('x')
31
+ self.assertEqual(len(search.collect_images([p,p/'x/a.PNG'])),1)
32
+ with self.assertRaises(ValueError):search.collect_images([p/'missing.png'])
33
+ def test_pack_integrity(self):
34
+ with tempfile.TemporaryDirectory() as t:
35
+ p=Path(t);np.savez(p/'lda.npz',**self.model);(p/'artists.json').write_text(json.dumps(self.artists))
36
+ d={'format':'style-scout-csd-lda-v1','dimension':2,'files':{n:{'sha256':search.sha(p/n),'bytes':(p/n).stat().st_size} for n in ['lda.npz','artists.json']}}
37
+ (p/'manifest.json').write_text(json.dumps(d));search.load_pack(p);(p/'artists.json').write_text('[]')
38
+ with self.assertRaisesRegex(ValueError,'Corrupt'):search.load_pack(p)
39
+
40
+ class ImageTests(unittest.TestCase):
41
+ def test_cache_and_duplicates(self):
42
+ import csd_features as f
43
+ from PIL import Image
44
+ with tempfile.TemporaryDirectory() as t:
45
+ p=Path(t);b=io.BytesIO();Image.new('RGB',(32,32),'white').save(b,'PNG');(p/'a.png').write_bytes(b.getvalue());(p/'b.png').write_bytes(b.getvalue())
46
+ vector=np.zeros(768);vector[0]=1;model={'center':np.zeros(768),'W':np.eye(768)}
47
+ with patch.object(f,'extract',return_value=(vector,None)) as extract:
48
+ q,info=search.image_query([p/'a.png',p/'b.png'],model,{'feature_version':f.VERSION},p/'cache')
49
+ self.assertEqual(info['count'],1);self.assertEqual(info['exact_duplicates_skipped'],1);self.assertEqual(extract.call_count,1)
50
+ search.image_query([p/'a.png'],model,{'feature_version':f.VERSION},p/'cache');self.assertEqual(extract.call_count,1)
51
+ np.testing.assert_array_equal(q,vector)
52
+ def test_corrupt_image(self):
53
+ import csd_features as f
54
+ with self.assertRaises(Exception):f.prepare_image(b'broken')
55
+ def test_preview_and_projection(self):
56
+ import csd_features as f
57
+ from PIL import Image
58
+ b=io.BytesIO();Image.new('RGBA',(1800,1200),(1,50,99,100)).save(b,'PNG')
59
+ with Image.open(io.BytesIO(f.prepare_image(b.getvalue()))) as im:self.assertEqual(im.size,(1024,683));self.assertEqual(im.mode,'RGB')
60
+ class Model:
61
+ def load_state_dict(self,w,strict):self.w=w;self.strict=strict
62
+ m=Model();style=np.zeros((1024,768));f.load_visual_weights(m,{'model_state_dict':{'last_layer_style':style,'backbone.a':np.zeros(1)}})
63
+ self.assertIs(m.w['proj'],style);self.assertTrue(m.strict)
64
+ with self.assertRaises(ValueError):f.load_visual_weights(m,{})
65
+
66
+ if __name__=='__main__':unittest.main()
vendor/CLIP-LICENSE ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2021 OpenAI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
vendor/CSD-LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2024 learn2phoenix
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
vendor/__init__.py ADDED
File without changes
vendor/clip_model.py ADDED
@@ -0,0 +1,436 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import OrderedDict
2
+ from typing import Tuple, Union
3
+
4
+ import numpy as np
5
+ import torch
6
+ import torch.nn.functional as F
7
+ from torch import nn
8
+
9
+
10
+ class Bottleneck(nn.Module):
11
+ expansion = 4
12
+
13
+ def __init__(self, inplanes, planes, stride=1):
14
+ super().__init__()
15
+
16
+ # all conv layers have stride 1. an avgpool is performed after the second convolution when stride > 1
17
+ self.conv1 = nn.Conv2d(inplanes, planes, 1, bias=False)
18
+ self.bn1 = nn.BatchNorm2d(planes)
19
+ self.relu1 = nn.ReLU(inplace=True)
20
+
21
+ self.conv2 = nn.Conv2d(planes, planes, 3, padding=1, bias=False)
22
+ self.bn2 = nn.BatchNorm2d(planes)
23
+ self.relu2 = nn.ReLU(inplace=True)
24
+
25
+ self.avgpool = nn.AvgPool2d(stride) if stride > 1 else nn.Identity()
26
+
27
+ self.conv3 = nn.Conv2d(planes, planes * self.expansion, 1, bias=False)
28
+ self.bn3 = nn.BatchNorm2d(planes * self.expansion)
29
+ self.relu3 = nn.ReLU(inplace=True)
30
+
31
+ self.downsample = None
32
+ self.stride = stride
33
+
34
+ if stride > 1 or inplanes != planes * Bottleneck.expansion:
35
+ # downsampling layer is prepended with an avgpool, and the subsequent convolution has stride 1
36
+ self.downsample = nn.Sequential(OrderedDict([
37
+ ("-1", nn.AvgPool2d(stride)),
38
+ ("0", nn.Conv2d(inplanes, planes * self.expansion, 1, stride=1, bias=False)),
39
+ ("1", nn.BatchNorm2d(planes * self.expansion))
40
+ ]))
41
+
42
+ def forward(self, x: torch.Tensor):
43
+ identity = x
44
+
45
+ out = self.relu1(self.bn1(self.conv1(x)))
46
+ out = self.relu2(self.bn2(self.conv2(out)))
47
+ out = self.avgpool(out)
48
+ out = self.bn3(self.conv3(out))
49
+
50
+ if self.downsample is not None:
51
+ identity = self.downsample(x)
52
+
53
+ out += identity
54
+ out = self.relu3(out)
55
+ return out
56
+
57
+
58
+ class AttentionPool2d(nn.Module):
59
+ def __init__(self, spacial_dim: int, embed_dim: int, num_heads: int, output_dim: int = None):
60
+ super().__init__()
61
+ self.positional_embedding = nn.Parameter(torch.randn(spacial_dim ** 2 + 1, embed_dim) / embed_dim ** 0.5)
62
+ self.k_proj = nn.Linear(embed_dim, embed_dim)
63
+ self.q_proj = nn.Linear(embed_dim, embed_dim)
64
+ self.v_proj = nn.Linear(embed_dim, embed_dim)
65
+ self.c_proj = nn.Linear(embed_dim, output_dim or embed_dim)
66
+ self.num_heads = num_heads
67
+
68
+ def forward(self, x):
69
+ x = x.flatten(start_dim=2).permute(2, 0, 1) # NCHW -> (HW)NC
70
+ x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (HW+1)NC
71
+ x = x + self.positional_embedding[:, None, :].to(x.dtype) # (HW+1)NC
72
+ x, _ = F.multi_head_attention_forward(
73
+ query=x[:1], key=x, value=x,
74
+ embed_dim_to_check=x.shape[-1],
75
+ num_heads=self.num_heads,
76
+ q_proj_weight=self.q_proj.weight,
77
+ k_proj_weight=self.k_proj.weight,
78
+ v_proj_weight=self.v_proj.weight,
79
+ in_proj_weight=None,
80
+ in_proj_bias=torch.cat([self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]),
81
+ bias_k=None,
82
+ bias_v=None,
83
+ add_zero_attn=False,
84
+ dropout_p=0,
85
+ out_proj_weight=self.c_proj.weight,
86
+ out_proj_bias=self.c_proj.bias,
87
+ use_separate_proj_weight=True,
88
+ training=self.training,
89
+ need_weights=False
90
+ )
91
+ return x.squeeze(0)
92
+
93
+
94
+ class ModifiedResNet(nn.Module):
95
+ """
96
+ A ResNet class that is similar to torchvision's but contains the following changes:
97
+ - There are now 3 "stem" convolutions as opposed to 1, with an average pool instead of a max pool.
98
+ - Performs anti-aliasing strided convolutions, where an avgpool is prepended to convolutions with stride > 1
99
+ - The final pooling layer is a QKV attention instead of an average pool
100
+ """
101
+
102
+ def __init__(self, layers, output_dim, heads, input_resolution=224, width=64):
103
+ super().__init__()
104
+ self.output_dim = output_dim
105
+ self.input_resolution = input_resolution
106
+
107
+ # the 3-layer stem
108
+ self.conv1 = nn.Conv2d(3, width // 2, kernel_size=3, stride=2, padding=1, bias=False)
109
+ self.bn1 = nn.BatchNorm2d(width // 2)
110
+ self.relu1 = nn.ReLU(inplace=True)
111
+ self.conv2 = nn.Conv2d(width // 2, width // 2, kernel_size=3, padding=1, bias=False)
112
+ self.bn2 = nn.BatchNorm2d(width // 2)
113
+ self.relu2 = nn.ReLU(inplace=True)
114
+ self.conv3 = nn.Conv2d(width // 2, width, kernel_size=3, padding=1, bias=False)
115
+ self.bn3 = nn.BatchNorm2d(width)
116
+ self.relu3 = nn.ReLU(inplace=True)
117
+ self.avgpool = nn.AvgPool2d(2)
118
+
119
+ # residual layers
120
+ self._inplanes = width # this is a *mutable* variable used during construction
121
+ self.layer1 = self._make_layer(width, layers[0])
122
+ self.layer2 = self._make_layer(width * 2, layers[1], stride=2)
123
+ self.layer3 = self._make_layer(width * 4, layers[2], stride=2)
124
+ self.layer4 = self._make_layer(width * 8, layers[3], stride=2)
125
+
126
+ embed_dim = width * 32 # the ResNet feature dimension
127
+ self.attnpool = AttentionPool2d(input_resolution // 32, embed_dim, heads, output_dim)
128
+
129
+ def _make_layer(self, planes, blocks, stride=1):
130
+ layers = [Bottleneck(self._inplanes, planes, stride)]
131
+
132
+ self._inplanes = planes * Bottleneck.expansion
133
+ for _ in range(1, blocks):
134
+ layers.append(Bottleneck(self._inplanes, planes))
135
+
136
+ return nn.Sequential(*layers)
137
+
138
+ def forward(self, x):
139
+ def stem(x):
140
+ x = self.relu1(self.bn1(self.conv1(x)))
141
+ x = self.relu2(self.bn2(self.conv2(x)))
142
+ x = self.relu3(self.bn3(self.conv3(x)))
143
+ x = self.avgpool(x)
144
+ return x
145
+
146
+ x = x.type(self.conv1.weight.dtype)
147
+ x = stem(x)
148
+ x = self.layer1(x)
149
+ x = self.layer2(x)
150
+ x = self.layer3(x)
151
+ x = self.layer4(x)
152
+ x = self.attnpool(x)
153
+
154
+ return x
155
+
156
+
157
+ class LayerNorm(nn.LayerNorm):
158
+ """Subclass torch's LayerNorm to handle fp16."""
159
+
160
+ def forward(self, x: torch.Tensor):
161
+ orig_type = x.dtype
162
+ ret = super().forward(x.type(torch.float32))
163
+ return ret.type(orig_type)
164
+
165
+
166
+ class QuickGELU(nn.Module):
167
+ def forward(self, x: torch.Tensor):
168
+ return x * torch.sigmoid(1.702 * x)
169
+
170
+
171
+ class ResidualAttentionBlock(nn.Module):
172
+ def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None):
173
+ super().__init__()
174
+
175
+ self.attn = nn.MultiheadAttention(d_model, n_head)
176
+ self.ln_1 = LayerNorm(d_model)
177
+ self.mlp = nn.Sequential(OrderedDict([
178
+ ("c_fc", nn.Linear(d_model, d_model * 4)),
179
+ ("gelu", QuickGELU()),
180
+ ("c_proj", nn.Linear(d_model * 4, d_model))
181
+ ]))
182
+ self.ln_2 = LayerNorm(d_model)
183
+ self.attn_mask = attn_mask
184
+
185
+ def attention(self, x: torch.Tensor):
186
+ self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None
187
+ return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0]
188
+
189
+ def forward(self, x: torch.Tensor):
190
+ x = x + self.attention(self.ln_1(x))
191
+ x = x + self.mlp(self.ln_2(x))
192
+ return x
193
+
194
+
195
+ class Transformer(nn.Module):
196
+ def __init__(self, width: int, layers: int, heads: int, attn_mask: torch.Tensor = None):
197
+ super().__init__()
198
+ self.width = width
199
+ self.layers = layers
200
+ self.resblocks = nn.Sequential(*[ResidualAttentionBlock(width, heads, attn_mask) for _ in range(layers)])
201
+
202
+ def forward(self, x: torch.Tensor):
203
+ return self.resblocks(x)
204
+
205
+
206
+ class VisionTransformer(nn.Module):
207
+ def __init__(self, input_resolution: int, patch_size: int, width: int, layers: int, heads: int, output_dim: int):
208
+ super().__init__()
209
+ self.input_resolution = input_resolution
210
+ self.output_dim = output_dim
211
+ self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False)
212
+
213
+ scale = width ** -0.5
214
+ self.class_embedding = nn.Parameter(scale * torch.randn(width))
215
+ self.positional_embedding = nn.Parameter(scale * torch.randn((input_resolution // patch_size) ** 2 + 1, width))
216
+ self.ln_pre = LayerNorm(width)
217
+
218
+ self.transformer = Transformer(width, layers, heads)
219
+
220
+ self.ln_post = LayerNorm(width)
221
+ self.proj = nn.Parameter(scale * torch.randn(width, output_dim))
222
+
223
+ def forward(self, x: torch.Tensor):
224
+ x = self.conv1(x) # shape = [*, width, grid, grid]
225
+ x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]
226
+ x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]
227
+ x = torch.cat([self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device), x], dim=1) # shape = [*, grid ** 2 + 1, width]
228
+ x = x + self.positional_embedding.to(x.dtype)
229
+ x = self.ln_pre(x)
230
+
231
+ x = x.permute(1, 0, 2) # NLD -> LND
232
+ x = self.transformer(x)
233
+ x = x.permute(1, 0, 2) # LND -> NLD
234
+
235
+ x = self.ln_post(x[:, 0, :])
236
+
237
+ if self.proj is not None:
238
+ x = x @ self.proj
239
+
240
+ return x
241
+
242
+
243
+ class CLIP(nn.Module):
244
+ def __init__(self,
245
+ embed_dim: int,
246
+ # vision
247
+ image_resolution: int,
248
+ vision_layers: Union[Tuple[int, int, int, int], int],
249
+ vision_width: int,
250
+ vision_patch_size: int,
251
+ # text
252
+ context_length: int,
253
+ vocab_size: int,
254
+ transformer_width: int,
255
+ transformer_heads: int,
256
+ transformer_layers: int
257
+ ):
258
+ super().__init__()
259
+
260
+ self.context_length = context_length
261
+
262
+ if isinstance(vision_layers, (tuple, list)):
263
+ vision_heads = vision_width * 32 // 64
264
+ self.visual = ModifiedResNet(
265
+ layers=vision_layers,
266
+ output_dim=embed_dim,
267
+ heads=vision_heads,
268
+ input_resolution=image_resolution,
269
+ width=vision_width
270
+ )
271
+ else:
272
+ vision_heads = vision_width // 64
273
+ self.visual = VisionTransformer(
274
+ input_resolution=image_resolution,
275
+ patch_size=vision_patch_size,
276
+ width=vision_width,
277
+ layers=vision_layers,
278
+ heads=vision_heads,
279
+ output_dim=embed_dim
280
+ )
281
+
282
+ self.transformer = Transformer(
283
+ width=transformer_width,
284
+ layers=transformer_layers,
285
+ heads=transformer_heads,
286
+ attn_mask=self.build_attention_mask()
287
+ )
288
+
289
+ self.vocab_size = vocab_size
290
+ self.token_embedding = nn.Embedding(vocab_size, transformer_width)
291
+ self.positional_embedding = nn.Parameter(torch.empty(self.context_length, transformer_width))
292
+ self.ln_final = LayerNorm(transformer_width)
293
+
294
+ self.text_projection = nn.Parameter(torch.empty(transformer_width, embed_dim))
295
+ self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07))
296
+
297
+ self.initialize_parameters()
298
+
299
+ def initialize_parameters(self):
300
+ nn.init.normal_(self.token_embedding.weight, std=0.02)
301
+ nn.init.normal_(self.positional_embedding, std=0.01)
302
+
303
+ if isinstance(self.visual, ModifiedResNet):
304
+ if self.visual.attnpool is not None:
305
+ std = self.visual.attnpool.c_proj.in_features ** -0.5
306
+ nn.init.normal_(self.visual.attnpool.q_proj.weight, std=std)
307
+ nn.init.normal_(self.visual.attnpool.k_proj.weight, std=std)
308
+ nn.init.normal_(self.visual.attnpool.v_proj.weight, std=std)
309
+ nn.init.normal_(self.visual.attnpool.c_proj.weight, std=std)
310
+
311
+ for resnet_block in [self.visual.layer1, self.visual.layer2, self.visual.layer3, self.visual.layer4]:
312
+ for name, param in resnet_block.named_parameters():
313
+ if name.endswith("bn3.weight"):
314
+ nn.init.zeros_(param)
315
+
316
+ proj_std = (self.transformer.width ** -0.5) * ((2 * self.transformer.layers) ** -0.5)
317
+ attn_std = self.transformer.width ** -0.5
318
+ fc_std = (2 * self.transformer.width) ** -0.5
319
+ for block in self.transformer.resblocks:
320
+ nn.init.normal_(block.attn.in_proj_weight, std=attn_std)
321
+ nn.init.normal_(block.attn.out_proj.weight, std=proj_std)
322
+ nn.init.normal_(block.mlp.c_fc.weight, std=fc_std)
323
+ nn.init.normal_(block.mlp.c_proj.weight, std=proj_std)
324
+
325
+ if self.text_projection is not None:
326
+ nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5)
327
+
328
+ def build_attention_mask(self):
329
+ # lazily create causal attention mask, with full attention between the vision tokens
330
+ # pytorch uses additive attention mask; fill with -inf
331
+ mask = torch.empty(self.context_length, self.context_length)
332
+ mask.fill_(float("-inf"))
333
+ mask.triu_(1) # zero out the lower diagonal
334
+ return mask
335
+
336
+ @property
337
+ def dtype(self):
338
+ return self.visual.conv1.weight.dtype
339
+
340
+ def encode_image(self, image):
341
+ return self.visual(image.type(self.dtype))
342
+
343
+ def encode_text(self, text):
344
+ x = self.token_embedding(text).type(self.dtype) # [batch_size, n_ctx, d_model]
345
+
346
+ x = x + self.positional_embedding.type(self.dtype)
347
+ x = x.permute(1, 0, 2) # NLD -> LND
348
+ x = self.transformer(x)
349
+ x = x.permute(1, 0, 2) # LND -> NLD
350
+ x = self.ln_final(x).type(self.dtype)
351
+
352
+ # x.shape = [batch_size, n_ctx, transformer.width]
353
+ # take features from the eot embedding (eot_token is the highest number in each sequence)
354
+ x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection
355
+
356
+ return x
357
+
358
+ def forward(self, image, text):
359
+ image_features = self.encode_image(image)
360
+ text_features = self.encode_text(text)
361
+
362
+ # normalized features
363
+ image_features = image_features / image_features.norm(dim=1, keepdim=True)
364
+ text_features = text_features / text_features.norm(dim=1, keepdim=True)
365
+
366
+ # cosine similarity as logits
367
+ logit_scale = self.logit_scale.exp()
368
+ logits_per_image = logit_scale * image_features @ text_features.t()
369
+ logits_per_text = logits_per_image.t()
370
+
371
+ # shape = [global_batch_size, global_batch_size]
372
+ return logits_per_image, logits_per_text
373
+
374
+
375
+ def convert_weights(model: nn.Module):
376
+ """Convert applicable model parameters to fp16"""
377
+
378
+ def _convert_weights_to_fp16(l):
379
+ if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)):
380
+ l.weight.data = l.weight.data.half()
381
+ if l.bias is not None:
382
+ l.bias.data = l.bias.data.half()
383
+
384
+ if isinstance(l, nn.MultiheadAttention):
385
+ for attr in [*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], "in_proj_bias", "bias_k", "bias_v"]:
386
+ tensor = getattr(l, attr)
387
+ if tensor is not None:
388
+ tensor.data = tensor.data.half()
389
+
390
+ for name in ["text_projection", "proj"]:
391
+ if hasattr(l, name):
392
+ attr = getattr(l, name)
393
+ if attr is not None:
394
+ attr.data = attr.data.half()
395
+
396
+ model.apply(_convert_weights_to_fp16)
397
+
398
+
399
+ def build_model(state_dict: dict):
400
+ vit = "visual.proj" in state_dict
401
+
402
+ if vit:
403
+ vision_width = state_dict["visual.conv1.weight"].shape[0]
404
+ vision_layers = len([k for k in state_dict.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")])
405
+ vision_patch_size = state_dict["visual.conv1.weight"].shape[-1]
406
+ grid_size = round((state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5)
407
+ image_resolution = vision_patch_size * grid_size
408
+ else:
409
+ counts: list = [len(set(k.split(".")[2] for k in state_dict if k.startswith(f"visual.layer{b}"))) for b in [1, 2, 3, 4]]
410
+ vision_layers = tuple(counts)
411
+ vision_width = state_dict["visual.layer1.0.conv1.weight"].shape[0]
412
+ output_width = round((state_dict["visual.attnpool.positional_embedding"].shape[0] - 1) ** 0.5)
413
+ vision_patch_size = None
414
+ assert output_width ** 2 + 1 == state_dict["visual.attnpool.positional_embedding"].shape[0]
415
+ image_resolution = output_width * 32
416
+
417
+ embed_dim = state_dict["text_projection"].shape[1]
418
+ context_length = state_dict["positional_embedding"].shape[0]
419
+ vocab_size = state_dict["token_embedding.weight"].shape[0]
420
+ transformer_width = state_dict["ln_final.weight"].shape[0]
421
+ transformer_heads = transformer_width // 64
422
+ transformer_layers = len(set(k.split(".")[2] for k in state_dict if k.startswith("transformer.resblocks")))
423
+
424
+ model = CLIP(
425
+ embed_dim,
426
+ image_resolution, vision_layers, vision_width, vision_patch_size,
427
+ context_length, vocab_size, transformer_width, transformer_heads, transformer_layers
428
+ )
429
+
430
+ for key in ["input_resolution", "context_length", "vocab_size"]:
431
+ if key in state_dict:
432
+ del state_dict[key]
433
+
434
+ convert_weights(model)
435
+ model.load_state_dict(state_dict)
436
+ return model.eval()