Spaces:
Running
on
Zero
Running
on
Zero
File size: 9,622 Bytes
dfa0bd7 2b1e4b7 d27df0e 96070b5 bc928c9 2c099cb ea6037b 2c099cb bc928c9 2c099cb ea6037b 2b1e4b7 2c099cb ea6037b 2c099cb ea6037b 4efedce ea6037b 2b1e4b7 ea6037b 2c099cb bc928c9 2c099cb bc928c9 2c099cb ea6037b 2c099cb ea6037b 2c099cb ea6037b 2c099cb ea6037b 2c099cb ea6037b 2c099cb ea6037b 2c099cb ea6037b 2c099cb bc928c9 ea6037b bc928c9 2c099cb ea6037b bc928c9 2c099cb ea6037b 2c099cb ea6037b bc928c9 ea6037b 2c099cb ea6037b 2c099cb ea6037b 2c099cb ea6037b 2c099cb ea6037b 2c099cb ea6037b 2c099cb ea6037b 2c099cb ea6037b 74b6cd5 ea6037b 74b6cd5 ea6037b bc928c9 ea6037b 96070b5 ea6037b 2c099cb ea6037b 74b6cd5 ea6037b 74b6cd5 ea6037b 74b6cd5 2c099cb bc928c9 2c099cb bc928c9 74b6cd5 4efedce 2c099cb 74b6cd5 2c099cb 4efedce ea6037b 58d3ab4 ea6037b |
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 |
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
import torch
from wordcloud import WordCloud
from topic_translator import translate_topics
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.sentiment import SentimentIntensityAnalyzer
from sklearn.cluster import KMeans
# GPU ์ค์
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# 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.
"""
# WBGDocTopic ์ด๊ธฐํ ์ device ์ง์
clf = wbgtopic.WBGDocTopic(device=device)
def safe_process(func):
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 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
@safe_process
def calculate_topic_correlations(topics):
topic_scores = {}
for topic in topics:
topic_scores[topic['label']] = topic['score_mean']
if len(topic_scores) < 2:
return np.array([[1]]), list(topic_scores.keys())
correlation_matrix = np.corrcoef(list(topic_scores.values()))
return correlation_matrix, list(topic_scores.keys())
@safe_process
def perform_sentiment_analysis(text):
sia = SentimentIntensityAnalyzer()
sentences = sent_tokenize(text)
sentiments = [sia.polarity_scores(sent) for sent in sentences]
return pd.DataFrame(sentiments)
@safe_process
def create_topic_clusters(topics):
if len(topics) < 3:
return np.zeros(len(topics))
X = np.array([[t['score_mean'], t['score_std']] for t in topics])
kmeans = KMeans(n_clusters=min(3, len(topics)), random_state=42)
clusters = kmeans.fit_predict(X)
return clusters
@safe_process
def create_main_charts(topics):
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,
xaxis_title='์ฃผ์ ',
yaxis_title='๊ด๋ จ๋ (%)',
template='plotly_white'
)
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='์ฃผ์ ๋ ์ด๋ ์ฐจํธ',
height=500,
template='plotly_white'
)
return bar_fig, radar_fig
@safe_process
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='์ฃผ์ ๊ฐ ์๊ด๊ด๊ณ',
height=500,
template='plotly_white'
)
return fig
@safe_process
def create_topic_evolution(section_topics):
if not section_topics or len(section_topics) == 0:
return go.Figure()
fig = go.Figure()
for topic in section_topics[0]:
try:
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'
))
except Exception as e:
print(f"Error processing topic {topic['label']}: {e}")
continue
fig.update_layout(
title='์ฃผ์ ๋ณํ ์ถ์ด',
xaxis_title='์น์
',
yaxis_title='๊ด๋ จ๋',
height=500,
template='plotly_white'
)
return fig
@safe_process
def create_confidence_gauge(topics):
fig = go.Figure()
for i, topic in enumerate(topics):
fig.add_trace(go.Indicator(
mode="gauge+number",
value=topic['confidence'],
title={'text': topic['label']},
domain={'row': 0, 'column': i, 'x': [i/len(topics), (i+1)/len(topics)]}
))
fig.update_layout(
grid={'rows': 1, 'columns': len(topics)},
height=400,
template='plotly_white'
)
return fig
@safe_process
def process_results(results):
if not results or not results[0]:
return []
topics = results[0]
top_topics = sorted(topics, key=lambda x: x['score_mean'], reverse=True)[:5]
formatted_topics = []
for topic in top_topics:
formatted_topic = {
'label': translate_topics.get(topic['label'], topic['label']),
'score': round(topic['score_mean'] * 100, 1),
'confidence': round((1 - topic['score_std']) * 100, 1)
}
formatted_topics.append(formatted_topic)
return formatted_topics
@spaces.GPU(enable_queue=True, duration=50)
def process_all_analysis(text):
try:
# ๊ธฐ๋ณธ ์ฃผ์ ๋ถ์
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() if sentiments is not None else {},
'clusters': clusters.tolist() if clusters is not None else []
}
except Exception as e:
print(f"Analysis error: {str(e)}")
return {
'error': str(e),
'topics': [],
'bar_chart': go.Figure(),
'radar_chart': go.Figure(),
'heatmap': go.Figure(),
'evolution': go.Figure(),
'gauge': go.Figure(),
'sentiments': {},
'clusters': []
}
# Gradio ์ธํฐํ์ด์ค
with gr.Blocks(title="๊ณ ๊ธ ๋ฌธ์ ์ฃผ์ ๋ถ์๊ธฐ") as demo:
gr.Markdown("## ๐ ๊ณ ๊ธ ๋ฌธ์ ์ฃผ์ ๋ถ์๊ธฐ")
gr.Markdown("๋ฌธ์๋ฅผ ์
๋ ฅํ๋ฉด ๋ค์ํ ๋ถ์ ๊ฒฐ๊ณผ๋ฅผ ์๊ฐํํ์ฌ ๋ณด์ฌ์ค๋๋ค.")
with gr.Row():
text = gr.Textbox(
value=SAMPLE_TEXT,
label="๋ถ์ํ ํ
์คํธ",
placeholder="์ฌ๊ธฐ์ ๋ถ์ํ ํ
์คํธ๋ฅผ ์
๋ ฅํ์ธ์",
lines=8
)
with gr.Row():
submit_btn = gr.Button("๋ถ์ ์์", variant="primary")
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]
)
if __name__ == "__main__":
demo.queue(max_size=1) # concurrency_count ๋์ max_size ์ฌ์ฉ
demo.launch(
server_name="0.0.0.0",
server_port=7860,
share=False,
debug=True
) |