openfree's picture
Update app.py
2c099cb verified
raw
history blame
6.55 kB
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)