File size: 6,553 Bytes
dfa0bd7
2b1e4b7
d27df0e
96070b5
bc928c9
2c099cb
 
 
 
 
 
 
 
bc928c9
2c099cb
 
2b1e4b7
2c099cb
 
 
 
 
 
 
 
4efedce
96070b5
2b1e4b7
2c099cb
 
 
 
 
bc928c9
2c099cb
 
 
bc928c9
2c099cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc928c9
 
 
2c099cb
bc928c9
2c099cb
 
 
 
 
 
 
 
 
bc928c9
2c099cb
 
 
 
 
 
 
 
 
 
bc928c9
 
2c099cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74b6cd5
2c099cb
 
 
 
 
74b6cd5
bc928c9
2c099cb
 
 
 
bc928c9
2c099cb
 
 
 
 
 
 
 
 
 
96070b5
2c099cb
 
74b6cd5
 
2c099cb
74b6cd5
 
2c099cb
74b6cd5
2c099cb
 
 
 
 
bc928c9
2c099cb
 
 
 
 
 
 
 
 
 
 
bc928c9
 
74b6cd5
4efedce
2c099cb
74b6cd5
2c099cb
4efedce
 
2c099cb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
import json
import gradio as gr
import spaces
import wbgtopic
import plotly.graph_objects as go
import plotly.express as px
import plotly.figure_factory as ff
import nltk
import numpy as np
import pandas as pd
from collections import Counter
from scipy import stats
from wordcloud import WordCloud
from topic_translator import translate_topics
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.sentiment import SentimentIntensityAnalyzer

# NLTK ํ•„์š” ๋ฐ์ดํ„ฐ ๋‹ค์šด๋กœ๋“œ
nltk.download('punkt')
nltk.download('vader_lexicon')

SAMPLE_TEXT = """
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.
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.
"""  

clf = wbgtopic.WBGDocTopic()

def analyze_text_sections(text):
    # ๋ฌธ๋‹จ๋ณ„ ๋ถ„์„
    sentences = sent_tokenize(text)
    sections = [' '.join(sentences[i:i+3]) for i in range(0, len(sentences), 3)]
    section_topics = []
    
    for section in sections:
        topics = clf.suggest_topics(section)[0]
        section_topics.append(topics)
    
    return section_topics

def calculate_topic_correlations(topics):
    # ์ฃผ์ œ ๊ฐ„ ์ƒ๊ด€๊ด€๊ณ„ ๊ณ„์‚ฐ
    topic_scores = {}
    for topic in topics:
        topic_scores[topic['label']] = topic['score_mean']
    
    correlation_matrix = np.corrcoef(list(topic_scores.values()))
    return correlation_matrix, list(topic_scores.keys())

def perform_sentiment_analysis(text):
    # ๊ฐ์„ฑ ๋ถ„์„
    sia = SentimentIntensityAnalyzer()
    sentences = sent_tokenize(text)
    sentiments = [sia.polarity_scores(sent) for sent in sentences]
    return pd.DataFrame(sentiments)

def create_topic_clusters(topics):
    # ์ฃผ์ œ ๊ตฐ์ง‘ํ™”
    from sklearn.cluster import KMeans
    X = np.array([[t['score_mean'], t['score_std']] for t in topics])
    kmeans = KMeans(n_clusters=3, random_state=42)
    clusters = kmeans.fit_predict(X)
    return clusters


def create_main_charts(topics):
    # 1. ๊ธฐ๋ณธ ๋ง‰๋Œ€ ์ฐจํŠธ
    bar_fig = go.Figure()
    bar_fig.add_trace(go.Bar(
        x=[t['label'] for t in topics],
        y=[t['score'] for t in topics],
        name='๊ด€๋ จ๋„',
        marker_color='rgb(55, 83, 109)'
    ))
    bar_fig.update_layout(title='์ฃผ์ œ ๋ถ„์„ ๊ฒฐ๊ณผ', height=500)
    
    # 2. ๋ ˆ์ด๋” ์ฐจํŠธ
    radar_fig = go.Figure()
    radar_fig.add_trace(go.Scatterpolar(
        r=[t['score'] for t in topics],
        theta=[t['label'] for t in topics],
        fill='toself',
        name='์ฃผ์ œ ๋ถ„ํฌ'
    ))
    radar_fig.update_layout(title='์ฃผ์ œ ๋ ˆ์ด๋” ์ฐจํŠธ')
    
    return bar_fig, radar_fig

