File size: 14,908 Bytes
dfa0bd7
2b1e4b7
d27df0e
96070b5
bc928c9
2c099cb
 
 
6efc05e
2c099cb
 
ea6037b
6efc05e
ea6037b
5ad5437
ea6037b
2b1e4b7
5ad5437
6efc05e
 
5ad5437
ea6037b
 
 
2134133
5ad5437
2c099cb
5ad5437
2134133
 
 
 
4efedce
ea6037b
2134133
5ad5437
 
2134133
ea6037b
 
 
 
 
 
 
2b1e4b7
6efc05e
 
 
5ad5437
 
 
 
 
 
 
 
 
 
 
 
6efc05e
5ad5437
 
 
 
6efc05e
 
2134133
6efc05e
2134133
5ad5437
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2134133
5ad5437
 
 
 
 
 
 
 
 
6efc05e
5ad5437
 
 
 
 
 
 
 
 
6efc05e
5ad5437
6efc05e
2134133
 
5ad5437
6efc05e
 
 
5ad5437
2134133
6efc05e
ea6037b
2c099cb
6efc05e
5ad5437
 
6efc05e
2c099cb
5ad5437
2c099cb
2134133
6efc05e
2c099cb
6efc05e
 
 
2c099cb
2134133
6efc05e
ea6037b
6efc05e
 
5ad5437
 
 
 
 
6efc05e
 
 
2134133
6efc05e
2134133
 
6efc05e
 
2134133
6efc05e
 
5a47f9e
ea6037b
2c099cb
2134133
5ad5437
 
2134133
2c099cb
6efc05e
 
 
 
ea6037b
6efc05e
2134133
5ad5437
 
2134133
6efc05e
2134133
 
6efc05e
 
 
2134133
6efc05e
 
2134133
 
6efc05e
2c099cb
2134133
2c099cb
ea6037b
6efc05e
 
5ad5437
 
6efc05e
 
 
2134133
6efc05e
5ad5437
2134133
5ad5437
6efc05e
 
 
ea6037b
5ad5437
 
 
6efc05e
 
ea6037b
2134133
5ad5437
2c099cb
 
6efc05e
 
2c099cb
5ad5437
2c099cb
ea6037b
5ad5437
6efc05e
ea6037b
6efc05e
 
ea6037b
2c099cb
 
ea6037b
2c099cb
2134133
5ad5437
 
2134133
6efc05e
5ad5437
6efc05e
2134133
 
5ad5437
6efc05e
 
 
2134133
2c099cb
 
 
 
 
 
ea6037b
5ad5437
ea6037b
 
 
bc928c9
 
ea6037b
2c099cb
6efc05e
5ad5437
 
6efc05e
2c099cb
6efc05e
 
2134133
6efc05e
 
2134133
5ad5437
6efc05e
 
 
 
 
 
 
 
 
2134133
6efc05e
 
 
 
 
 
2134133
ea6037b
5ad5437
 
 
ea6037b
 
 
2c099cb
 
ea6037b
6efc05e
 
5ad5437
 
6efc05e
 
 
2134133
2c099cb
6efc05e
2134133
6efc05e
2134133
2c099cb
 
2134133
6efc05e
 
2c099cb
2134133
ea6037b
6efc05e
ea6037b
 
 
2c099cb
 
6efc05e
 
2134133
5ad5437
 
2134133
6efc05e
5ad5437
6efc05e
2134133
 
5ad5437
6efc05e
 
2134133
5ad5437
2134133
 
5ad5437
6efc05e
 
 
2134133
5ad5437
2134133
6efc05e
 
 
2134133
5ad5437
6efc05e
5ad5437
 
 
ea6037b
2134133
6efc05e
5ad5437
 
 
 
 
 
 
6efc05e
2134133
6efc05e
 
 
 
 
 
 
 
 
 
 
 
ea6037b
2134133
 
 
96070b5
5ad5437
 
