ktmu 0.1.1__tar.gz
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.
- ktmu-0.1.1/LICENSE +184 -0
- ktmu-0.1.1/PKG-INFO +111 -0
- ktmu-0.1.1/README.md +84 -0
- ktmu-0.1.1/pyproject.toml +43 -0
- ktmu-0.1.1/setup.cfg +4 -0
- ktmu-0.1.1/src/ktmu/__init__.py +0 -0
- ktmu-0.1.1/src/ktmu/main.py +519 -0
- ktmu-0.1.1/src/ktmu.egg-info/PKG-INFO +111 -0
- ktmu-0.1.1/src/ktmu.egg-info/SOURCES.txt +10 -0
- ktmu-0.1.1/src/ktmu.egg-info/dependency_links.txt +1 -0
- ktmu-0.1.1/src/ktmu.egg-info/requires.txt +13 -0
- ktmu-0.1.1/src/ktmu.egg-info/top_level.txt +1 -0
ktmu-0.1.1/LICENSE
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
KTMU - Korean Text Mining Utilities
|
|
2
|
+
Copyright (C) 2026 Kilhwan Kim <khkim@smu.ac.kr>
|
|
3
|
+
|
|
4
|
+
This library is free software; you can redistribute it and/or
|
|
5
|
+
modify it under the terms of the GNU Lesser General Public
|
|
6
|
+
License as published by the Free Software Foundation; either
|
|
7
|
+
version 3 of the License, or (at your option) any later version.
|
|
8
|
+
|
|
9
|
+
This library is distributed in the hope that it will be useful,
|
|
10
|
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
11
|
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
|
12
|
+
Lesser General Public License for more details.
|
|
13
|
+
|
|
14
|
+
You should have received a copy of the GNU Lesser General Public
|
|
15
|
+
License along with this library; if not, write to the Free Software
|
|
16
|
+
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
|
17
|
+
|
|
18
|
+
--------------
|
|
19
|
+
|
|
20
|
+
GNU LESSER GENERAL PUBLIC LICENSE
|
|
21
|
+
Version 3, 29 June 2007
|
|
22
|
+
|
|
23
|
+
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
|
24
|
+
Everyone is permitted to copy and distribute verbatim copies
|
|
25
|
+
of this license document, but changing it is not allowed.
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
This version of the GNU Lesser General Public License incorporates
|
|
29
|
+
the terms and conditions of version 3 of the GNU General Public
|
|
30
|
+
License, supplemented by the additional permissions listed below.
|
|
31
|
+
|
|
32
|
+
0. Additional Definitions.
|
|
33
|
+
|
|
34
|
+
As used herein, "this License" refers to version 3 of the GNU Lesser
|
|
35
|
+
General Public License, and the "GNU GPL" refers to version 3 of the GNU
|
|
36
|
+
General Public License.
|
|
37
|
+
|
|
38
|
+
"The Library" refers to a covered work governed by this License,
|
|
39
|
+
other than an Application or a Combined Work as defined below.
|
|
40
|
+
|
|
41
|
+
An "Application" is any work that makes use of an interface provided
|
|
42
|
+
by the Library, but which is not otherwise based on the Library.
|
|
43
|
+
Defining a subclass of a class defined by the Library is deemed a mode
|
|
44
|
+
of using an interface provided by the Library.
|
|
45
|
+
|
|
46
|
+
A "Combined Work" is a work produced by combining or linking an
|
|
47
|
+
Application with the Library. The particular version of the Library
|
|
48
|
+
with which the Combined Work was made is also called the "Linked
|
|
49
|
+
Version".
|
|
50
|
+
|
|
51
|
+
The "Minimal Corresponding Source" for a Combined Work means the
|
|
52
|
+
Corresponding Source for the Combined Work, excluding any source code
|
|
53
|
+
for portions of the Combined Work that, considered in isolation, are
|
|
54
|
+
based on the Application, and not on the Linked Version.
|
|
55
|
+
|
|
56
|
+
The "Corresponding Application Code" for a Combined Work means the
|
|
57
|
+
object code and/or source code for the Application, including any data
|
|
58
|
+
and utility programs needed for reproducing the Combined Work from the
|
|
59
|
+
Application, but excluding the System Libraries of the Combined Work.
|
|
60
|
+
|
|
61
|
+
1. Exception to Section 3 of the GNU GPL.
|
|
62
|
+
|
|
63
|
+
You may convey a covered work under sections 3 and 4 of this License
|
|
64
|
+
without being bound by section 3 of the GNU GPL.
|
|
65
|
+
|
|
66
|
+
2. Conveying Modified Versions.
|
|
67
|
+
|
|
68
|
+
If you modify a copy of the Library, and, in your modifications, a
|
|
69
|
+
facility refers to a function or data to be supplied by an Application
|
|
70
|
+
that uses the facility (other than as an argument passed when the
|
|
71
|
+
facility is invoked), then you may convey a copy of the modified
|
|
72
|
+
version:
|
|
73
|
+
|
|
74
|
+
a) under this License, provided that you make a good faith effort to
|
|
75
|
+
ensure that, in the event an Application does not supply the
|
|
76
|
+
function or data, the facility still operates, and performs
|
|
77
|
+
whatever part of its purpose remains meaningful, or
|
|
78
|
+
|
|
79
|
+
b) under the GNU GPL, with none of the additional permissions of
|
|
80
|
+
this License applicable to that copy.
|
|
81
|
+
|
|
82
|
+
3. Object Code Incorporating Material from Library Header Files.
|
|
83
|
+
|
|
84
|
+
The object code form of an Application may incorporate material from
|
|
85
|
+
a header file that is part of the Library. You may convey such object
|
|
86
|
+
code under terms of your choice, provided that, if the incorporated
|
|
87
|
+
material is not limited to numerical parameters, data structure
|
|
88
|
+
layouts and accessors, or small macros, inline functions and templates
|
|
89
|
+
(ten or fewer lines in length), you do both of the following:
|
|
90
|
+
|
|
91
|
+
a) Give prominent notice with each copy of the object code that the
|
|
92
|
+
Library is used in it and that the Library and its use are
|
|
93
|
+
covered by this License.
|
|
94
|
+
|
|
95
|
+
b) Accompany the object code with a copy of the GNU GPL and this license
|
|
96
|
+
document.
|
|
97
|
+
|
|
98
|
+
4. Combined Works.
|
|
99
|
+
|
|
100
|
+
You may convey a Combined Work under terms of your choice that,
|
|
101
|
+
taken together, effectively do not restrict modification of the
|
|
102
|
+
portions of the Library contained in the Combined Work and reverse
|
|
103
|
+
engineering for debugging such modifications, if you also do each of
|
|
104
|
+
the following:
|
|
105
|
+
|
|
106
|
+
a) Give prominent notice with each copy of the Combined Work that
|
|
107
|
+
the Library is used in it and that the Library and its use are
|
|
108
|
+
covered by this License.
|
|
109
|
+
|
|
110
|
+
b) Accompany the Combined Work with a copy of the GNU GPL and this license
|
|
111
|
+
document.
|
|
112
|
+
|
|
113
|
+
c) For a Combined Work that displays copyright notices during
|
|
114
|
+
execution, include the copyright notice for the Library among
|
|
115
|
+
these notices, as well as a reference directing the user to the
|
|
116
|
+
copies of the GNU GPL and this license document.
|
|
117
|
+
|
|
118
|
+
d) Do one of the following:
|
|
119
|
+
|
|
120
|
+
0) Convey the Minimal Corresponding Source under the terms of this
|
|
121
|
+
License, and the Corresponding Application Code in a form
|
|
122
|
+
suitable for, and under terms that permit, the user to
|
|
123
|
+
recombine or relink the Application with a modified version of
|
|
124
|
+
the Linked Version to produce a modified Combined Work, in the
|
|
125
|
+
manner specified by section 6 of the GNU GPL for conveying
|
|
126
|
+
Corresponding Source.
|
|
127
|
+
|
|
128
|
+
1) Use a suitable shared library mechanism for linking with the
|
|
129
|
+
Library. A suitable mechanism is one that (a) uses at run time
|
|
130
|
+
a copy of the Library already present on the user's computer
|
|
131
|
+
system, and (b) will operate properly with a modified version
|
|
132
|
+
of the Library that is interface-compatible with the Linked
|
|
133
|
+
Version.
|
|
134
|
+
|
|
135
|
+
e) Provide Installation Information, but only if you would otherwise
|
|
136
|
+
be required to provide such information under section 6 of the
|
|
137
|
+
GNU GPL, and only to the extent that such information is
|
|
138
|
+
necessary to install and execute a modified version of the
|
|
139
|
+
Combined Work produced by recombining or relinking the
|
|
140
|
+
Application with a modified version of the Linked Version. (If
|
|
141
|
+
you use option 4d0, the Installation Information must accompany
|
|
142
|
+
the Minimal Corresponding Source and Corresponding Application
|
|
143
|
+
Code. If you use option 4d1, you must provide the Installation
|
|
144
|
+
Information in the manner specified by section 6 of the GNU GPL
|
|
145
|
+
for conveying Corresponding Source.)
|
|
146
|
+
|
|
147
|
+
5. Combined Libraries.
|
|
148
|
+
|
|
149
|
+
You may place library facilities that are a work based on the
|
|
150
|
+
Library side by side in a single library together with other library
|
|
151
|
+
facilities that are not Applications and are not covered by this
|
|
152
|
+
License, and convey such a combined library under terms of your
|
|
153
|
+
choice, if you do both of the following:
|
|
154
|
+
|
|
155
|
+
a) Accompany the combined library with a copy of the same work based
|
|
156
|
+
on the Library, uncombined with any other library facilities,
|
|
157
|
+
conveyed under the terms of this License.
|
|
158
|
+
|
|
159
|
+
b) Give prominent notice with the combined library that part of it
|
|
160
|
+
is a work based on the Library, and explaining where to find the
|
|
161
|
+
accompanying uncombined form of the same work.
|
|
162
|
+
|
|
163
|
+
6. Revised Versions of the GNU Lesser General Public License.
|
|
164
|
+
|
|
165
|
+
The Free Software Foundation may publish revised and/or new versions
|
|
166
|
+
of the GNU Lesser General Public License from time to time. Such new
|
|
167
|
+
versions will be similar in spirit to the present version, but may
|
|
168
|
+
differ in detail to address new problems or concerns.
|
|
169
|
+
|
|
170
|
+
Each version is given a distinguishing version number. If the
|
|
171
|
+
Library as you received it specifies that a certain numbered version
|
|
172
|
+
of the GNU Lesser General Public License "or any later version"
|
|
173
|
+
applies to it, you have the option of following the terms and
|
|
174
|
+
conditions either of that published version or of any later version
|
|
175
|
+
published by the Free Software Foundation. If the Library as you
|
|
176
|
+
received it does not specify a version number of the GNU Lesser
|
|
177
|
+
General Public License, you may choose any version of the GNU Lesser
|
|
178
|
+
General Public License ever published by the Free Software Foundation.
|
|
179
|
+
|
|
180
|
+
If the Library as you received it specifies that a proxy can decide
|
|
181
|
+
whether future versions of the GNU Lesser General Public License shall
|
|
182
|
+
apply, that proxy's public statement of acceptance of any version is
|
|
183
|
+
permanent authorization for you to choose that version for the
|
|
184
|
+
Library.
|
ktmu-0.1.1/PKG-INFO
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ktmu
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: Korean Text Mining utilities for visualization, NLP, and LLM analysis
|
|
5
|
+
Author-email: Kilhwan Kim <khkim@smu.ac.kr>
|
|
6
|
+
Classifier: Programming Language :: Python :: 3
|
|
7
|
+
Classifier: License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)
|
|
8
|
+
Classifier: Operating System :: OS Independent
|
|
9
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
10
|
+
Classifier: Topic :: Text Processing :: Linguistic
|
|
11
|
+
Requires-Python: >=3.9
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
License-File: LICENSE
|
|
14
|
+
Requires-Dist: pandas
|
|
15
|
+
Requires-Dist: numpy
|
|
16
|
+
Requires-Dist: matplotlib
|
|
17
|
+
Requires-Dist: wordcloud
|
|
18
|
+
Requires-Dist: spacy
|
|
19
|
+
Requires-Dist: kiwipiepy
|
|
20
|
+
Requires-Dist: scikit-learn
|
|
21
|
+
Requires-Dist: scipy
|
|
22
|
+
Requires-Dist: google-genai
|
|
23
|
+
Provides-Extra: dev
|
|
24
|
+
Requires-Dist: pytest; extra == "dev"
|
|
25
|
+
Requires-Dist: black; extra == "dev"
|
|
26
|
+
Dynamic: license-file
|
|
27
|
+
|
|
28
|
+
# ktmu: Korean Text Mining Utilities
|
|
29
|
+
|
|
30
|
+
`ktmu`는 텍스트 데이터의 전처리, 시각화, 언어 모델 연동을 통합적으로 지원하기 위한 파이썬 패키지입니다. 특히 한국어(Kiwi)와 영어(spaCy) 형태소 분석을 일관된 인터페이스로 제공하며, 최신 LLM(Gemini)을 활용한 분석 기능을 포함하고 있습니다.
|
|
31
|
+
|
|
32
|
+
## 주요 기능
|
|
33
|
+
|
|
34
|
+
* **다양한 시각화 지원**: 토큰 빈도 막대 그래프, 워드클라우드, 임베딩 차원 축소(PCA/t-SNE), 계층적 군집화 덴드로그램 출력.
|
|
35
|
+
* **통합 형태소 분석 인터페이스**: `SpacyTokenizer`(영어) 및 `KiwiTokenizer`(한국어) 클래스를 통한 손쉬운 토큰화 및 표제어 추출.
|
|
36
|
+
* **Pandas 연동**: 모든 분석 결과(토큰, 형태소 정보 등)를 즉시 DataFrame으로 변환하여 데이터 분석 파이프라인에 활용 가능.
|
|
37
|
+
* **LLM 감성 분석**: Google Gemini API를 활용한 대규모 텍스트 데이터의 배치 감성 분석 기능.
|
|
38
|
+
* **임베딩 분석**: Gensim 모델과 연동하여 단어 간 유사도 비교 및 시각화.
|
|
39
|
+
|
|
40
|
+
## 설치 방법
|
|
41
|
+
|
|
42
|
+
패키지는 다음과 같이 설치합니다.
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
pip install ktmu
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## 사용 예시
|
|
49
|
+
|
|
50
|
+
### 1. 한국어 형태소 분석 (Kiwi)
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
from ktmu import KiwiTokenizer
|
|
54
|
+
|
|
55
|
+
tokenizer = KiwiTokenizer()
|
|
56
|
+
text = "텍스트 마이닝은 정말 재밌는 학문입니다."
|
|
57
|
+
|
|
58
|
+
# 토큰화 및 데이터프레임 변환
|
|
59
|
+
df = tokenizer.get_token_dataframe(text)
|
|
60
|
+
print(df)
|
|
61
|
+
|
|
62
|
+
# 명사만 추출
|
|
63
|
+
nouns = tokenizer.noun_tokenize(text)
|
|
64
|
+
print(nouns)
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
### 2. 빈도 시각화
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
from ktmu import visualize_tokens
|
|
71
|
+
|
|
72
|
+
tokens = ["데이터", "분석", "데이터", "AI", "텍스트", "분석", "데이터"]
|
|
73
|
+
visualize_tokens(tokens, top_n=10)
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
### 3. Gemini를 활용한 감성 분석
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
import pandas as pd
|
|
80
|
+
from google import genai
|
|
81
|
+
from ktmu import analyze_sentiment_with_gemini
|
|
82
|
+
|
|
83
|
+
client = genai.Client(api_key="YOUR_API_KEY")
|
|
84
|
+
reviews = pd.Series(["이 영화 정말 재밌어요!", "시간 아까워요..."], name="review")
|
|
85
|
+
|
|
86
|
+
# 배치 감성 분석 수행
|
|
87
|
+
results = analyze_sentiment_with_gemini(client, reviews, system_message="감성 분석 전문가로서 응답해줘.")
|
|
88
|
+
print(results)
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
### 4. 워드 임베딩 시각화
|
|
92
|
+
|
|
93
|
+
```python
|
|
94
|
+
from ktmu import visualize_embeddings
|
|
95
|
+
|
|
96
|
+
# gensim의 word vector 객체(wv)가 있다고 가정
|
|
97
|
+
words = ["사과", "바나나", "컴퓨터", "키보드"]
|
|
98
|
+
visualize_embeddings(wv, words, method='pca')
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
## 의존성
|
|
102
|
+
|
|
103
|
+
이 패키지는 다음 라이브러리들을 사용합니다:
|
|
104
|
+
* `pandas`, `numpy`, `matplotlib`
|
|
105
|
+
* `spacy`, `kiwipiepy`
|
|
106
|
+
* `scikit-learn`, `scipy`
|
|
107
|
+
* `wordcloud`, `google-genai`
|
|
108
|
+
|
|
109
|
+
## 라이선스
|
|
110
|
+
|
|
111
|
+
이 프로젝트는 **LGPL-3.0** 라이선스 하에 배포됩니다.
|
ktmu-0.1.1/README.md
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
# ktmu: Korean Text Mining Utilities
|
|
2
|
+
|
|
3
|
+
`ktmu`는 텍스트 데이터의 전처리, 시각화, 언어 모델 연동을 통합적으로 지원하기 위한 파이썬 패키지입니다. 특히 한국어(Kiwi)와 영어(spaCy) 형태소 분석을 일관된 인터페이스로 제공하며, 최신 LLM(Gemini)을 활용한 분석 기능을 포함하고 있습니다.
|
|
4
|
+
|
|
5
|
+
## 주요 기능
|
|
6
|
+
|
|
7
|
+
* **다양한 시각화 지원**: 토큰 빈도 막대 그래프, 워드클라우드, 임베딩 차원 축소(PCA/t-SNE), 계층적 군집화 덴드로그램 출력.
|
|
8
|
+
* **통합 형태소 분석 인터페이스**: `SpacyTokenizer`(영어) 및 `KiwiTokenizer`(한국어) 클래스를 통한 손쉬운 토큰화 및 표제어 추출.
|
|
9
|
+
* **Pandas 연동**: 모든 분석 결과(토큰, 형태소 정보 등)를 즉시 DataFrame으로 변환하여 데이터 분석 파이프라인에 활용 가능.
|
|
10
|
+
* **LLM 감성 분석**: Google Gemini API를 활용한 대규모 텍스트 데이터의 배치 감성 분석 기능.
|
|
11
|
+
* **임베딩 분석**: Gensim 모델과 연동하여 단어 간 유사도 비교 및 시각화.
|
|
12
|
+
|
|
13
|
+
## 설치 방법
|
|
14
|
+
|
|
15
|
+
패키지는 다음과 같이 설치합니다.
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
pip install ktmu
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## 사용 예시
|
|
22
|
+
|
|
23
|
+
### 1. 한국어 형태소 분석 (Kiwi)
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
from ktmu import KiwiTokenizer
|
|
27
|
+
|
|
28
|
+
tokenizer = KiwiTokenizer()
|
|
29
|
+
text = "텍스트 마이닝은 정말 재밌는 학문입니다."
|
|
30
|
+
|
|
31
|
+
# 토큰화 및 데이터프레임 변환
|
|
32
|
+
df = tokenizer.get_token_dataframe(text)
|
|
33
|
+
print(df)
|
|
34
|
+
|
|
35
|
+
# 명사만 추출
|
|
36
|
+
nouns = tokenizer.noun_tokenize(text)
|
|
37
|
+
print(nouns)
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
### 2. 빈도 시각화
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
from ktmu import visualize_tokens
|
|
44
|
+
|
|
45
|
+
tokens = ["데이터", "분석", "데이터", "AI", "텍스트", "분석", "데이터"]
|
|
46
|
+
visualize_tokens(tokens, top_n=10)
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
### 3. Gemini를 활용한 감성 분석
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
import pandas as pd
|
|
53
|
+
from google import genai
|
|
54
|
+
from ktmu import analyze_sentiment_with_gemini
|
|
55
|
+
|
|
56
|
+
client = genai.Client(api_key="YOUR_API_KEY")
|
|
57
|
+
reviews = pd.Series(["이 영화 정말 재밌어요!", "시간 아까워요..."], name="review")
|
|
58
|
+
|
|
59
|
+
# 배치 감성 분석 수행
|
|
60
|
+
results = analyze_sentiment_with_gemini(client, reviews, system_message="감성 분석 전문가로서 응답해줘.")
|
|
61
|
+
print(results)
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
### 4. 워드 임베딩 시각화
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
from ktmu import visualize_embeddings
|
|
68
|
+
|
|
69
|
+
# gensim의 word vector 객체(wv)가 있다고 가정
|
|
70
|
+
words = ["사과", "바나나", "컴퓨터", "키보드"]
|
|
71
|
+
visualize_embeddings(wv, words, method='pca')
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## 의존성
|
|
75
|
+
|
|
76
|
+
이 패키지는 다음 라이브러리들을 사용합니다:
|
|
77
|
+
* `pandas`, `numpy`, `matplotlib`
|
|
78
|
+
* `spacy`, `kiwipiepy`
|
|
79
|
+
* `scikit-learn`, `scipy`
|
|
80
|
+
* `wordcloud`, `google-genai`
|
|
81
|
+
|
|
82
|
+
## 라이선스
|
|
83
|
+
|
|
84
|
+
이 프로젝트는 **LGPL-3.0** 라이선스 하에 배포됩니다.
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "ktmu"
|
|
7
|
+
version = "0.1.1"
|
|
8
|
+
description = "Korean Text Mining utilities for visualization, NLP, and LLM analysis"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9" # google-genai 및 최신 라이브러리 호환성을 위해 3.9 이상 권장
|
|
11
|
+
authors = [
|
|
12
|
+
{name = "Kilhwan Kim", email="khkim@smu.ac.kr"}
|
|
13
|
+
]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)",
|
|
17
|
+
"Operating System :: OS Independent",
|
|
18
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
19
|
+
"Topic :: Text Processing :: Linguistic",
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
# 소스 코드 내에서 import하고 있는 필수 라이브러리들입니다.
|
|
23
|
+
dependencies = [
|
|
24
|
+
"pandas",
|
|
25
|
+
"numpy",
|
|
26
|
+
"matplotlib",
|
|
27
|
+
"wordcloud",
|
|
28
|
+
"spacy",
|
|
29
|
+
"kiwipiepy",
|
|
30
|
+
"scikit-learn",
|
|
31
|
+
"scipy",
|
|
32
|
+
"google-genai",
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
[tool.setuptools.packages.find]
|
|
36
|
+
where = ["src"]
|
|
37
|
+
|
|
38
|
+
[project.optional-dependencies]
|
|
39
|
+
# 개발 및 테스트를 위한 선택적 의존성
|
|
40
|
+
dev = [
|
|
41
|
+
"pytest",
|
|
42
|
+
"black",
|
|
43
|
+
]
|
ktmu-0.1.1/setup.cfg
ADDED
|
File without changes
|
|
@@ -0,0 +1,519 @@
|
|
|
1
|
+
# main.py
|
|
2
|
+
# Copyright (C) 2026 Kilhwan Kim
|
|
3
|
+
#
|
|
4
|
+
# This program is free software: you can redistribute it and/or modify
|
|
5
|
+
# it under the terms of the GNU Lesser General Public License as published by
|
|
6
|
+
# the Free Software Foundation, either version 3 of the License, or
|
|
7
|
+
# (at your option) any later version.
|
|
8
|
+
|
|
9
|
+
import pandas as pd
|
|
10
|
+
import numpy as np
|
|
11
|
+
import matplotlib.pyplot as plt
|
|
12
|
+
import matplotlib.font_manager as fm
|
|
13
|
+
from wordcloud import WordCloud
|
|
14
|
+
import spacy
|
|
15
|
+
import spacy.cli
|
|
16
|
+
import unicodedata
|
|
17
|
+
from spacy.util import is_package
|
|
18
|
+
from kiwipiepy import Kiwi
|
|
19
|
+
from kiwipiepy.utils import Stopwords
|
|
20
|
+
from sklearn.decomposition import PCA
|
|
21
|
+
from sklearn.manifold import TSNE
|
|
22
|
+
from scipy.cluster.hierarchy import dendrogram, linkage
|
|
23
|
+
from typing import List, Union, Iterable
|
|
24
|
+
from google import genai
|
|
25
|
+
import json
|
|
26
|
+
|
|
27
|
+
def visualize_tokens(tokens, top_n=20, font_path=None):
|
|
28
|
+
"""토큰 빈도 기반의 막대 그래프와 워드클라우드를 시각화
|
|
29
|
+
|
|
30
|
+
Args:
|
|
31
|
+
tokens (list): 시각화할 텍스트 토큰들의 리스트.
|
|
32
|
+
top_n (int, optional): 막대 그래프에 표시할 상위 단어의 개수. 기본값은 20.
|
|
33
|
+
font_path (str, optional): 워드 클라우드에 사용할 폰트 설정
|
|
34
|
+
|
|
35
|
+
Returns:
|
|
36
|
+
None: 결과 그래프를 화면에 출력
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
# 시스템에서 나눔폰트 경로 자동 탐색
|
|
40
|
+
try:
|
|
41
|
+
font_path = [f.fname for f in fm.fontManager.ttflist if 'Nanum' in f.name][0]
|
|
42
|
+
except IndexError:
|
|
43
|
+
font_path = None # 폰트를 못 찾을 경우를 대비한 예외 처리
|
|
44
|
+
|
|
45
|
+
# 단어별 출현 빈도 계산
|
|
46
|
+
word_counts = pd.Series(tokens).value_counts()
|
|
47
|
+
|
|
48
|
+
# 레이아웃 설정 (막대 그래프와 워드클라우드 비율 1:2)
|
|
49
|
+
fig, axes = plt.subplots(1, 2, figsize=(10, 4), gridspec_kw={"width_ratios": [1, 2]})
|
|
50
|
+
|
|
51
|
+
# 상위 n개 단어 막대 그래프 생성
|
|
52
|
+
word_counts[:top_n].sort_values().plot(kind="barh", ax=axes[0], title=f"Top {top_n} words")
|
|
53
|
+
|
|
54
|
+
# 워드클라우드 생성
|
|
55
|
+
wcloud = WordCloud(background_color="white", max_words=100,
|
|
56
|
+
width=1000, height=600, font_path=font_path)
|
|
57
|
+
wcloud.generate_from_frequencies(word_counts)
|
|
58
|
+
|
|
59
|
+
# 워드클라우드 출력
|
|
60
|
+
axes[1].axis("off")
|
|
61
|
+
axes[1].imshow(wcloud, interpolation="bilinear")
|
|
62
|
+
|
|
63
|
+
plt.show()
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def get_dataframe_from_doc(doc):
|
|
67
|
+
"""spaCy Doc 객체의 토큰별 정보를 추출하여 Pandas DataFrame으로 변환.
|
|
68
|
+
|
|
69
|
+
이 함수는 각 토큰의 원문, 소문자, 표제어, 품사 및 속성(문자 여부, 불용어 여부 등)을
|
|
70
|
+
딕셔너리 리스트로 구성한 후 데이터프레임으로 반환.
|
|
71
|
+
|
|
72
|
+
Args:
|
|
73
|
+
doc (spacy.tokens.doc.Doc): spaCy의 nlp() 파이프라인을 거친 Doc 객체.
|
|
74
|
+
|
|
75
|
+
Returns:
|
|
76
|
+
pd.DataFrame: 토큰별 언어학적 속성을 컬럼으로 가지는 데이터프레임.
|
|
77
|
+
"""
|
|
78
|
+
# 리스트 컴프리헨션을 사용하여 각 토큰의 속성을 딕셔너리 형태로 추출
|
|
79
|
+
token_data = [
|
|
80
|
+
{
|
|
81
|
+
"token": token.text, # 토큰
|
|
82
|
+
"lower": token.lower_, # 소문자화된 텍스트
|
|
83
|
+
"lemma": token.lemma_, # 단어의 기본형 (표제어)
|
|
84
|
+
"pos": token.pos_, # 단순화된 품사 태그 (예: NOUN, VERB)
|
|
85
|
+
"is_alpha": token.is_alpha, # 알파벳 문자로만 구성되었는지 여부
|
|
86
|
+
"is_digit": token.is_digit, # 숫자 [0-9]로만 구성되었는지 여부
|
|
87
|
+
"is_stop": token.is_stop, # 해당 언어의 불용어 목록에 포함되는지 여부
|
|
88
|
+
"is_space": token.is_space, # 공백 문자인지 여부
|
|
89
|
+
"is_punct": token.is_punct, # 문장 부호(구두점)인지 여부
|
|
90
|
+
}
|
|
91
|
+
for token in doc
|
|
92
|
+
]
|
|
93
|
+
|
|
94
|
+
return pd.DataFrame(token_data)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def strip_accents(text):
|
|
98
|
+
"""엑센트가 포함된 문자에서 엑센터를 제거하는 함수
|
|
99
|
+
"""
|
|
100
|
+
# NFD로 분해 후 비간격 부호(Mn)를 제거하여 기저 문자만 남김
|
|
101
|
+
return "".join(c for c in unicodedata.normalize('NFD', text)
|
|
102
|
+
if unicodedata.category(c) != 'Mn')
|
|
103
|
+
|
|
104
|
+
class SpacyTokenizer:
|
|
105
|
+
"""spaCy를 활용하여 텍스트 토큰화 및 표제어 추출을 수행하는 클래스.
|
|
106
|
+
|
|
107
|
+
이 클래스는 기본적으로 영어 모델('en_core_web_sm')을 사용하도록 설정되어 있으며,
|
|
108
|
+
모델 설치 여부를 자동으로 확인하여 필요 시 다운로드를 수행합니다.
|
|
109
|
+
|
|
110
|
+
Attributes:
|
|
111
|
+
nlp (spacy.lang.en.English): 로드된 spaCy 언어 모델 객체.
|
|
112
|
+
"""
|
|
113
|
+
|
|
114
|
+
def __init__(self, model_name: str = "en_core_web_sm"):
|
|
115
|
+
"""SpacyTokenizer를 초기화하고 지정된 언어 모델을 로드함.
|
|
116
|
+
|
|
117
|
+
Args:
|
|
118
|
+
model_name (str): 사용할 spaCy 모델의 이름. 기본값은 "en_core_web_sm".
|
|
119
|
+
|
|
120
|
+
Raises:
|
|
121
|
+
OSError: 모델 다운로드에 실패하거나 로드할 수 없을 때 발생.
|
|
122
|
+
"""
|
|
123
|
+
try:
|
|
124
|
+
if not is_package(model_name):
|
|
125
|
+
print(f"모델 '{model_name}'이 설치되어 있지 않습니다. 다운로드를 시작합니다...")
|
|
126
|
+
spacy.cli.download(model_name)
|
|
127
|
+
|
|
128
|
+
# 속도 최적화를 위해 구문 분석기(Parser)와 개체명 인식기(NER) 비활성화
|
|
129
|
+
self.nlp = spacy.load(model_name, disable=["ner", "parser"])
|
|
130
|
+
except Exception as e:
|
|
131
|
+
raise OSError(f"모델 로드 실패: {e}\n'python -m spacy download {model_name}' 명령어를 확인하세요.")
|
|
132
|
+
|
|
133
|
+
def _process_pipe(self, texts: Union[str, Iterable[str]], attr_name: str, filter_stop: bool, batch_size: int = 1000, n_process: int = -1) -> Union[List[str], List[List[str]]]:
|
|
134
|
+
""" nlp.pipe을 사용하여 입력을 배치 처리하는 내부 메서드. """
|
|
135
|
+
|
|
136
|
+
# 1. 입력이 단일 문자열인 경우 리스트로 래핑
|
|
137
|
+
is_single_input = isinstance(texts, str)
|
|
138
|
+
if is_single_input:
|
|
139
|
+
texts = [texts]
|
|
140
|
+
|
|
141
|
+
# 2. Pandas Series 대응 및 결측치(NaN) 처리
|
|
142
|
+
if isinstance(texts, pd.Series):
|
|
143
|
+
texts = texts.fillna("").astype(str).tolist()
|
|
144
|
+
|
|
145
|
+
# 3. nlp.pipe 실행 (GPU 서버 환경이라면 n_process를 코어 수에 맞춰 조절 가능)
|
|
146
|
+
#
|
|
147
|
+
docs = self.nlp.pipe(texts, batch_size=batch_size, n_process=n_process)
|
|
148
|
+
|
|
149
|
+
results = []
|
|
150
|
+
for doc in docs:
|
|
151
|
+
tokens = [
|
|
152
|
+
getattr(token, attr_name) for token in doc
|
|
153
|
+
if not token.is_space and not token.is_punct
|
|
154
|
+
and (not (filter_stop and token.is_stop))
|
|
155
|
+
]
|
|
156
|
+
results.append(tokens)
|
|
157
|
+
|
|
158
|
+
# 4. 입력 형식이 단일 문자열이었다면 단일 리스트 반환, 아니면 중첩 리스트 반환
|
|
159
|
+
return results[0] if is_single_input else results
|
|
160
|
+
|
|
161
|
+
def tokenize(self, texts: Union[str, Iterable[str]], filter_stop: bool = True, **kwargs) -> Union[List[str], List[List[str]]]:
|
|
162
|
+
""" 텍스트(들)를 소문자 토큰 리스트(들)로 반환. """
|
|
163
|
+
return self._process_pipe(texts, "lower_", filter_stop, **kwargs)
|
|
164
|
+
|
|
165
|
+
def lemmatize(self, texts: Union[str, Iterable[str]], filter_stop: bool = True, **kwargs) -> Union[List[str], List[List[str]]]:
|
|
166
|
+
""" 텍스트(들)에서 표제어(기본형) 리스트(들)를 추출. """
|
|
167
|
+
return self._process_pipe(texts, "lemma_", filter_stop, **kwargs)
|
|
168
|
+
|
|
169
|
+
def get_token_dataframe(self, text):
|
|
170
|
+
"""텍스트를 토큰화한 결과를 데이터프레임으로 반환
|
|
171
|
+
|
|
172
|
+
Args:
|
|
173
|
+
text (str): 입력 텍스트.
|
|
174
|
+
|
|
175
|
+
Returns:
|
|
176
|
+
pd.DataFrame: 토큰별 언어학적 속성을 컬럼으로 가지는 데이터프레임.
|
|
177
|
+
"""
|
|
178
|
+
doc = self.nlp(text)
|
|
179
|
+
return get_dataframe_from_doc(doc)
|
|
180
|
+
|
|
181
|
+
def add_stop_words(self, words):
|
|
182
|
+
"""불용어 사전에 단어를 추가합니다.
|
|
183
|
+
|
|
184
|
+
Args:
|
|
185
|
+
words (str list): 제외할 단어의 리스트
|
|
186
|
+
"""
|
|
187
|
+
for word in words:
|
|
188
|
+
self.nlp.vocab[word].is_stop = True
|
|
189
|
+
|
|
190
|
+
print(f"불용어 추가 완료: {words}")
|
|
191
|
+
|
|
192
|
+
def get_dataframe_from_kiwi_tokens(tokens):
|
|
193
|
+
"""Kiwi 토큰 리스트를 Pandas DataFrame으로 변환합니다.
|
|
194
|
+
|
|
195
|
+
Args:
|
|
196
|
+
tokens (list[kiwipiepy.Token]): Kiwi 형태소 분석기에서 반환된 토큰 객체 리스트.
|
|
197
|
+
|
|
198
|
+
Returns:
|
|
199
|
+
pd.DataFrame: 'token'(형태), 'pos'(품사), 'lemma'(표제어) 컬럼을 포함하는 데이터프레임.
|
|
200
|
+
"""
|
|
201
|
+
token_data = [
|
|
202
|
+
{
|
|
203
|
+
"token": token.form,
|
|
204
|
+
"pos": token.tag,
|
|
205
|
+
"lemma": token.lemma,
|
|
206
|
+
}
|
|
207
|
+
for token in tokens
|
|
208
|
+
]
|
|
209
|
+
return pd.DataFrame(token_data)
|
|
210
|
+
|
|
211
|
+
def filter_tokens_by_tags(tokens, selected_tags=None):
|
|
212
|
+
"""특정 품사 태그를 기준으로 토큰의 표제어 리스트를 반환합니다.
|
|
213
|
+
|
|
214
|
+
Args:
|
|
215
|
+
tokens (list[kiwipiepy.Token]): Kiwi 형태소 분석 결과 토큰 리스트.
|
|
216
|
+
selected_tags (list[str], optional): 필터링할 품사 태그 리스트.
|
|
217
|
+
None일 경우 모든 토큰의 표제어를 반환합니다.
|
|
218
|
+
|
|
219
|
+
Returns:
|
|
220
|
+
list[str]: 필터링된 토큰들의 표제어(lemma) 리스트.
|
|
221
|
+
"""
|
|
222
|
+
if selected_tags is None:
|
|
223
|
+
return [token.lemma for token in tokens]
|
|
224
|
+
|
|
225
|
+
tag_set = set(selected_tags)
|
|
226
|
+
return [token.lemma for token in tokens if token.tag in tag_set]
|
|
227
|
+
|
|
228
|
+
class KiwiTokenizer:
|
|
229
|
+
"""Kiwi를 활용하여 텍스트를 토큰화하고 필터링하는 기능을 제공하는 클래스.
|
|
230
|
+
|
|
231
|
+
Attributes:
|
|
232
|
+
NOUN_TAGS (list[str]): 일반 명사 및 고유 명사 태그.
|
|
233
|
+
NOUN_VERB_ADJ_ADV_TAGS (list[str]): 주요 품사(명사, 동사, 형용사, 부사) 태그.
|
|
234
|
+
kiwi (kiwipiepy.Kiwi): Kiwi 형태소 분석기 인스턴스.
|
|
235
|
+
stopwords (kiwipiepy.Stopwords, optional): 불용어 관리 객체.
|
|
236
|
+
"""
|
|
237
|
+
|
|
238
|
+
NOUN_TAGS = ["NNG", "NNP"]
|
|
239
|
+
NOUN_VERB_ADJ_ADV_TAGS = ["NNG", "NNP", "VV", "VV-R", "VV-I", "VA", "VA-R", "VA-I", "MAG"]
|
|
240
|
+
|
|
241
|
+
def __init__(self):
|
|
242
|
+
"""KiwiTokenizer 인스턴스를 초기화합니다.
|
|
243
|
+
|
|
244
|
+
Args:
|
|
245
|
+
stop_words (bool): True일 경우 기본 불용어 사전을 로드합니다. 기본값은 True.
|
|
246
|
+
"""
|
|
247
|
+
self.kiwi = Kiwi()
|
|
248
|
+
self.stopwords = Stopwords()
|
|
249
|
+
|
|
250
|
+
def get_tokens(self, text, filter_stop=True):
|
|
251
|
+
"""텍스트를 형태소 분석하여 토큰 리스트를 반환합니다.
|
|
252
|
+
|
|
253
|
+
Args:
|
|
254
|
+
text (str): 분석할 입력 문자열.
|
|
255
|
+
filter_stop (boolean): 불용어를 제거할지 여부
|
|
256
|
+
|
|
257
|
+
Returns:
|
|
258
|
+
list[kiwipiepy.Token]: 분석된 토큰 객체 리스트.
|
|
259
|
+
"""
|
|
260
|
+
if filter_stop:
|
|
261
|
+
return self.kiwi.tokenize(text, stopwords=self.stopwords)
|
|
262
|
+
else:
|
|
263
|
+
return self.kiwi.tokenize(text)
|
|
264
|
+
|
|
265
|
+
def get_token_dataframe(self, text):
|
|
266
|
+
"""텍스트 분석 결과를 데이터프레임으로 반환합니다.
|
|
267
|
+
|
|
268
|
+
Args:
|
|
269
|
+
text (str): 분석할 입력 문자열.
|
|
270
|
+
|
|
271
|
+
Returns:
|
|
272
|
+
pd.DataFrame: 형태소 정보가 담긴 데이터프레임.
|
|
273
|
+
"""
|
|
274
|
+
tokens = self.get_tokens(text)
|
|
275
|
+
return get_dataframe_from_kiwi_tokens(tokens)
|
|
276
|
+
|
|
277
|
+
def tokenize(self, text, filter_stop=True, tags=NOUN_VERB_ADJ_ADV_TAGS):
|
|
278
|
+
"""설정된 품사 필터에 따라 텍스트를 토큰화하고 표제어 리스트를 반환합니다.
|
|
279
|
+
|
|
280
|
+
Args:
|
|
281
|
+
text (str): 분석할 입력 문자열.
|
|
282
|
+
|
|
283
|
+
Returns:
|
|
284
|
+
list[str]: 필터링된 표제어 리스트.
|
|
285
|
+
"""
|
|
286
|
+
tokens = self.get_tokens(text, filter_stop)
|
|
287
|
+
if isinstance(tokens, map):
|
|
288
|
+
return [filter_tokens_by_tags(tokens_item, tags) for tokens_item in tokens]
|
|
289
|
+
return filter_tokens_by_tags(tokens, tags)
|
|
290
|
+
|
|
291
|
+
def noun_tokenize(self, text, filter_stop=True):
|
|
292
|
+
"""텍스트를 토큰화하여 명사의 표제어 리스트만 반환합니다.
|
|
293
|
+
|
|
294
|
+
Args:
|
|
295
|
+
text (str): 분석할 입력 문자열.
|
|
296
|
+
|
|
297
|
+
Returns:
|
|
298
|
+
list[str]: 필터링된 표제어 리스트.
|
|
299
|
+
"""
|
|
300
|
+
return self.tokenize(text, filter_stop, self.NOUN_TAGS)
|
|
301
|
+
|
|
302
|
+
def add_stop_word(self, word, tag=None):
|
|
303
|
+
"""불용어 사전에 단어를 추가합니다.
|
|
304
|
+
|
|
305
|
+
Args:
|
|
306
|
+
word (str): 제외할 단어 (예: '정말', '것').
|
|
307
|
+
tag (str, optional): 특정 품사의 단어만 제외하고 싶을 때 지정 (예: 'MAG').
|
|
308
|
+
None이면 해당 단어의 모든 품사를 제외합니다.
|
|
309
|
+
"""
|
|
310
|
+
if tag:
|
|
311
|
+
self.stopwords.add((word, tag))
|
|
312
|
+
else:
|
|
313
|
+
self.stopwords.add(word)
|
|
314
|
+
print(f"불용어 추가 완료: {word}{f'({tag})' if tag else ''}")
|
|
315
|
+
|
|
316
|
+
def add_stop_words(self, stopwords_list):
|
|
317
|
+
"""여러 개의 불용어를 리스트로 받아 한꺼번에 추가합니다."""
|
|
318
|
+
for word in stopwords_list:
|
|
319
|
+
self.add_stop_word(word)
|
|
320
|
+
|
|
321
|
+
def compare_words(wv, words1, words2):
|
|
322
|
+
# 단어 존재 여부 사전 필터링 (OOV 에러 방지)
|
|
323
|
+
valid_words1 = [w for w in words1 if w in wv]
|
|
324
|
+
valid_words2 = [b for b in words2 if b in wv]
|
|
325
|
+
|
|
326
|
+
if not valid_words1 or not valid_words2:
|
|
327
|
+
print("경고: 모델에 존재하지 않는 단어가 포함되어 있습니다.")
|
|
328
|
+
return None
|
|
329
|
+
|
|
330
|
+
# 데이터 프레임 생성
|
|
331
|
+
data = []
|
|
332
|
+
for word1 in valid_words1:
|
|
333
|
+
row = {word2: wv.similarity(word1, word2) for word2 in valid_words2}
|
|
334
|
+
data.append(row)
|
|
335
|
+
|
|
336
|
+
df = pd.DataFrame(data, index=valid_words1)
|
|
337
|
+
|
|
338
|
+
# 시각화
|
|
339
|
+
df.plot(kind="bar")
|
|
340
|
+
plt.xticks(rotation=0)
|
|
341
|
+
plt.show()
|
|
342
|
+
|
|
343
|
+
return df # 데이터 분석 결과를 리턴하여 재사용 가능하게 함
|
|
344
|
+
|
|
345
|
+
def compare_brands(wv, brands, attrs):
|
|
346
|
+
return compare_words(wv, brands, attrs)
|
|
347
|
+
|
|
348
|
+
def visualize_embeddings(wv, words, method='pca'):
|
|
349
|
+
# 1. 시각화할 단어들의 벡터 추출
|
|
350
|
+
vectors = np.array([wv[w] for w in words if w in wv])
|
|
351
|
+
labels = [w for w in words if w in wv]
|
|
352
|
+
|
|
353
|
+
# 2. 차원 축소 모델 선택
|
|
354
|
+
if method.lower() == 'pca':
|
|
355
|
+
reducer = PCA(n_components=2)
|
|
356
|
+
else:
|
|
357
|
+
reducer = TSNE(n_components=2, perplexity=min(5, len(labels)-1), random_state=42)
|
|
358
|
+
|
|
359
|
+
result = reducer.fit_transform(vectors)
|
|
360
|
+
|
|
361
|
+
# 3. 시각화
|
|
362
|
+
plt.figure(figsize=(10, 8))
|
|
363
|
+
plt.scatter(result[:, 0], result[:, 1], edgecolors='k', c='skyblue')
|
|
364
|
+
|
|
365
|
+
for i, label in enumerate(labels):
|
|
366
|
+
plt.annotate(label, xy=(result[i, 0], result[i, 1]), xytext=(5, 2),
|
|
367
|
+
textcoords='offset points', ha='right', va='bottom')
|
|
368
|
+
|
|
369
|
+
plt.title(f"Word Embedding Visualization ({method.upper()})")
|
|
370
|
+
plt.grid(True)
|
|
371
|
+
plt.show()
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def plot_word_dendrogram(wv, words, method='average', metric='cosine'):
|
|
375
|
+
"""
|
|
376
|
+
Gensim 단어 임베딩을 사용하여 병합 군집화를 수행하고 덴드로그램을 시각화합니다.
|
|
377
|
+
|
|
378
|
+
Args:
|
|
379
|
+
wv: 학습된 Gensim Word2Vec/FastText의 wv 객체
|
|
380
|
+
words: 군집화할 단어 리스트
|
|
381
|
+
method: 군집 결합 방식 ('ward', 'complete', 'average' 등)
|
|
382
|
+
metric: 거리 계산 척도 ('euclidean', 'cosine' 등)
|
|
383
|
+
"""
|
|
384
|
+
|
|
385
|
+
# 1. Filter valid words (OOV Handling)
|
|
386
|
+
valid_words = [w for w in words if w in wv]
|
|
387
|
+
if len(valid_words) < 2:
|
|
388
|
+
print("경고: 군집화를 위한 유효 단어가 부족합니다. (최소 2개 필요)")
|
|
389
|
+
return
|
|
390
|
+
|
|
391
|
+
# 2. Extract vectors
|
|
392
|
+
word_vectors = np.array([wv[w] for w in valid_words])
|
|
393
|
+
|
|
394
|
+
# 3. Perform Hierarchical Clustering
|
|
395
|
+
linked = linkage(word_vectors, method=method, metric=metric)
|
|
396
|
+
|
|
397
|
+
# 4. Visualization (Dendrogram)
|
|
398
|
+
plt.figure(figsize=(12, 7))
|
|
399
|
+
dendrogram(linked,
|
|
400
|
+
orientation='top',
|
|
401
|
+
labels=valid_words,
|
|
402
|
+
distance_sort='descending',
|
|
403
|
+
show_leaf_counts=True,
|
|
404
|
+
leaf_font_size=12)
|
|
405
|
+
|
|
406
|
+
# Titles and Labels
|
|
407
|
+
plt.title(f"Hierarchical Clustering of Word Embeddings (Method: {method})", fontsize=15)
|
|
408
|
+
plt.xlabel("Words")
|
|
409
|
+
plt.ylabel("Distance (Similarity Threshold)")
|
|
410
|
+
|
|
411
|
+
# Cut-off line for visual reference
|
|
412
|
+
#plt.axhline(y=linked[-3, 2], color='r', linestyle='--')
|
|
413
|
+
|
|
414
|
+
plt.show()
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def print_wv_similar_words(wv, words, topn=5):
|
|
418
|
+
for word in words:
|
|
419
|
+
similar_words = [similar_word for similar_word, _
|
|
420
|
+
in wv.most_similar(word, topn=topn)]
|
|
421
|
+
print(f"{word}: {', '.join(similar_words)}")
|
|
422
|
+
|
|
423
|
+
# 감성분석을 위한 디폴트 시스템 메시지
|
|
424
|
+
DEFALT_SYSTEM_MESSAGE="""
|
|
425
|
+
너는 숙련된 데이터 분석가야. 입력된 영화 리뷰를 분석하여 감성을 분류하는 역할을 수행한다.
|
|
426
|
+
|
|
427
|
+
[Constrains]
|
|
428
|
+
1. 분류 기준: 긍정적이면 'pos', 부정적이면 'neg'로 분류한다.
|
|
429
|
+
2. 출력 형식: 반드시 'id'와 'sent' 요소를 가진 객체들의 리스트(JSON Array) 형식으로만 응답한다.
|
|
430
|
+
3. 무결성: 입력된 모든 id를 빠짐없이 포함하며, 부연 설명이나 인사말은 생략한다.
|
|
431
|
+
"""
|
|
432
|
+
|
|
433
|
+
def _analyze_sentiment_with_gemini(client, data, system_message=DEFALT_SYSTEM_MESSAGE):
|
|
434
|
+
"""하나의 미니배치에 대하여 Gemini로 감성분석을 수행하는 함수
|
|
435
|
+
|
|
436
|
+
Args:
|
|
437
|
+
client: google.genai.Client의 Gemini API의 클라이언트 객체
|
|
438
|
+
data: pandas.Series 형식의 감성분석할 텍스트 데이터
|
|
439
|
+
system_message: LLM에 감성분석을 지시하는 시스템 메시지
|
|
440
|
+
|
|
441
|
+
Returns: pd.Series 형식의 감성분석 결과
|
|
442
|
+
"""
|
|
443
|
+
|
|
444
|
+
# 사용자 메시지를 위한 리뷰 데이터 변환
|
|
445
|
+
input_data = [{"id": id, "text": text} for id, text in data.items()]
|
|
446
|
+
|
|
447
|
+
# 사용자 메시지
|
|
448
|
+
user_message = f"""
|
|
449
|
+
아래 JSON 형식의 데이터를 감성분석해서 JSON 형태로 반환한다.
|
|
450
|
+
JSON 데이터에서 id는 식별자이고, text는 감성분석을 수행해야 할 텍스트이다.
|
|
451
|
+
|
|
452
|
+
데이터:
|
|
453
|
+
|
|
454
|
+
{json.dumps(input_data, ensure_ascii=False)}
|
|
455
|
+
"""
|
|
456
|
+
|
|
457
|
+
# LLM 호출
|
|
458
|
+
response = client.models.generate_content(
|
|
459
|
+
model="gemini-2.5-flash",
|
|
460
|
+
contents=user_message, # 사용자 메시지
|
|
461
|
+
config=genai.types.GenerateContentConfig(
|
|
462
|
+
system_instruction=system_message, # 시스템 메시지
|
|
463
|
+
response_mime_type="application/json" # 반환 형식 지정
|
|
464
|
+
)
|
|
465
|
+
)
|
|
466
|
+
|
|
467
|
+
# LLM 결과를 시리즈 형태로 변환
|
|
468
|
+
result_df = pd.DataFrame(json.loads(response.text)).set_index("id")
|
|
469
|
+
sent_result = result_df["sent"]
|
|
470
|
+
|
|
471
|
+
# 원본 인덱스가 결과 인덱스에 모두 있는지 파악
|
|
472
|
+
check_all_exists = data.index.isin(sent_result.index)
|
|
473
|
+
if not check_all_exists.all():
|
|
474
|
+
missing_indices = data.index[~check_all_exists].tolist()
|
|
475
|
+
raise ValueError(f"오류: 다음 인덱스가 분석에제 누락되었습니다: {missing_indices}")
|
|
476
|
+
|
|
477
|
+
# 리뷰의 인덱스 순서에 맞추어 결과 반환
|
|
478
|
+
return sent_result.reindex(data.index)
|
|
479
|
+
|
|
480
|
+
def analyze_sentiment_with_gemini(client, data, system_message,
|
|
481
|
+
batch_size=10, n_batches=5):
|
|
482
|
+
"""Gemini로 영화평을 미니배치로 감성분석을 수행하는 함수
|
|
483
|
+
_analyze_sentiment_with_gemini를 미니배치로 반복적으로 호출한다.
|
|
484
|
+
|
|
485
|
+
Args:
|
|
486
|
+
client: google.genai.Client의 Gemini API의 클라이언트 객체
|
|
487
|
+
data: pandas.Series 형식의 감성분석할 데이터
|
|
488
|
+
system_message: LLM에 감성분석을 지시하는 시스템 메시지
|
|
489
|
+
batch_size: 미니배치의 크기
|
|
490
|
+
n_batches: 처리할 배치의 수
|
|
491
|
+
|
|
492
|
+
Returns: pd.Series 형식의 감성분석 결과
|
|
493
|
+
"""
|
|
494
|
+
result = []
|
|
495
|
+
for i in range(n_batches):
|
|
496
|
+
start = i * batch_size
|
|
497
|
+
end = (i+1) * batch_size
|
|
498
|
+
result.append(_analyze_sentiment_with_gemini(client, data[start:end], system_message))
|
|
499
|
+
if end >= len(data):
|
|
500
|
+
break
|
|
501
|
+
return pd.concat(result)
|
|
502
|
+
|
|
503
|
+
def generate_few_shot_prompt(X_train, y_train, n_shots=10):
|
|
504
|
+
"""
|
|
505
|
+
훈련 데이터셋에서 n개의 사례를 뽑아 Few-shot 지시문을 생성합니다.
|
|
506
|
+
"""
|
|
507
|
+
few_shot_text = ""
|
|
508
|
+
|
|
509
|
+
for i in range(n_shots):
|
|
510
|
+
# 특수문자 및 한국어 처리를 위해 json.dumps 활용
|
|
511
|
+
# 문자열 내부에 따옴표나 줄바꿈이 있어도 안전하게 변환
|
|
512
|
+
id = X_train.index[i]
|
|
513
|
+
input_json = json.dumps({"id": int(id), "text": X_train[id]}, ensure_ascii=False)
|
|
514
|
+
output_json = json.dumps({"id": int(id), "sent": y_train[id]}, ensure_ascii=False)
|
|
515
|
+
|
|
516
|
+
few_shot_text += f"[Input]\n{input_json}\n"
|
|
517
|
+
few_shot_text += f"[Output]\n{output_json}\n\n"
|
|
518
|
+
|
|
519
|
+
return few_shot_text
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ktmu
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: Korean Text Mining utilities for visualization, NLP, and LLM analysis
|
|
5
|
+
Author-email: Kilhwan Kim <khkim@smu.ac.kr>
|
|
6
|
+
Classifier: Programming Language :: Python :: 3
|
|
7
|
+
Classifier: License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)
|
|
8
|
+
Classifier: Operating System :: OS Independent
|
|
9
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
10
|
+
Classifier: Topic :: Text Processing :: Linguistic
|
|
11
|
+
Requires-Python: >=3.9
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
License-File: LICENSE
|
|
14
|
+
Requires-Dist: pandas
|
|
15
|
+
Requires-Dist: numpy
|
|
16
|
+
Requires-Dist: matplotlib
|
|
17
|
+
Requires-Dist: wordcloud
|
|
18
|
+
Requires-Dist: spacy
|
|
19
|
+
Requires-Dist: kiwipiepy
|
|
20
|
+
Requires-Dist: scikit-learn
|
|
21
|
+
Requires-Dist: scipy
|
|
22
|
+
Requires-Dist: google-genai
|
|
23
|
+
Provides-Extra: dev
|
|
24
|
+
Requires-Dist: pytest; extra == "dev"
|
|
25
|
+
Requires-Dist: black; extra == "dev"
|
|
26
|
+
Dynamic: license-file
|
|
27
|
+
|
|
28
|
+
# ktmu: Korean Text Mining Utilities
|
|
29
|
+
|
|
30
|
+
`ktmu`는 텍스트 데이터의 전처리, 시각화, 언어 모델 연동을 통합적으로 지원하기 위한 파이썬 패키지입니다. 특히 한국어(Kiwi)와 영어(spaCy) 형태소 분석을 일관된 인터페이스로 제공하며, 최신 LLM(Gemini)을 활용한 분석 기능을 포함하고 있습니다.
|
|
31
|
+
|
|
32
|
+
## 주요 기능
|
|
33
|
+
|
|
34
|
+
* **다양한 시각화 지원**: 토큰 빈도 막대 그래프, 워드클라우드, 임베딩 차원 축소(PCA/t-SNE), 계층적 군집화 덴드로그램 출력.
|
|
35
|
+
* **통합 형태소 분석 인터페이스**: `SpacyTokenizer`(영어) 및 `KiwiTokenizer`(한국어) 클래스를 통한 손쉬운 토큰화 및 표제어 추출.
|
|
36
|
+
* **Pandas 연동**: 모든 분석 결과(토큰, 형태소 정보 등)를 즉시 DataFrame으로 변환하여 데이터 분석 파이프라인에 활용 가능.
|
|
37
|
+
* **LLM 감성 분석**: Google Gemini API를 활용한 대규모 텍스트 데이터의 배치 감성 분석 기능.
|
|
38
|
+
* **임베딩 분석**: Gensim 모델과 연동하여 단어 간 유사도 비교 및 시각화.
|
|
39
|
+
|
|
40
|
+
## 설치 방법
|
|
41
|
+
|
|
42
|
+
패키지는 다음과 같이 설치합니다.
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
pip install ktmu
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## 사용 예시
|
|
49
|
+
|
|
50
|
+
### 1. 한국어 형태소 분석 (Kiwi)
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
from ktmu import KiwiTokenizer
|
|
54
|
+
|
|
55
|
+
tokenizer = KiwiTokenizer()
|
|
56
|
+
text = "텍스트 마이닝은 정말 재밌는 학문입니다."
|
|
57
|
+
|
|
58
|
+
# 토큰화 및 데이터프레임 변환
|
|
59
|
+
df = tokenizer.get_token_dataframe(text)
|
|
60
|
+
print(df)
|
|
61
|
+
|
|
62
|
+
# 명사만 추출
|
|
63
|
+
nouns = tokenizer.noun_tokenize(text)
|
|
64
|
+
print(nouns)
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
### 2. 빈도 시각화
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
from ktmu import visualize_tokens
|
|
71
|
+
|
|
72
|
+
tokens = ["데이터", "분석", "데이터", "AI", "텍스트", "분석", "데이터"]
|
|
73
|
+
visualize_tokens(tokens, top_n=10)
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
### 3. Gemini를 활용한 감성 분석
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
import pandas as pd
|
|
80
|
+
from google import genai
|
|
81
|
+
from ktmu import analyze_sentiment_with_gemini
|
|
82
|
+
|
|
83
|
+
client = genai.Client(api_key="YOUR_API_KEY")
|
|
84
|
+
reviews = pd.Series(["이 영화 정말 재밌어요!", "시간 아까워요..."], name="review")
|
|
85
|
+
|
|
86
|
+
# 배치 감성 분석 수행
|
|
87
|
+
results = analyze_sentiment_with_gemini(client, reviews, system_message="감성 분석 전문가로서 응답해줘.")
|
|
88
|
+
print(results)
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
### 4. 워드 임베딩 시각화
|
|
92
|
+
|
|
93
|
+
```python
|
|
94
|
+
from ktmu import visualize_embeddings
|
|
95
|
+
|
|
96
|
+
# gensim의 word vector 객체(wv)가 있다고 가정
|
|
97
|
+
words = ["사과", "바나나", "컴퓨터", "키보드"]
|
|
98
|
+
visualize_embeddings(wv, words, method='pca')
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
## 의존성
|
|
102
|
+
|
|
103
|
+
이 패키지는 다음 라이브러리들을 사용합니다:
|
|
104
|
+
* `pandas`, `numpy`, `matplotlib`
|
|
105
|
+
* `spacy`, `kiwipiepy`
|
|
106
|
+
* `scikit-learn`, `scipy`
|
|
107
|
+
* `wordcloud`, `google-genai`
|
|
108
|
+
|
|
109
|
+
## 라이선스
|
|
110
|
+
|
|
111
|
+
이 프로젝트는 **LGPL-3.0** 라이선스 하에 배포됩니다.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
ktmu
|