Spaces:
Running
on
Zero
Running
on
Zero
Update app.py
Browse files
app.py
CHANGED
@@ -3,95 +3,187 @@ import gradio as gr
|
|
3 |
import spaces
|
4 |
import wbgtopic
|
5 |
import plotly.graph_objects as go
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
6 |
from topic_translator import translate_topics
|
|
|
|
|
7 |
|
8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
|
10 |
clf = wbgtopic.WBGDocTopic()
|
11 |
|
12 |
-
def
|
13 |
-
#
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
|
18 |
-
|
19 |
-
|
|
|
20 |
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
25 |
name='관련도',
|
26 |
marker_color='rgb(55, 83, 109)'
|
27 |
))
|
|
|
28 |
|
29 |
-
#
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
)
|
38 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
39 |
return fig
|
40 |
|
41 |
-
def
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
47 |
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
'confidence': round((1 - topic['score_std']) * 100, 1)
|
54 |
-
}
|
55 |
-
formatted_topics.append(formatted_topic)
|
56 |
|
57 |
# 차트 생성
|
58 |
-
|
|
|
|
|
|
|
59 |
|
60 |
-
return
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
|
|
|
|
|
|
|
|
66 |
|
67 |
-
|
68 |
-
|
69 |
-
gr.Markdown("## 📚 문서 주제 분석기")
|
70 |
-
gr.Markdown("문서를 입력하면 관련된 주제들을 분석하여 보여줍니다.")
|
71 |
|
72 |
with gr.Row():
|
73 |
-
text = gr.Textbox(
|
74 |
-
value=SAMPLE_TEXT,
|
75 |
-
label="분석할 텍스트",
|
76 |
-
placeholder="여기에 분석할 텍스트를 입력하세요",
|
77 |
-
lines=5
|
78 |
-
)
|
79 |
|
80 |
with gr.Row():
|
81 |
-
submit_btn = gr.Button("분석 시작"
|
82 |
|
83 |
-
with gr.
|
84 |
-
|
85 |
-
|
|
|
|
|
86 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
87 |
with gr.Row():
|
88 |
output = gr.JSON(label="상세 분석 결과")
|
89 |
|
90 |
-
# 이벤트 연결
|
91 |
submit_btn.click(
|
92 |
-
fn=
|
93 |
inputs=[text],
|
94 |
-
outputs=[output,
|
95 |
)
|
96 |
|
97 |
-
demo.launch(debug=True)
|
|
|
3 |
import spaces
|
4 |
import wbgtopic
|
5 |
import plotly.graph_objects as go
|
6 |
+
import plotly.express as px
|
7 |
+
import plotly.figure_factory as ff
|
8 |
+
import nltk
|
9 |
+
import numpy as np
|
10 |
+
import pandas as pd
|
11 |
+
from collections import Counter
|
12 |
+
from scipy import stats
|
13 |
+
from wordcloud import WordCloud
|
14 |
from topic_translator import translate_topics
|
15 |
+
from nltk.tokenize import sent_tokenize, word_tokenize
|
16 |
+
from nltk.sentiment import SentimentIntensityAnalyzer
|
17 |
|
18 |
+
# NLTK 필요 데이터 다운로드
|
19 |
+
nltk.download('punkt')
|
20 |
+
nltk.download('vader_lexicon')
|
21 |
+
|
22 |
+
SAMPLE_TEXT = """
|
23 |
+
The three reportedly discussed the Stargate Project, a large-scale AI initiative led by OpenAI, SoftBank, and U.S. software giant Oracle. The project aims to invest $500 billion over the next four years in building new AI infrastructure in the U.S. The U.S. government has shown a strong commitment to the initiative, with President Donald Trump personally announcing it at the White House the day after his inauguration last month. If Samsung participates, the project will lead to a Korea-U.S.-Japan AI alliance.
|
24 |
+
The AI sector requires massive investments and extensive resources, including advanced models, high-performance AI chips to power the models, and large-scale data centers to operate them. Nvidia and TSMC currently dominate the AI sector, but a partnership between Samsung, SoftBank, and OpenAI could pave the way for a competitive alternative.
|
25 |
+
"""
|
26 |
|
27 |
clf = wbgtopic.WBGDocTopic()
|
28 |
|
29 |
+
def analyze_text_sections(text):
|
30 |
+
# 문단별 분석
|
31 |
+
sentences = sent_tokenize(text)
|
32 |
+
sections = [' '.join(sentences[i:i+3]) for i in range(0, len(sentences), 3)]
|
33 |
+
section_topics = []
|
34 |
|
35 |
+
for section in sections:
|
36 |
+
topics = clf.suggest_topics(section)[0]
|
37 |
+
section_topics.append(topics)
|
38 |
|
39 |
+
return section_topics
|
40 |
+
|
41 |
+
def calculate_topic_correlations(topics):
|
42 |
+
# 주제 간 상관관계 계산
|
43 |
+
topic_scores = {}
|
44 |
+
for topic in topics:
|
45 |
+
topic_scores[topic['label']] = topic['score_mean']
|
46 |
+
|
47 |
+
correlation_matrix = np.corrcoef(list(topic_scores.values()))
|
48 |
+
return correlation_matrix, list(topic_scores.keys())
|
49 |
+
|
50 |
+
def perform_sentiment_analysis(text):
|
51 |
+
# 감성 분석
|
52 |
+
sia = SentimentIntensityAnalyzer()
|
53 |
+
sentences = sent_tokenize(text)
|
54 |
+
sentiments = [sia.polarity_scores(sent) for sent in sentences]
|
55 |
+
return pd.DataFrame(sentiments)
|
56 |
+
|
57 |
+
def create_topic_clusters(topics):
|
58 |
+
# 주제 군집화
|
59 |
+
from sklearn.cluster import KMeans
|
60 |
+
X = np.array([[t['score_mean'], t['score_std']] for t in topics])
|
61 |
+
kmeans = KMeans(n_clusters=3, random_state=42)
|
62 |
+
clusters = kmeans.fit_predict(X)
|
63 |
+
return clusters
|
64 |
+
|
65 |
+
|
66 |
+
def create_main_charts(topics):
|
67 |
+
# 1. 기본 막대 차트
|
68 |
+
bar_fig = go.Figure()
|
69 |
+
bar_fig.add_trace(go.Bar(
|
70 |
+
x=[t['label'] for t in topics],
|
71 |
+
y=[t['score'] for t in topics],
|
72 |
name='관련도',
|
73 |
marker_color='rgb(55, 83, 109)'
|
74 |
))
|
75 |
+
bar_fig.update_layout(title='주제 분석 결과', height=500)
|
76 |
|
77 |
+
# 2. 레이더 차트
|
78 |
+
radar_fig = go.Figure()
|
79 |
+
radar_fig.add_trace(go.Scatterpolar(
|
80 |
+
r=[t['score'] for t in topics],
|
81 |
+
theta=[t['label'] for t in topics],
|
82 |
+
fill='toself',
|
83 |
+
name='주제 분포'
|
84 |
+
))
|
85 |
+
radar_fig.update_layout(title='주제 레이더 차트')
|
86 |
|
87 |
+
return bar_fig, radar_fig
|
88 |
+
|
89 |
+
def create_correlation_heatmap(corr_matrix, labels):
|
90 |
+
fig = go.Figure(data=go.Heatmap(
|
91 |
+
z=corr_matrix,
|
92 |
+
x=labels,
|
93 |
+
y=labels,
|
94 |
+
colorscale='Viridis'
|
95 |
+
))
|
96 |
+
fig.update_layout(title='주제 간 상관관계')
|
97 |
return fig
|
98 |
|
99 |
+
def create_topic_evolution(section_topics):
|
100 |
+
fig = go.Figure()
|
101 |
+
for topic in section_topics[0]:
|
102 |
+
topic_scores = [topics[topic['label']]['score_mean']
|
103 |
+
for topics in section_topics]
|
104 |
+
fig.add_trace(go.Scatter(
|
105 |
+
x=list(range(len(section_topics))),
|
106 |
+
y=topic_scores,
|
107 |
+
name=topic['label'],
|
108 |
+
mode='lines+markers'
|
109 |
+
))
|
110 |
+
fig.update_layout(title='주제 변화 ��이')
|
111 |
+
return fig
|
112 |
+
|
113 |
+
def create_confidence_gauge(topics):
|
114 |
+
fig = go.Figure()
|
115 |
+
for topic in topics:
|
116 |
+
fig.add_trace(go.Indicator(
|
117 |
+
mode="gauge+number",
|
118 |
+
value=topic['confidence'],
|
119 |
+
title={'text': topic['label']},
|
120 |
+
domain={'row': 0, 'column': 0}
|
121 |
+
))
|
122 |
+
fig.update_layout(grid={'rows': 1, 'columns': len(topics)})
|
123 |
+
return fig
|
124 |
+
|
125 |
+
|
126 |
+
def process_all_analysis(text):
|
127 |
+
# 기본 주제 분석
|
128 |
+
raw_results = clf.suggest_topics(text)
|
129 |
+
topics = process_results(raw_results)
|
130 |
|
131 |
+
# 추가 분석
|
132 |
+
section_topics = analyze_text_sections(text)
|
133 |
+
corr_matrix, labels = calculate_topic_correlations(topics)
|
134 |
+
sentiments = perform_sentiment_analysis(text)
|
135 |
+
clusters = create_topic_clusters(topics)
|
|
|
|
|
|
|
136 |
|
137 |
# 차트 생성
|
138 |
+
bar_chart, radar_chart = create_main_charts(topics)
|
139 |
+
heatmap = create_correlation_heatmap(corr_matrix, labels)
|
140 |
+
evolution_chart = create_topic_evolution(section_topics)
|
141 |
+
gauge_chart = create_confidence_gauge(topics)
|
142 |
|
143 |
+
return {
|
144 |
+
'topics': topics,
|
145 |
+
'bar_chart': bar_chart,
|
146 |
+
'radar_chart': radar_chart,
|
147 |
+
'heatmap': heatmap,
|
148 |
+
'evolution': evolution_chart,
|
149 |
+
'gauge': gauge_chart,
|
150 |
+
'sentiments': sentiments.to_dict(),
|
151 |
+
'clusters': clusters.tolist()
|
152 |
+
}
|
153 |
|
154 |
+
with gr.Blocks(title="고급 문서 주제 분석기") as demo:
|
155 |
+
gr.Markdown("## 📊 고급 문서 주제 분석기")
|
|
|
|
|
156 |
|
157 |
with gr.Row():
|
158 |
+
text = gr.Textbox(value=SAMPLE_TEXT, label="분석할 텍스트", lines=5)
|
|
|
|
|
|
|
|
|
|
|
159 |
|
160 |
with gr.Row():
|
161 |
+
submit_btn = gr.Button("분석 시작")
|
162 |
|
163 |
+
with gr.Tabs():
|
164 |
+
with gr.TabItem("주요 분석"):
|
165 |
+
with gr.Row():
|
166 |
+
plot1 = gr.Plot(label="주제 분포")
|
167 |
+
plot2 = gr.Plot(label="레이더 차트")
|
168 |
|
169 |
+
with gr.TabItem("상세 분석"):
|
170 |
+
with gr.Row():
|
171 |
+
plot3 = gr.Plot(label="상관관계 히트맵")
|
172 |
+
plot4 = gr.Plot(label="주제 변화 추이")
|
173 |
+
|
174 |
+
with gr.TabItem("신뢰도 분석"):
|
175 |
+
plot5 = gr.Plot(label="신뢰도 게이지")
|
176 |
+
|
177 |
+
with gr.TabItem("감성 분석"):
|
178 |
+
plot6 = gr.Plot(label="감성 분석 결과")
|
179 |
+
|
180 |
with gr.Row():
|
181 |
output = gr.JSON(label="상세 분석 결과")
|
182 |
|
|
|
183 |
submit_btn.click(
|
184 |
+
fn=process_all_analysis,
|
185 |
inputs=[text],
|
186 |
+
outputs=[output, plot1, plot2, plot3, plot4, plot5, plot6]
|
187 |
)
|
188 |
|
189 |
+
demo.launch(debug=True)
|