bertopic-ja 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of bertopic-ja might be problematic. Click here for more details.

@@ -0,0 +1,14 @@
1
+ """日本語文書の探索的トピック分析。
2
+
3
+ 手法と実装の本体は Maarten Grootendorst の BERTopic です。
4
+ このパッケージは公式のサブプロジェクトではなく、Sudachi による分かち書きと
5
+ トピック語の調整メソッドを足した第三者の入口です。
6
+
7
+ https://github.com/MaartenGr/BERTopic
8
+ https://arxiv.org/abs/2203.05794
9
+ """
10
+
11
+ from bertopic_ja._model import BERTopic
12
+
13
+ __all__ = ["BERTopic"]
14
+ __version__ = "0.1.0"
bertopic_ja/_config.py ADDED
@@ -0,0 +1,83 @@
1
+ """引数と YAML で共有する設定。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ import yaml
10
+
11
+ _FIELDS = (
12
+ "min_topic_size",
13
+ "nr_topics",
14
+ "n_neighbors",
15
+ "reduce_outliers",
16
+ "embedding_model",
17
+ "exclude",
18
+ "protect",
19
+ "fillers",
20
+ )
21
+
22
+
23
+ @dataclass
24
+ class Config:
25
+ """フィット時の設定。引数と YAML は同じ項目を持つ。"""
26
+
27
+ min_topic_size: int = 10
28
+ nr_topics: int | str | None = None
29
+ n_neighbors: int | None = None
30
+ reduce_outliers: bool = True
31
+ embedding_model: Any = None
32
+ exclude: list[str] = field(default_factory=list)
33
+ protect: list[str] = field(default_factory=list)
34
+ fillers: list[str] = field(default_factory=list)
35
+
36
+ @classmethod
37
+ def from_mapping(cls, data: dict[str, Any] | None, overrides: dict[str, Any] | None = None) -> Config:
38
+ merged: dict[str, Any] = dict(data or {})
39
+ if overrides:
40
+ merged.update(overrides)
41
+ unknown = sorted(set(merged) - set(_FIELDS))
42
+ if unknown:
43
+ names = ", ".join(unknown)
44
+ raise ValueError(f"未知の設定項目です: {names}")
45
+ for key in ("exclude", "protect", "fillers"):
46
+ value = merged.get(key)
47
+ if value is None:
48
+ merged[key] = []
49
+ elif not isinstance(value, list):
50
+ raise ValueError(f"{key} は文字列のリストです。")
51
+ else:
52
+ merged[key] = [str(item) for item in value]
53
+ if "min_topic_size" in merged:
54
+ merged["min_topic_size"] = int(merged["min_topic_size"])
55
+ if "n_neighbors" in merged and merged["n_neighbors"] is not None:
56
+ merged["n_neighbors"] = int(merged["n_neighbors"])
57
+ return cls(**merged)
58
+
59
+ @classmethod
60
+ def from_yaml(cls, path: str | Path, overrides: dict[str, Any] | None = None) -> Config:
61
+ loaded = yaml.safe_load(Path(path).read_text(encoding="utf-8"))
62
+ if loaded is None:
63
+ loaded = {}
64
+ if not isinstance(loaded, dict):
65
+ raise ValueError("YAML の先頭は設定項目のマップにしてください。")
66
+ return cls.from_mapping(loaded, overrides)
67
+
68
+ def to_dict(self) -> dict[str, Any]:
69
+ embedding_model = self.embedding_model if isinstance(self.embedding_model, str) else None
70
+ return {
71
+ "min_topic_size": self.min_topic_size,
72
+ "nr_topics": self.nr_topics,
73
+ "n_neighbors": self.n_neighbors,
74
+ "reduce_outliers": self.reduce_outliers,
75
+ "embedding_model": embedding_model,
76
+ "exclude": list(self.exclude),
77
+ "protect": list(self.protect),
78
+ "fillers": list(self.fillers),
79
+ }
80
+
81
+ def to_yaml(self, path: str | Path) -> None:
82
+ text = yaml.safe_dump(self.to_dict(), allow_unicode=True, sort_keys=False)
83
+ Path(path).write_text(text, encoding="utf-8")
bertopic_ja/_model.py ADDED
@@ -0,0 +1,314 @@
1
+ """BERTopic を日本語の初期値で包む。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ import pandas as pd
9
+ from bertopic import BERTopic as _BERTopic
10
+ from bertopic.representation import KeyBERTInspired
11
+ from hdbscan import HDBSCAN
12
+ from umap import UMAP
13
+
14
+ from bertopic_ja._config import Config
15
+ from bertopic_ja._tokenizer import build_vectorizer, explain_text, strip_fillers
16
+
17
+
18
+ class BERTopic(_BERTopic):
19
+ """日本語文書から、どんなトピックが話されているかを探索する。
20
+
21
+ 呼び出し方は公式の BERTopic と同じです。埋め込みの初期値は
22
+ ``language="multilingual"`` です。トピック語は Sudachi(モード C)の
23
+ 名詞で、フィラーはトピック語からだけ外します。
24
+
25
+ これは Maarten Grootendorst の BERTopic の公式サブプロジェクトでは
26
+ ありません。https://github.com/MaartenGr/BERTopic
27
+ """
28
+
29
+ def __init__(
30
+ self,
31
+ *,
32
+ min_topic_size: int = 10,
33
+ nr_topics: int | str | None = None,
34
+ n_neighbors: int | None = None,
35
+ reduce_outliers: bool = True,
36
+ embedding_model: Any = None,
37
+ exclude: list[str] | None = None,
38
+ protect: list[str] | None = None,
39
+ fillers: list[str] | None = None,
40
+ ) -> None:
41
+ self.ja_config = Config(
42
+ min_topic_size=min_topic_size,
43
+ nr_topics=nr_topics,
44
+ n_neighbors=n_neighbors,
45
+ reduce_outliers=reduce_outliers,
46
+ embedding_model=embedding_model,
47
+ exclude=list(exclude or []),
48
+ protect=list(protect or []),
49
+ fillers=list(fillers or []),
50
+ )
51
+ self._documents: list[str] = []
52
+ self._embeddings = None
53
+ self._fitted = False
54
+ umap_model = self._make_umap(n_docs=max(min_topic_size + 2, 32))
55
+ init_kwargs: dict[str, Any] = {
56
+ "language": "multilingual",
57
+ "umap_model": umap_model,
58
+ "hdbscan_model": self._make_hdbscan(self.ja_config.min_topic_size),
59
+ "vectorizer_model": build_vectorizer(self.ja_config),
60
+ "representation_model": KeyBERTInspired(),
61
+ "min_topic_size": self.ja_config.min_topic_size,
62
+ "nr_topics": self.ja_config.nr_topics,
63
+ "calculate_probabilities": False,
64
+ "verbose": False,
65
+ }
66
+ if embedding_model is not None:
67
+ init_kwargs["embedding_model"] = embedding_model
68
+ super().__init__(**init_kwargs)
69
+
70
+ @classmethod
71
+ def from_yaml(cls, path: str | Path, **overrides: Any) -> BERTopic:
72
+ """YAML を読み、同じ項目の引数があれば引数を優先する。"""
73
+ config = Config.from_yaml(path, overrides)
74
+ return cls(
75
+ min_topic_size=config.min_topic_size,
76
+ nr_topics=config.nr_topics,
77
+ n_neighbors=config.n_neighbors,
78
+ reduce_outliers=config.reduce_outliers,
79
+ embedding_model=config.embedding_model,
80
+ exclude=config.exclude,
81
+ protect=config.protect,
82
+ fillers=config.fillers,
83
+ )
84
+
85
+ def to_yaml(self, path: str | Path) -> None:
86
+ """今の設定を YAML に書き戻す。"""
87
+ self.ja_config.to_yaml(path)
88
+
89
+ def fit_transform(self, documents, embeddings=None, **kwargs):
90
+ """文書をクラスタリングし、トピック番号の列を返す。"""
91
+ docs = self._prepare_documents(documents)
92
+ self._documents = docs
93
+ self.umap_model = self._make_umap(len(docs))
94
+ self.hdbscan_model = self._make_hdbscan(self.ja_config.min_topic_size)
95
+ if embeddings is None:
96
+ embeddings = self.embedding_model.embed(docs)
97
+ self._embeddings = embeddings
98
+ topics, probs = super().fit_transform(docs, embeddings=embeddings, **kwargs)
99
+ if self.ja_config.reduce_outliers:
100
+ topics = self._apply_outlier_reduction(docs, topics)
101
+ self._drop_blank_topic_words()
102
+ self._fitted = True
103
+ return topics, probs
104
+
105
+ def exclude(self, *words: str | list[str]) -> pd.DataFrame | None:
106
+ """トピック語から外す。埋め込みとクラスタは変えない。"""
107
+ for word in _flatten(words):
108
+ if word not in self.ja_config.exclude:
109
+ self.ja_config.exclude.append(word)
110
+ self._replace_vectorizer(update=self._fitted)
111
+ if not self._fitted:
112
+ return None
113
+ return self.get_topic_info()
114
+
115
+ def refit(self, min_topic_size: int | None = None, nr_topics: int | str | None = None):
116
+ """クラスタの粗さだけを変えて学習し直す。埋め込みは再利用する。"""
117
+ self._check_fitted()
118
+ if min_topic_size is not None:
119
+ self.ja_config.min_topic_size = int(min_topic_size)
120
+ self.min_topic_size = self.ja_config.min_topic_size
121
+ self.hdbscan_model = self._make_hdbscan(self.ja_config.min_topic_size)
122
+ if nr_topics is not None:
123
+ self.ja_config.nr_topics = nr_topics
124
+ self.nr_topics = nr_topics
125
+ self.umap_model = self._make_umap(len(self._documents))
126
+ topics, probs = super().fit_transform(self._documents, embeddings=self._embeddings)
127
+ if self.ja_config.reduce_outliers:
128
+ topics = self._apply_outlier_reduction(self._documents, topics)
129
+ self._drop_blank_topic_words()
130
+ return topics, probs
131
+
132
+ def suggest(self) -> pd.DataFrame:
133
+ """多くのトピックに出る語を、文書頻度とともに返す。"""
134
+ self._check_fitted()
135
+ topic_words = self.get_topics()
136
+ topic_ids = [topic_id for topic_id in topic_words if topic_id != -1]
137
+ in_topics: dict[str, int] = {}
138
+ for topic_id in topic_ids:
139
+ seen: set[str] = set()
140
+ for word, _score in topic_words[topic_id]:
141
+ if word and word not in seen:
142
+ seen.add(word)
143
+ in_topics[word] = in_topics.get(word, 0) + 1
144
+ analyzer = self.vectorizer_model.build_analyzer()
145
+ doc_counts: dict[str, int] = {}
146
+ for document in self._documents:
147
+ for token in set(analyzer(document)):
148
+ doc_counts[token] = doc_counts.get(token, 0) + 1
149
+ n_topics = max(len(topic_ids), 1)
150
+ n_docs = max(len(self._documents), 1)
151
+ rows = []
152
+ for token in set(in_topics) | set(doc_counts):
153
+ topic_count = in_topics.get(token, 0)
154
+ rows.append(
155
+ {
156
+ "token": token,
157
+ "n_topics": topic_count,
158
+ "topic_fraction": round(topic_count / n_topics, 3),
159
+ "doc_frequency": round(doc_counts.get(token, 0) / n_docs, 3),
160
+ }
161
+ )
162
+ frame = pd.DataFrame(rows, columns=["token", "n_topics", "topic_fraction", "doc_frequency"])
163
+ if frame.empty:
164
+ return frame
165
+ return frame.sort_values(["topic_fraction", "doc_frequency"], ascending=False).reset_index(drop=True)
166
+
167
+ def explain(self, text: str) -> dict[str, list]:
168
+ """1文について、残す語と落とした理由を返す。"""
169
+ return explain_text(text, self.ja_config)
170
+
171
+ def preview_exclude(self, words: list[str]) -> list[dict[str, Any]]:
172
+ """除外したあとのトピック語を、設定を変えずに見る。"""
173
+ self._check_fitted()
174
+ before = _topic_words(self)
175
+ old_exclude = list(self.ja_config.exclude)
176
+ old_vectorizer = self.vectorizer_model
177
+ old_representation = self.representation_model
178
+ try:
179
+ self.ja_config.exclude = old_exclude + [word for word in words if word not in old_exclude]
180
+ self.vectorizer_model = build_vectorizer(self.ja_config)
181
+ self.update_topics(
182
+ self._documents,
183
+ vectorizer_model=self.vectorizer_model,
184
+ representation_model=old_representation,
185
+ )
186
+ self._drop_blank_topic_words()
187
+ after = _topic_words(self)
188
+ finally:
189
+ self.ja_config.exclude = old_exclude
190
+ self.vectorizer_model = old_vectorizer
191
+ self.update_topics(
192
+ self._documents,
193
+ vectorizer_model=old_vectorizer,
194
+ representation_model=old_representation,
195
+ )
196
+ self._drop_blank_topic_words()
197
+ topic_ids = sorted(set(before) | set(after))
198
+ return [
199
+ {"topic": topic_id, "before": before.get(topic_id, []), "after": after.get(topic_id, [])}
200
+ for topic_id in topic_ids
201
+ ]
202
+
203
+ def _prepare_documents(self, documents) -> list[str]:
204
+ docs = ["" if document is None else str(document) for document in documents]
205
+ if len(docs) < 3:
206
+ raise ValueError("文書は3件以上必要です。")
207
+ if self.ja_config.min_topic_size >= len(docs):
208
+ raise ValueError("min_topic_size は文書数より小さくしてください。")
209
+ if not self.ja_config.fillers:
210
+ return docs
211
+ return [strip_fillers(document, self.ja_config.fillers) for document in docs]
212
+
213
+ def _replace_vectorizer(self, update: bool) -> None:
214
+ self.vectorizer_model = build_vectorizer(self.ja_config)
215
+ if not update:
216
+ return
217
+ self.update_topics(
218
+ self._documents,
219
+ vectorizer_model=self.vectorizer_model,
220
+ representation_model=self.representation_model,
221
+ )
222
+ self._drop_blank_topic_words()
223
+
224
+ def _apply_outlier_reduction(self, documents: list[str], topics) -> list[int]:
225
+ if topics is None or -1 not in set(topics):
226
+ return topics
227
+ updated = self.reduce_outliers(documents, topics)
228
+ self.update_topics(
229
+ documents,
230
+ topics=updated,
231
+ vectorizer_model=self.vectorizer_model,
232
+ representation_model=self.representation_model,
233
+ )
234
+ self._drop_blank_topic_words()
235
+ return list(self.topics_)
236
+
237
+ def _make_umap(self, n_docs: int) -> UMAP:
238
+ neighbors = self.ja_config.n_neighbors
239
+ if neighbors is None:
240
+ neighbors = 5 if n_docs < 500 else 15
241
+ neighbors = max(2, min(int(neighbors), max(n_docs - 1, 2)))
242
+ n_components = min(5, neighbors - 1)
243
+ options: dict[str, Any] = {
244
+ "n_neighbors": neighbors,
245
+ "n_components": n_components,
246
+ "min_dist": 0.0,
247
+ "metric": "cosine",
248
+ "random_state": 42,
249
+ "init": "random",
250
+ "n_jobs": 1,
251
+ "compatibility_layout": True,
252
+ }
253
+ try:
254
+ return UMAP(**options)
255
+ except TypeError:
256
+ options.pop("compatibility_layout")
257
+ return UMAP(**options)
258
+
259
+ def _make_hdbscan(self, min_topic_size: int) -> HDBSCAN:
260
+ return HDBSCAN(
261
+ min_cluster_size=min_topic_size,
262
+ min_samples=max(1, min_topic_size // 2),
263
+ metric="euclidean",
264
+ cluster_selection_method="eom",
265
+ prediction_data=True,
266
+ )
267
+
268
+ def _drop_blank_topic_words(self) -> None:
269
+ """空文字だけのトピック語を、そのトピックの名詞の出現順に戻す。
270
+
271
+ KeyBERTInspired は候補語が少ないと空文字を足す。類似度で空文字が
272
+ 上位になると、トピック名が空白になる。
273
+ """
274
+ representations = getattr(self, "topic_representations_", None)
275
+ if not representations:
276
+ return
277
+ repaired: dict[int, list[tuple[str, float]]] = {}
278
+ for topic_id, pairs in representations.items():
279
+ words = [(str(word), float(score)) for word, score in pairs if word]
280
+ repaired[topic_id] = words or self._words_from_documents(topic_id)
281
+ self.topic_representations_ = repaired
282
+
283
+ def _words_from_documents(self, topic_id: int) -> list[tuple[str, float]]:
284
+ analyzer = self.vectorizer_model.build_analyzer()
285
+ counts: dict[str, int] = {}
286
+ for document, topic in zip(self._documents, self.topics_):
287
+ if topic != topic_id:
288
+ continue
289
+ for token in analyzer(document):
290
+ if token:
291
+ counts[token] = counts.get(token, 0) + 1
292
+ ranked = sorted(counts.items(), key=lambda item: item[1], reverse=True)
293
+ return [(word, float(count)) for word, count in ranked[:10]]
294
+
295
+ def _check_fitted(self) -> None:
296
+ if not self._fitted:
297
+ raise RuntimeError("fit_transform を先に呼んでください。")
298
+
299
+
300
+ def _flatten(words: tuple[str | list[str], ...]) -> list[str]:
301
+ flat: list[str] = []
302
+ for word in words:
303
+ if isinstance(word, (list, tuple, set)):
304
+ flat.extend(str(item) for item in word)
305
+ else:
306
+ flat.append(str(word))
307
+ return flat
308
+
309
+
310
+ def _topic_words(model: BERTopic) -> dict[int, list[str]]:
311
+ return {
312
+ topic_id: [word for word, _score in words]
313
+ for topic_id, words in model.get_topics().items()
314
+ }
@@ -0,0 +1,148 @@
1
+ """Sudachi によるトピック語の抽出。
2
+
3
+ フィラーはトピック語から外す。本文からの削除は fillers を渡したときだけで、
4
+ そのときもトークン単位で行い、名詞・連体詞は残す。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from functools import lru_cache
10
+
11
+ from sklearn.feature_extraction.text import CountVectorizer
12
+
13
+ from bertopic_ja._config import Config
14
+
15
+ # 感動詞として取りこぼしたときのための完全一致。指示語の「あの」は含めない。
16
+ FILLER_TOKENS = frozenset(
17
+ {
18
+ "えー",
19
+ "えーっと",
20
+ "えーと",
21
+ "あのー",
22
+ "あのぉ",
23
+ "まあ",
24
+ "まぁ",
25
+ "まー",
26
+ }
27
+ )
28
+
29
+ # 本文からフィラーを消すとき、この品詞は残す。「あの車」の「あの」は連体詞。
30
+ _KEEP_WHEN_STRIPPING = frozenset({"名詞", "動詞", "形容詞", "連体詞"})
31
+
32
+
33
+ @lru_cache(maxsize=1)
34
+ def tokenizer():
35
+ """Sudachi のタグガーと分割モード C を返す。"""
36
+ try:
37
+ from sudachipy import Dictionary, SplitMode
38
+ except ImportError: # sudachipy 0.6
39
+ from sudachipy.dictionary import Dictionary
40
+ from sudachipy.tokenizer import Tokenizer
41
+
42
+ SplitMode = Tokenizer.SplitMode
43
+
44
+ dictionary = Dictionary()
45
+ tagger = dictionary.create() if hasattr(dictionary, "create") else dictionary.tokenizer()
46
+ return tagger, SplitMode.C
47
+
48
+
49
+ def _forms(morpheme) -> tuple[str, str]:
50
+ surface = morpheme.surface()
51
+ try:
52
+ normalized = morpheme.normalized_form()
53
+ except Exception:
54
+ normalized = surface
55
+ if not normalized:
56
+ normalized = surface
57
+ return surface, normalized
58
+
59
+
60
+ def iter_morphemes(text: str):
61
+ if not text or not str(text).strip():
62
+ return
63
+ tagger, mode = tokenizer()
64
+ for morpheme in tagger.tokenize(str(text), mode):
65
+ yield morpheme
66
+
67
+
68
+ def strip_fillers(text: str, fillers: list[str]) -> str:
69
+ """指定したフィラーを、トークン単位で本文から外す。"""
70
+ targets = set(fillers)
71
+ if not targets or not text:
72
+ return "" if text is None else str(text)
73
+ kept: list[str] = []
74
+ for morpheme in iter_morphemes(text):
75
+ surface, normalized = _forms(morpheme)
76
+ pos = morpheme.part_of_speech()[0]
77
+ listed = surface in targets or normalized in targets
78
+ if listed and pos not in _KEEP_WHEN_STRIPPING:
79
+ continue
80
+ kept.append(surface)
81
+ return "".join(kept)
82
+
83
+
84
+ def explain_text(text: str, config: Config) -> dict[str, list]:
85
+ """1文について、残す語と落とした理由を返す。"""
86
+ kept: list[str] = []
87
+ dropped: list[dict[str, str]] = []
88
+ protect = set(config.protect)
89
+ exclude = set(config.exclude)
90
+ for morpheme in iter_morphemes(text):
91
+ surface, normalized = _forms(morpheme)
92
+ pos = morpheme.part_of_speech()
93
+ pos_main = pos[0] if pos else ""
94
+ pos_sub = pos[1] if len(pos) > 1 else ""
95
+ token = normalized or surface
96
+ reason = _drop_reason(token, surface, pos_main, pos_sub, protect, exclude)
97
+ if reason is None:
98
+ kept.append(token)
99
+ else:
100
+ dropped.append({"token": surface, "reason": reason})
101
+ return {"kept": kept, "dropped": dropped}
102
+
103
+
104
+ def _drop_reason(
105
+ token: str,
106
+ surface: str,
107
+ pos_main: str,
108
+ pos_sub: str,
109
+ protect: set[str],
110
+ exclude: set[str],
111
+ ) -> str | None:
112
+ if token in protect or surface in protect:
113
+ return None
114
+ if token in FILLER_TOKENS or surface in FILLER_TOKENS:
115
+ return "フィラー"
116
+ if pos_main == "感動詞":
117
+ return "感動詞"
118
+ if token in exclude or surface in exclude:
119
+ return "除外"
120
+ if pos_main != "名詞":
121
+ return pos_main or "品詞"
122
+ if pos_sub in {"代名詞", "数詞"}:
123
+ return pos_sub
124
+ if len(token) <= 1:
125
+ return "1文字"
126
+ if token.isdigit():
127
+ return "数"
128
+ return None
129
+
130
+
131
+ def build_vectorizer(config: Config) -> CountVectorizer:
132
+ """トピック語専用の CountVectorizer。クラスタ分けには使わない。"""
133
+ protect = set(config.protect)
134
+ exclude = set(config.exclude)
135
+
136
+ def analyze(text: str) -> list[str]:
137
+ words: list[str] = []
138
+ for morpheme in iter_morphemes(text):
139
+ _surface, normalized = _forms(morpheme)
140
+ pos = morpheme.part_of_speech()
141
+ pos_main = pos[0] if pos else ""
142
+ pos_sub = pos[1] if len(pos) > 1 else ""
143
+ token = normalized or _surface
144
+ if _drop_reason(token, _surface, pos_main, pos_sub, protect, exclude) is None:
145
+ words.append(token)
146
+ return words
147
+
148
+ return CountVectorizer(analyzer=analyze, token_pattern=None)
@@ -0,0 +1,130 @@
1
+ Metadata-Version: 2.5
2
+ Name: bertopic-ja
3
+ Version: 0.1.0
4
+ Summary: 日本語の文書から、どんなトピックが話されているかを探索するための BERTopic。Sudachi でトピック語を分かち書きします。
5
+ Project-URL: BERTopic, https://github.com/MaartenGr/BERTopic
6
+ Project-URL: Documentation, https://maartengr.github.io/BERTopic/
7
+ Project-URL: BERTopic Paper, https://arxiv.org/abs/2203.05794
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: bertopic,japanese,nlp,topic-modeling,topic-modelling,トピックモデル,トピック分析,日本語,話題
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Natural Language :: Japanese
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
21
+ Classifier: Topic :: Text Processing :: Linguistic
22
+ Requires-Python: >=3.10
23
+ Requires-Dist: bertopic<1,>=0.17.4
24
+ Requires-Dist: numpy>=1.20
25
+ Requires-Dist: pandas>=1.1.5
26
+ Requires-Dist: pyyaml>=6
27
+ Requires-Dist: sudachidict-core>=20230927
28
+ Requires-Dist: sudachipy<0.7,>=0.6.8
29
+ Description-Content-Type: text/markdown
30
+
31
+ # bertopic-ja
32
+
33
+ 日本語の文書から、どんなトピックが話されているかを探索するなら [BERTopic](https://github.com/MaartenGr/BERTopic) です。埋め込み、UMAP、HDBSCAN、c-TF-IDF という今の探索的トピックモデルの手順を、日本語のトピック語が単語になる状態で始められます。
34
+
35
+ このパッケージはその入口です。公式 BERTopic のサブプロジェクトではありません。手法と実装の本体は Maarten Grootendorst の BERTopic(論文: [arXiv:2203.05794](https://arxiv.org/abs/2203.05794))です。
36
+
37
+ ## インストール
38
+
39
+ ```bash
40
+ uv add bertopic-ja
41
+ ```
42
+
43
+ ```bash
44
+ pip install bertopic-ja
45
+ ```
46
+
47
+ ## 使い方
48
+
49
+ ```python
50
+ from bertopic_ja import BERTopic
51
+
52
+ topic_model = BERTopic()
53
+ topics, probs = topic_model.fit_transform(docs)
54
+ topic_model.get_topic_info()
55
+ ```
56
+
57
+ 何も指定しないときの埋め込みは、BERTopic の `language="multilingual"`(`paraphrase-multilingual-MiniLM-L12-v2`)です。トピック語は Sudachi(分割モード C)の名詞です。1文字の名詞、代名詞、数詞は出しません。「えー」「まあ」のようなフィラーはトピック語から外し、本文には残します。「あの車」の「あの」は消しません。
58
+
59
+ トピックの粗さは `min_topic_size` です。UMAP と HDBSCAN は自分で組みません。
60
+
61
+ ```python
62
+ topic_model = BERTopic(min_topic_size=8)
63
+ ```
64
+
65
+ ## 出てきた語を調整する
66
+
67
+ トピック語から外すだけなら、埋め込みはやり直しません。
68
+
69
+ ```python
70
+ topic_model.exclude("残価", "月々")
71
+ topic_model.suggest()
72
+ topic_model.explain("残価設定って聞いてることあります?")
73
+ topic_model.preview_exclude(["残価"])
74
+ ```
75
+
76
+ クラスタの数や粗さを変えるときは、保存してある埋め込みで学習し直します。
77
+
78
+ ```python
79
+ topic_model.refit(min_topic_size=8)
80
+ topic_model.refit(nr_topics=15)
81
+ ```
82
+
83
+ 本文からフィラーを消すとクラスタが変わるので、初期値では消しません。消すときだけ `fillers=` を渡します。
84
+
85
+ ```python
86
+ topic_model = BERTopic(fillers=["えー", "あのー"])
87
+ ```
88
+
89
+ 別の埋め込みモデルにするときは、名前を一つ渡します。
90
+
91
+ ```python
92
+ topic_model = BERTopic(embedding_model="cl-nagoya/ruri-v3-310m")
93
+ ```
94
+
95
+ ## 設定ファイル
96
+
97
+ 引数と YAML は同じ項目です。両方あるときは引数が優先されます。
98
+
99
+ ```yaml
100
+ min_topic_size: 10
101
+ nr_topics: auto
102
+ reduce_outliers: true
103
+ embedding_model: null
104
+ exclude:
105
+ - 残価
106
+ protect:
107
+ - 金利
108
+ fillers: []
109
+ ```
110
+
111
+ ```python
112
+ topic_model = BERTopic.from_yaml("config.yaml", min_topic_size=8)
113
+ topic_model.to_yaml("config.yaml")
114
+ ```
115
+
116
+ ## 公式との違い
117
+
118
+ 公式の `BERTopic(language="multilingual")` は日本語の文をベクトルにできます。トピック語の区切りは空白のままなので、日本語では文のかたまりがトピック名になります。このパッケージはそこを Sudachi に置き換え、語の除外とクラスタの再調整をメソッドにしています。
119
+
120
+ 分類器でも、特定の業界向けの分析パイプラインでもありません。ラベルの付いていない文書から話題を探すためのものです。
121
+
122
+ ## 公開
123
+
124
+ ローカルでのビルドは次です。
125
+
126
+ ```bash
127
+ uv build
128
+ ```
129
+
130
+ PyPI へ出すときは、PyPI の Trusted Publishing に GitHub リポジトリを登録してからタグを切ります。このリポジトリのワークフローはテストの実行までです。
@@ -0,0 +1,8 @@
1
+ bertopic_ja/__init__.py,sha256=EIUqUi0chaFs0aV2NXaAQy3u562QdXyXLdHTY_LPIow,472
2
+ bertopic_ja/_config.py,sha256=YXtxKXcf0TCraQfw1ycTun4F8zOVVP463VIUwBm3Zgs,2973
3
+ bertopic_ja/_model.py,sha256=iJ8oUT9dixzDjeROI0EOP0J9xBysGSR_NTB616EVcz4,13101
4
+ bertopic_ja/_tokenizer.py,sha256=b-LUDPpHHf0zxUOE3RmeuFhWYHLNOKuiSQXfTUBKI6A,4754
5
+ bertopic_ja-0.1.0.dist-info/METADATA,sha256=R5NwN3d9FOtQ5Y6ldZAvHidQwzLBQX2jdgBWq7QfAmg,4931
6
+ bertopic_ja-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
7
+ bertopic_ja-0.1.0.dist-info/licenses/LICENSE,sha256=_A5kHKeokPfkdUdNxg6TKajdh3sNlJz59SHcvXPAVxA,1081
8
+ bertopic_ja-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 bertopic-ja contributors
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.