2134133
5ad5437
 
2134133
5a47f9e
74b6cd5
6efc05e
ea6037b
5ad5437
ea6037b
 
74b6cd5
5ad5437
2134133
2c099cb
5ad5437
2c099cb
5ad5437
 
 
2c099cb
5ad5437
 
 
 
 
 
2134133
bc928c9
5ad5437
2134133
4efedce
2c099cb
6efc05e
 
4efedce
 
ea6037b
5a47f9e
ea6037b
 
 
5ad5437
ea6037b
6efc05e
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
import json
import gradio as gr
import spaces
import wbgtopic
import plotly.graph_objects as go
import plotly.express as px
import numpy as np
import pandas as pd
import nltk
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.sentiment import SentimentIntensityAnalyzer
from sklearn.cluster import KMeans
import torch

# GPU ์‚ฌ์šฉ ๊ฐ€๋Šฅ ์‹œ ์„ค์ •
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

# WBGDocTopic ์ดˆ๊ธฐํ™”
clf = wbgtopic.WBGDocTopic(device=device)

# NLTK ๋ฐ์ดํ„ฐ ๋‹ค์šด๋กœ๋“œ (ํ•„์š” ์‹œ)
try:
    nltk.download('punkt', quiet=True)
    nltk.download('vader_lexicon', quiet=True)
except Exception as e:
    print(f"NLTK ๋ฐ์ดํ„ฐ ๋‹ค์šด๋กœ๋“œ ์—๋Ÿฌ: {e}")