def create_correlation_heatmap(corr_matrix, labels):
    fig = go.Figure(data=go.Heatmap(
        z=corr_matrix,
        x=labels,
        y=labels,
        colorscale='Viridis'
    ))
    fig.update_layout(title='์ฃผ์ œ ๊ฐ„ ์ƒ๊ด€๊ด€๊ณ„')
    return fig

def create_topic_evolution(section_topics):
    fig = go.Figure()
    for topic in section_topics[0]:
        topic_scores = [topics[topic['label']]['score_mean'] 
                       for topics in section_topics]
        fig.add_trace(go.Scatter(
            x=list(range(len(section_topics))),
            y=topic_scores,
            name=topic['label'],
            mode='lines+markers'
        ))
    fig.update_layout(title='์ฃผ์ œ ๋ณ€ํ™” ์ถ”์ด')
    return fig

def create_confidence_gauge(topics):
    fig = go.Figure()
    for topic in topics:
        fig.add_trace(go.Indicator(
            mode="gauge+number",
            value=topic['confidence'],
            title={'text': topic['label']},
            domain={'row': 0, 'column': 0}
        ))
    fig.update_layout(grid={'rows': 1, 'columns': len(topics)})
    return fig


def process_all_analysis(text):
    # ๊ธฐ๋ณธ ์ฃผ์ œ ๋ถ„์„
    raw_results = clf.suggest_topics(text)
    topics = process_results(raw_results)
    
    # ์ถ”๊ฐ€ ๋ถ„์„
    section_topics = analyze_text_sections(text)
    corr_matrix, labels = calculate_topic_correlations(topics)
    sentiments = perform_sentiment_analysis(text)
    clusters = create_topic_clusters(topics)
    
    # ์ฐจํŠธ ์ƒ์„ฑ
    bar_chart, radar_chart = create_main_charts(topics)
    heatmap = create_correlation_heatmap(corr_matrix, labels)
    evolution_chart = create_topic_evolution(section_topics)
    gauge_chart = create_confidence_gauge(topics)
    
    return {
        'topics': topics,
        'bar_chart': bar_chart,
        'radar_chart': radar_chart,
        'heatmap': heatmap,
        'evolution': evolution_chart,
        'gauge': gauge_chart,
        'sentiments': sentiments.to_dict(),
        'clusters': clusters.tolist()
    }

with gr.Blocks(title="๊ณ ๊ธ‰ ๋ฌธ์„œ ์ฃผ์ œ ๋ถ„์„๊ธฐ") as demo:
    gr.Markdown("## ๐Ÿ“Š ๊ณ ๊ธ‰ ๋ฌธ์„œ ์ฃผ์ œ ๋ถ„์„๊ธฐ")
    
    with gr.Row():
        text = gr.Textbox(value=SAMPLE_TEXT, label="๋ถ„์„ํ•  ํ…์ŠคํŠธ", lines=5)
    
    with gr.Row():
        submit_btn = gr.Button("๋ถ„์„ ์‹œ์ž‘")
    
    with gr.Tabs():
        with gr.TabItem("์ฃผ์š” ๋ถ„์„"):
            with gr.Row():
                plot1 = gr.Plot(label="์ฃผ์ œ ๋ถ„ํฌ")
                plot2 = gr.Plot(label="๋ ˆ์ด๋” ์ฐจํŠธ")
        
        with gr.TabItem("์ƒ์„ธ ๋ถ„์„"):
            with gr.Row():
                plot3 = gr.Plot(label="์ƒ๊ด€๊ด€๊ณ„ ํžˆํŠธ๋งต")
                plot4 = gr.Plot(label="์ฃผ์ œ ๋ณ€ํ™” ์ถ”์ด")
            
        with gr.TabItem("์‹ ๋ขฐ๋„ ๋ถ„์„"):
            plot5 = gr.Plot(label="์‹ ๋ขฐ๋„ ๊ฒŒ์ด์ง€")
            
        with gr.TabItem("๊ฐ์„ฑ ๋ถ„์„"):
            plot6 = gr.Plot(label="๊ฐ์„ฑ ๋ถ„์„ ๊ฒฐ๊ณผ")
            
    with gr.Row():
        output = gr.JSON(label="์ƒ์„ธ ๋ถ„์„ ๊ฒฐ๊ณผ")
    
    submit_btn.click(
        fn=process_all_analysis,
        inputs=[text],
        outputs=[output, plot1, plot2, plot3, plot4, plot5, plot6]
    )

demo.launch(debug=True)