# ์ƒ˜ํ”Œ ํ…์ŠคํŠธ
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.
"""

def safe_process(func):
    """
    ์˜ˆ์™ธ ๋ฐœ์ƒ ์‹œ ๋กœ๊ทธ๋ฅผ ๋‚จ๊ธฐ๊ณ  None์„ ๋ฐ˜ํ™˜ํ•˜๋Š” ๋ฐ์ฝ”๋ ˆ์ดํ„ฐ.
    Gradio ์ธํ„ฐํŽ˜์ด์Šค๊ฐ€ ์˜ˆ์™ธ๋กœ ์ธํ•ด ์ค‘๋‹จ๋˜์ง€ ์•Š๋„๋ก ๋„์™€์ค๋‹ˆ๋‹ค.
    """
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            print(f"Error in {func.__name__}: {str(e)}")
            return None
    return wrapper

@safe_process
def parse_wbg_results(raw_output):
    """
    wbgtopic.WBGDocTopic์˜ suggest_topics() ๊ฒฐ๊ณผ๋ฅผ
    'label', 'score_mean', 'score_std' ๊ตฌ์กฐ์˜ ๋ฆฌ์ŠคํŠธ๋กœ ํ†ต์ผํ•ด์„œ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

    ๋ฐ˜ํ™˜ ๊ตฌ์กฐ ์˜ˆ์‹œ:
    [
      {
        "label": "Agriculture",
        "score_mean": 0.32,
        "score_std": 0.05
      },
      ...
    ]
    """
    # ๋””๋ฒ„๊ทธ: ์‹ค์ œ ๊ฒฐ๊ณผ ๊ตฌ์กฐ๋ฅผ ํ™•์ธํ•ด๋ณด์„ธ์š”
    print(">>> DEBUG: raw_output =", raw_output)

    # ๊ฒฐ๊ณผ๊ฐ€ ๋น„์—ˆ์œผ๋ฉด ๋นˆ ๋ฆฌ์ŠคํŠธ ๋ฐ˜ํ™˜
    if not raw_output:
        return []

    first_item = raw_output[0]

    # (1) ์ด๋ฏธ 'label' ํ‚ค๊ฐ€ ์žˆ๋Š” ๋”•์…”๋„ˆ๋ฆฌ ํ˜•ํƒœ๋ผ๋ฉด
    # ์˜ˆ: [{"label": "...", "score": ...}, ...] ํ˜น์€ {"label": "...", "score_mean": ...}
    if isinstance(first_item, dict) and ("label" in first_item):
        parsed_list = []
        for item in raw_output:
            label = item.get("label", "")
            # score_mean / score_std๊ฐ€ ์ด๋ฏธ ์žˆ์œผ๋ฉด ์‚ฌ์šฉ
            # ์—†์œผ๋ฉด score ๋“ฑ์—์„œ ์ถ”๋ก 
            score_mean = item.get("score_mean", None)
            score_std = item.get("score_std", None)

            # ์˜ˆ: score๋งŒ ์žˆ๋Š” ๊ฒฝ์šฐ
            if score_mean is None and "score" in item:
                # ์ ์ˆ˜๊ฐ€ 0~1 ๋ฒ”์œ„์ธ์ง€ 0~100 ๋ฒ”์œ„์ธ์ง€ ํ™•์ธ ํ•„์š”
                # ์šฐ์„  ๊ทธ๋Œ€๋กœ float ์ฒ˜๋ฆฌ
                score_mean = float(item["score"])
            if score_mean is None:
                score_mean = 0.0

            if score_std is None:
                score_std = 0.0

            parsed_list.append({
                "label": label,
                "score_mean": float(score_mean),
                "score_std": float(score_std)
            })
        return parsed_list

    # (2) ํ† ํ”ฝ ์ด๋ฆ„: ์ ์ˆ˜ ํ˜•ํƒœ์˜ ๋”•์…”๋„ˆ๋ฆฌ๊ฐ€ ์žˆ๋Š” ๊ฒฝ์šฐ
    # ์˜ˆ: [{"Agriculture": 0.22, "Climate Change": 0.55}, ...]
    if isinstance(first_item, dict):
        # raw_output๊ฐ€ ์—ฌ๋Ÿฌ dict๋ฅผ ๋‹ด๊ณ  ์žˆ์„ ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ, ํ•˜๋‚˜๋กœ ํ•ฉ์น˜๊ฑฐ๋‚˜
        # ํ˜น์€ ์ฒซ ๋ฒˆ์งธ dict๋งŒ ํŒŒ์‹ฑํ• ์ง€ ๊ฒฐ์ •ํ•ด์•ผ ํ•จ.
        # ์ผ๋‹จ ์—ฌ๊ธฐ์„œ๋Š” ํ•ฉ์น˜๋Š” ๋ฐฉ์‹์œผ๋กœ ์‹œ์—ฐ:
        merged = {}
        for d in raw_output:
            for k, v in d.items():
                # ํ‚ค ์ค‘๋ณต ์‹œ ๋งˆ์ง€๋ง‰ ๊ฐ’์œผ๋กœ overwrite
                merged[k] = v

        parsed_list = []
        for label, val in merged.items():
            parsed_list.append({
                "label": label,
                "score_mean": float(val),
                "score_std": 0.0
            })
        return parsed_list

    # ์˜ˆ์ƒ์น˜ ๋ชปํ•œ ๊ตฌ์กฐ์ธ ๊ฒฝ์šฐ
    return []

@safe_process
def analyze_text_sections(text):
    """
    ํ…์ŠคํŠธ๋ฅผ ์—ฌ๋Ÿฌ ์„น์…˜(์˜ˆ: 3๋ฌธ์žฅ์”ฉ)์œผ๋กœ ๋‚˜๋ˆ„๊ณ ,
    ๊ฐ ์„น์…˜๋ณ„๋กœ suggest_topics() ๊ฒฐ๊ณผ๋ฅผ parse_wbg_results()๋กœ ํŒŒ์‹ฑํ•ด ๋ฆฌ์ŠคํŠธ๋กœ ๋ชจ์€๋‹ค.
    """
    sentences = sent_tokenize(text)
    # 3๋ฌธ์žฅ์”ฉ ๋ฌถ์–ด์„œ ํ•˜๋‚˜์˜ ์„น์…˜์„ ๊ตฌ์„ฑ
    sections = [' '.join(sentences[i:i+3]) for i in range(0, len(sentences), 3)]

    section_topics = []
    for section in sections:
        raw_sec = clf.suggest_topics(section)
        parsed_sec = parse_wbg_results(raw_sec)
        section_topics.append(parsed_sec)

    return section_topics

@safe_process
def calculate_topic_correlations(topic_dicts):
    """
    topic_dicts: [{'label': ..., 'score_mean': ..., 'score_std': ...}, ...]

    ์ฃผ์ œ๋ณ„ score_mean๋งŒ ๋ฝ‘์•„์„œ ์ƒ๊ด€๊ด€๊ณ„๋ฅผ ๊ตฌํ•œ๋‹ค.
    ์‹ค์ œ๋กœ๋Š” '์„œ๋กœ ๋‹ค๋ฅธ ๋ฌธ์„œ'๋“ค์— ๋Œ€ํ•œ ์ƒ๊ด€์„ ๊ตฌํ•˜๋Š” ๊ฒƒ์ด ํƒ€๋‹นํ•˜๋‚˜,
    ์—ฌ๊ธฐ์„œ๋Š” ์˜ˆ์‹œ๋กœ ๋‹จ์ผ ํ…์ŠคํŠธ์˜ ์„œ๋กœ ๋‹ค๋ฅธ ํ† ํ”ฝ๋“ค ๊ฐ„ ์ ์ˆ˜ ์ƒ๊ด€๋„๋ฅผ ๊ณ„์‚ฐํ•œ๋‹ค.
    """
    if len(topic_dicts) < 2:
        return np.array([[1.0]]), ["Insufficient topics"]

    labels = [d['label'] for d in topic_dicts]
    scores = [d['score_mean'] for d in topic_dicts]

    if len(scores) < 2:
        return np.array([[1.0]]), ["Insufficient topics"]

    corr_matrix = np.corrcoef(scores)
    return corr_matrix, labels

@safe_process
def perform_sentiment_analysis(text):
    """
    NLTK VADER๋ฅผ ์‚ฌ์šฉํ•ด ๋ฌธ์žฅ๋ณ„ ๊ฐ์„ฑ ์ ์ˆ˜๋ฅผ ๊ณ„์‚ฐํ•œ๋‹ค.
    ๋ฐ˜ํ™˜๊ฐ’์€ pandas DataFrame ํ˜•์‹.
    """
    sia = SentimentIntensityAnalyzer()
    sents = sent_tokenize(text)
    results = [sia.polarity_scores(s) for s in sents]
    return pd.DataFrame(results)

@safe_process
def create_topic_clusters(topic_dicts):
    """
    score_mean, score_std 2์ฐจ์›์œผ๋กœ KMeans ํด๋Ÿฌ์Šคํ„ฐ๋ง.
    ํ† ํ”ฝ ์ˆ˜๊ฐ€ 3๊ฐœ ๋ฏธ๋งŒ์ด๋ฉด trivially 0๋ฒˆ ํด๋Ÿฌ์Šคํ„ฐ๋กœ ์ฒ˜๋ฆฌ.
    """
    if len(topic_dicts) < 3:
        return [0] * len(topic_dicts)

    X = []
    for t in topic_dicts:
        X.append([t['score_mean'], t.get('score_std', 0.0)])

    X = np.array(X)
    if X.shape[0] < 3:
        return [0] * X.shape[0]

    kmeans = KMeans(n_clusters=min(3, X.shape[0]), random_state=42)
    clusters = kmeans.fit_predict(X)
    return clusters.tolist()

@safe_process
def create_main_charts(topic_dicts):
    """
    ๋ฐ” ์ฐจํŠธ์™€ ๋ ˆ์ด๋” ์ฐจํŠธ๋ฅผ ์ƒ์„ฑ.
    'score_mean'์„ 0~1๋กœ ๋ณด๊ณ , 100๋ฐฐ ํ•˜์—ฌ ํผ์„ผํŠธ๋กœ ์‹œ๊ฐํ™”.
    """
    if not topic_dicts:
        return go.Figure(), go.Figure()

    labels = [t['label'] for t in topic_dicts]
    scores = [t['score_mean'] * 100 for t in topic_dicts]

    # ๋ฐ” ์ฐจํŠธ
    bar_fig = go.Figure(
        data=[go.Bar(x=labels, y=scores, marker_color='rgb(55, 83, 109)')]
    )
    bar_fig.update_layout(
        title='์ฃผ์ œ ๋ถ„์„ ๊ฒฐ๊ณผ',
        xaxis_title='์ฃผ์ œ',
        yaxis_title='๊ด€๋ จ๋„(%)',
        template='plotly_white',
        height=500,
    )

    # ๋ ˆ์ด๋” ์ฐจํŠธ
    radar_fig = go.Figure()
    radar_fig.add_trace(go.Scatterpolar(
        r=scores,
        theta=labels,
        fill='toself',
        name='์ฃผ์ œ ๋ถ„ํฌ'
    ))
    radar_fig.update_layout(
        title='์ฃผ์ œ ๋ ˆ์ด๋” ์ฐจํŠธ',
        template='plotly_white',
        height=500,
        polar=dict(radialaxis=dict(visible=True)),
        showlegend=False
    )
    return bar_fig, radar_fig

@safe_process
def create_correlation_heatmap(corr_matrix, labels):
    """
    ์ƒ๊ด€๊ด€๊ณ„ ํ–‰๋ ฌ์„ ํžˆํŠธ๋งต์œผ๋กœ ์‹œ๊ฐํ™”.
    ๋งŒ์•ฝ ๋ฐ์ดํ„ฐ๊ฐ€ ๋ถ€์กฑํ•˜๋ฉด ์•ˆ๋‚ด ๋ฌธ๊ตฌ๋งŒ ํ‘œ์‹œ.
    """
    if corr_matrix.ndim == 0:
        # ์Šค์นผ๋ผ(0์ฐจ์›)์ด๋ฉด 2์ฐจ์› ๋ฐฐ์—ด๋กœ ๋ฐ”๊ฟ”์คŒ
        corr_matrix = np.array([[corr_matrix]])

    if corr_matrix.shape == (1, 1):
        # ๋ฐ์ดํ„ฐ๊ฐ€ ๋ถ€์กฑํ•œ ๊ฒฝ์šฐ
        fig = go.Figure()
        fig.add_annotation(text="Not enough topics for correlation", showarrow=False)
        return fig

    fig = go.Figure(data=go.Heatmap(
        z=corr_matrix,
        x=labels,
        y=labels,
        colorscale='Viridis'
    ))
    fig.update_layout(
        title='์ฃผ์ œ ์ƒ๊ด€๊ด€๊ณ„ ํžˆํŠธ๋งต',
        height=500,
        template='plotly_white'
    )
    return fig

@safe_process
def create_topic_evolution(section_topics):
    """
    ์„น์…˜๋ณ„ ํ† ํ”ฝ ์ ์ˆ˜ ๋ณ€ํ™”๋ฅผ ๋ผ์ธ ์ฐจํŠธ๋กœ ๋‚˜ํƒ€๋‚ธ๋‹ค.
    section_topics: [[{'label':..., 'score_mean':...}, ...], [...], ...]
    """
    fig = go.Figure()
    if not section_topics or len(section_topics) == 0:
        return fig

    if not section_topics[0]:
        return fig

    # ์ฒซ ์„น์…˜์˜ ํ† ํ”ฝ๋“ค์„ ๊ธฐ์ค€์œผ๋กœ, ๊ฐ ์„น์…˜๋งˆ๋‹ค ํ•ด๋‹น ํ† ํ”ฝ์ด ์กด์žฌํ•˜๋ฉด ์ ์ˆ˜๋ฅผ ์ถ”์ถœ
    for topic_dict in section_topics[0]:
        label = topic_dict['label']
        score_list = []
        for sec_list in section_topics:
            match = next((d for d in sec_list if d['label'] == label), None)
            if match:
                score_list.append(match['score_mean'])
            else:
                score_list.append(0.0)

        fig.add_trace(go.Scatter(
            x=list(range(len(section_topics))),
            y=score_list,
            name=label,
            mode='lines+markers'
        ))

    fig.update_layout(
        title='์„น์…˜๋ณ„ ์ฃผ์ œ ๋ณ€ํ™” ์ถ”์ด',
        xaxis_title='์„น์…˜',
        yaxis_title='score_mean',
        height=500,
        template='plotly_white'
    )
    return fig

@safe_process
def create_confidence_gauge(topic_dicts):
    """
    ๊ฐ ํ† ํ”ฝ์˜ ์‹ ๋ขฐ๋„๋ฅผ ๊ฒŒ์ด์ง€ ํ˜•ํƒœ๋กœ ํ‘œ์‹œ.
    ์—ฌ๊ธฐ์„œ๋Š” (1 - score_std) * 100 ๋‹จ์ˆœ ๊ณต์‹ ์‚ฌ์šฉ.
    """
    if not topic_dicts:
        return go.Figure()

    fig = go.Figure()
    num_topics = len(topic_dicts)

    for i, t in enumerate(topic_dicts):
        conf_val = 100.0 * (1.0 - t.get("score_std", 0.0))
        fig.add_trace(go.Indicator(
            mode="gauge+number",
            value=conf_val,
            title={'text': t['label']},
            domain={'row': 0, 'column': i}
        ))

    fig.update_layout(
        grid={'rows': 1, 'columns': num_topics},
        height=400,
        template='plotly_white'
    )
    return fig

@spaces.GPU()
def process_all_analysis(text):
    """
    ์ „์ฒด ํ…์ŠคํŠธ์— ๋Œ€ํ•œ ํ† ํ”ฝ ๋ถ„์„, ์„น์…˜ ๋ถ„์„, ์ƒ๊ด€๊ด€๊ณ„, ๊ฐ์„ฑ๋ถ„์„, ํด๋Ÿฌ์Šคํ„ฐ๋ง ๋“ฑ์„ ์ˆ˜ํ–‰ํ•œ ๋’ค
    JSON ๊ฒฐ๊ณผ์™€ Plotly ์ฐจํŠธ๋“ค์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค.
    """
    try:
        # 1) ์ „์ฒด ํ…์ŠคํŠธ ๋Œ€์ƒ ํ† ํ”ฝ ๋ถ„์„
        raw_results = clf.suggest_topics(text)
        all_topics = parse_wbg_results(raw_results)

        # 2) score_mean ๊ธฐ์ค€ ๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌ ํ›„ ์ƒ์œ„ 5๊ฐœ
        sorted_topics = sorted(all_topics, key=lambda x: x['score_mean'], reverse=True)
        top_topics = sorted_topics[:5]

        # 3) ์„น์…˜ ๋ณ„ ๋ถ„์„
        section_topics = analyze_text_sections(text)

        # 4) ์ถ”๊ฐ€ ๋ถ„์„(์ƒ๊ด€๊ด€๊ณ„, ๊ฐ์„ฑ๋ถ„์„, ํด๋Ÿฌ์Šคํ„ฐ)
        corr_matrix, corr_labels = calculate_topic_correlations(all_topics)
        sentiments_df = perform_sentiment_analysis(text)
        clusters = create_topic_clusters(all_topics)

        # 5) ์ฐจํŠธ ์ƒ์„ฑ
        bar_chart, radar_chart = create_main_charts(top_topics)
        heatmap = create_correlation_heatmap(corr_matrix, corr_labels)
        evolution_chart = create_topic_evolution(section_topics)
        gauge_chart = create_confidence_gauge(top_topics)

        # 6) JSON ํ˜•ํƒœ๋กœ ๋ฌถ์–ด์„œ ๋ฐ˜ํ™˜(๋ฌธ์ž์—ด ํ‚ค๋งŒ ์‚ฌ์šฉ)
        results = {
            "top_topics": top_topics,                         # ์ƒ์œ„ 5๊ฐœ ํ† ํ”ฝ
            "clusters": clusters,                             # ํด๋Ÿฌ์Šคํ„ฐ ๊ฒฐ๊ณผ
            "sentiments": sentiments_df.to_dict(orient="records")  # ๊ฐ์„ฑ ๋ถ„์„
        }

        return (
            results,          # JSON output
            bar_chart,        # plot1
            radar_chart,      # plot2
            heatmap,          # plot3
            evolution_chart,  # plot4
            gauge_chart,      # plot5
            go.Figure()       # plot6 (ํ•„์š” ์‹œ ๊ฐ์„ฑ๋ถ„์„ ๊ทธ๋ž˜ํ”„ ์‚ฌ์šฉ)
        )

    except Exception as e:
        print(f"Analysis error: {str(e)}")
        empty_fig = go.Figure()
        return (
            {"error": str(e), "topics": []},
            empty_fig,
            empty_fig,
            empty_fig,
            empty_fig,
            empty_fig,
            empty_fig
        )

######################################################
#                Gradio UI Definition               #
######################################################

with gr.Blocks(title="๊ณ ๊ธ‰ ๋ฌธ์„œ ์ฃผ์ œ ๋ถ„์„๊ธฐ") as demo:
    gr.Markdown("## ๊ณ ๊ธ‰ ๋ฌธ์„œ ์ฃผ์ œ ๋ถ„์„๊ธฐ")
    gr.Markdown(
        "ํ…์ŠคํŠธ๋ฅผ ์ž…๋ ฅํ•œ ๋’ค, **๋ถ„์„ ์‹œ์ž‘** ๋ฒ„ํŠผ์„ ๋ˆŒ๋Ÿฌ์ฃผ์„ธ์š”. "
        "์ฃผ์š” ํ† ํ”ฝ ๋ถ„์„, ์ƒ๊ด€๊ด€๊ณ„, ์‹ ๋ขฐ๋„ ๊ฒŒ์ด์ง€, ๊ฐ์„ฑ๋ถ„์„ ๊ฒฐ๊ณผ ๋“ฑ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค."
    )

    with gr.Row():
        text_input = gr.Textbox(
            value=SAMPLE_TEXT,
            label="๋ถ„์„ํ•  ํ…์ŠคํŠธ ์ž…๋ ฅ",
            lines=8
        )
    with gr.Row():
        submit_btn = gr.Button("๋ถ„์„ ์‹œ์ž‘", variant="primary")

    with gr.Tabs():
        with gr.TabItem("์ฃผ์š” ๋ถ„์„"):
            with gr.Row():
                plot1 = gr.Plot(label="์ฃผ์ œ ๋ถ„ํฌ(Bar Chart)")
                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_json = gr.JSON(label="์ƒ์„ธ ๋ถ„์„ ๊ฒฐ๊ณผ(JSON)")

    submit_btn.click(
        fn=process_all_analysis,
        inputs=[text_input],
        outputs=[output_json, plot1, plot2, plot3, plot4, plot5, plot6]
    )

if __name__ == "__main__":
    demo.queue(max_size=1)
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False,  # ๊ณต๊ฐœ ๋งํฌ ํ•„์š” ์‹œ True
        debug=True
    )