Spaces:
Paused
Paused
Update app.py
Browse files11 unmodified lines12131415161718192021222324252627282930312 unmodified lines3435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082091 unmodified line2112122132142152162172182192202212222232242252262272282291 unmodified line2312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073081 unmodified line3103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533541 unmodified line3563573583593603613623633647 unmodified lines3723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104115 unmodified lines41741841942042142211 unmodified linesfrom sklearn.cluster import KMeansimport torchdevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')# Initialize WBGDocTopicclf = wbgtopic.WBGDocTopic(device=device)try:nltk.download('punkt', quiet=True)nltk.download('vader_lexicon', quiet=True)except:passSAMPLE_TEXT = """Your sample text here ..."""def safe_process(func):def wrapper(*args, **kwargs):try:return func(*args, **kwargs)2 unmodified linesreturn Nonereturn wrapper################################################################# 1) Convert Raw Results into a Consistent Format #################################################################@safe_processdef parse_wbg_results(raw_output):"""Example: raw_output might be something like:[{ 'Innovation and Entrepreneurship': 0.32,'Digital Development': 0.27,...}]or it might be [ [ {...}, {...} ] ]Adjust logic so we end up with a list of dicts:[{'label': 'Innovation and Entrepreneurship', 'score_mean': 0.32, 'score_std': 0.0},{'label': 'Digital Development', 'score_mean': 0.27, 'score_std': 0.0},...]"""if not raw_output:return []# If the library returns a list with a single dictionary:# raw_output[0] might be a dict of {topic: score}# or it might be a list of dicts with 'label'/'score_mean' keysfirst_item = raw_output[0]# If it's already a list of dicts with 'label', 'score_mean', etc.if isinstance(first_item, dict) and 'label' in first_item:# Possibly we already have the correct formatreturn raw_output# If it's a dict of {topic_label: numeric_score}if isinstance(first_item, dict):# Then let's convert itparsed_list = []for label, val in first_item.items():parsed_list.append({'label': label,'score_mean': float(val),'score_std': 0.0 # If no std is given, default 0})return parsed_list# If it’s something else, handle itreturn []################################################################# 2) Section-based Analysis #################################################################@safe_processdef analyze_text_sections(text):"""Splits text into sections, calls clf.suggest_topics on each,and returns a list-of-lists:section_topics = [[ {'label':'...', 'score_mean':...}, {...} ],[ {'label':'...', 'score_mean':...}, {...} ],...]"""sentences = sent_tokenize(text)# e.g. group 3 sentences per sectionsections = [' '.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################################################################# 3) Basic Summaries (Correlation, Sentiment, Clusters etc.) #################################################################@safe_processdef calculate_topic_correlations(topic_dicts):"""If we only want a single dimension correlation (like score_mean),we can do a simple correlation across different topics.But typically you'd want multiple texts or some multi-dimensional approach."""if len(topic_dicts) < 2:# Not enough to do correlationreturn np.array([[1.0]]), ["Insufficient topics"]labels = [d['label'] for d in topic_dicts]scores = [d['score_mean'] for d in topic_dicts] # single dimensionif len(scores) < 2:return np.array([[1.0]]), ["Insufficient topics"]corr_matrix = np.corrcoef(scores)return corr_matrix, labels@safe_processdef perform_sentiment_analysis(text):sia = SentimentIntensityAnalyzer()sents = sent_tokenize(text)results = [sia.polarity_scores(s) for s in sents]return pd.DataFrame(results)@safe_processdef create_topic_clusters(topic_dicts):if len(topic_dicts) < 3:return [0]*len(topic_dicts) # trivial cluster# Must have 'score_mean' and 'score_std' or something elseX = []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 to JSON-encode################################################################# 4) Charts (Bar, Radar, Correlation Heatmap, etc.) #################################################################@safe_processdef create_main_charts(topic_dicts):"""Expects a list of dicts with keys: 'label', 'score_mean', ...We'll just use 'score_mean' (or a scaled version)."""if not topic_dicts:return go.Figure(), go.Figure()# Bar chartlabels = [t['label'] for t in topic_dicts]scores = [t['score_mean']*100 for t in topic_dicts] # convert to %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 chartradar_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)),1 unmodified line)return bar_fig, radar_fig@safe_processdef create_correlation_heatmap(corr_matrix, labels):if corr_matrix.ndim == 0:# It's a scalar => shape ()corr_matrix = np.array([[corr_matrix]])if corr_matrix.shape == (1,1):# Usually means not enough datafig = go.Figure()fig.add_annotation(text="Not enough topics for correlation", showarrow=False)return figfig = go.Figure(data=go.Heatmap(z=corr_matrix,x=labels,1 unmodified linecolorscale='Viridis'))fig.update_layout(title='주제 간 상관관계',height=500,template='plotly_white')return fig@safe_processdef create_topic_evolution(section_topics):"""section_topics: list of [ {label:..., score_mean:...}, ...]one element per section"""fig = go.Figure()if not section_topics or len(section_topics) == 0:return fig# Take the first section’s list as referenceif not section_topics[0]:return fig# For each topic in the first section, gather its evolutionfor topic_dict in section_topics[0]:label = topic_dict['label']score_list = []for sec_list in section_topics:# find matching labelmatch = 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_processdef create_confidence_gauge(topic_dicts):"""If your data doesn’t actually have a separate confidence measure,you may skip or adapt. For example, you might define confidence= (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):confidence_val = 100.0*(1.0 - t.get('score_std', 0.0)) # an examplefig.add_trace(go.Indicator(mode="gauge+number",value=confidence_val,title={'text': t['label']},domain={'row': 0, 'column': i}))fig.update_layout(grid={'rows': 1, 'columns': num_topics},height=400,1 unmodified line)return fig################################################################# 5) Putting Everything into `process_all_analysis` #################################################################@spaces.GPU()def process_all_analysis(text):try:# 1) Suggest topics on the entire textraw_results = clf.suggest_topics(text)all_topics = parse_wbg_results(raw_results) # keep full list of dicts# 2) Top 5 (if you want to highlight them)# Sort by score_mean descendingsorted_topics = sorted(all_topics, key=lambda x: x['score_mean'], reverse=True)top_topics = sorted_topics[:5]# 3) Section-basedsection_topics = analyze_text_sections(text) # list of lists# 4) Extra analysescorr_matrix, corr_labels = calculate_topic_correlations(all_topics)sentiments_df = perform_sentiment_analysis(text)clusters = create_topic_clusters(all_topics)# 5) Build chartsbar_chart, radar_chart = create_main_charts(top_topics) # show top 5 on barheatmap = create_correlation_heatmap(corr_matrix, corr_labels)evolution_chart = create_topic_evolution(section_topics)gauge_chart = create_confidence_gauge(top_topics)# 6) Prepare output for the JSON field# Make sure everything is JSON-serializable with string keysresults = {"top_topics": top_topics, # list of dict"clusters": clusters, # list of ints"sentiments": sentiments_df.to_dict(orient="records"),}return (results, # JSON outputbar_chart, # plot11 unmodified lineheatmap, # plot3evolution_chart,# plot4gauge_chart, # plot5go.Figure() # plot6 (placeholder for sentiment plot, or skip))except Exception as e:print(f"Analysis error: {str(e)}")empty_fig = go.Figure()7 unmodified linesempty_fig)################################################################# 6) Gradio UI #################################################################with gr.Blocks(title="고급 문서 주제 분석기") as demo: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="주제 분포")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="상세 분석 결과")submit_btn.click(fn=process_all_analysis,inputs=[text_input],5 unmodified linesdemo.launch(server_name="0.0.0.0",server_port=7860,share=False,debug=True)11 unmodified lines121314151617181920212223242526272829303132333435363738394041422 unmodified lines454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881 unmodified line1901911921931941951961971981992002012022032042052062072082092102111 unmodified line2132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862871 unmodified line2892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303311 unmodified line3333343353363373383393403417 unmodified lines3493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903915 unmodified lines39739839940040140211 unmodified linesfrom sklearn.cluster import KMeansimport torch# Set GPU if availabledevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')# Initialize WBGDocTopicclf = wbgtopic.WBGDocTopic(device=device)# Download NLTK data if neededtry:nltk.download('punkt', quiet=True)nltk.download('vader_lexicon', quiet=True)except Exception as e:print(f"NLTK data download error: {e}")# Sample text for demonstrationSAMPLE_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):"""A decorator that catches and logs exceptions inside a function,returning None if an error occurs. This helps ensure thatthe Gradio interface does not crash from unexpected exceptions."""def wrapper(*args, **kwargs):try:return func(*args, **kwargs)2 unmodified linesreturn Nonereturn wrapper@safe_processdef parse_wbg_results(raw_output):"""Convert the raw output from WBGDocTopic into a list of dictionaries with'label', 'score_mean', and 'score_std'. Adjust logic according to theactual structure of raw_output."""if not raw_output:return []# Example logic: If raw_output is something like:# [ { "Innovation and Entrepreneurship": 0.74, "Digital Development": 0.65, ... } ]# We'll parse it accordingly.first_item = raw_output[0]# If the first item is already a dict with a 'label' key, it might already be in the right formatif isinstance(first_item, dict) and "label" in first_item:return raw_output# If it's a dict containing topic -> scoreif isinstance(first_item, dict):parsed_list = []for label, val in first_item.items():parsed_list.append({"label": label,"score_mean": float(val),"score_std": 0.0 # If std is not provided, default to 0})return parsed_listreturn []@safe_processdef analyze_text_sections(text):"""Splits the text into sections and calls clf.suggest_topics for each section.Returns a list of topic lists, where each element is the parsed WBG resultfor that section."""sentences = sent_tokenize(text)# Example: group every 3 sentences into one sectionsections = [' '.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_processdef calculate_topic_correlations(topic_dicts):"""Calculates correlation between topics based on 'score_mean'.This is usually a single-dimensional correlation across different topics,which can be conceptually limited, but shown here as an example.Returns (corr_matrix, labels)."""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_processdef perform_sentiment_analysis(text):"""Uses NLTK's VADER sentiment analyzer to produce sentiment scores(neg, neu, pos, compound) for each sentence in the text.Returns a pandas DataFrame of results."""sia = SentimentIntensityAnalyzer()sents = sent_tokenize(text)results = [sia.polarity_scores(s) for s in sents]return pd.DataFrame(results)@safe_processdef create_topic_clusters(topic_dicts):"""Applies a KMeans clustering on (score_mean, score_std).If there are fewer than 3 topics, returns trivial cluster assignments."""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_processdef create_main_charts(topic_dicts):"""Creates a bar chart and a radar chart for the given list of topics.Uses 'score_mean' as the base score."""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] # scale to %# Bar chartbar_fig = go.Figure(data=[go.Bar(x=labels, y=scores, marker_color='rgb(55, 83, 109)')])bar_fig.update_layout(title='Topic Analysis Results',xaxis_title='Topics',yaxis_title='Relevance (%)',template='plotly_white',height=500,)# Radar chartradar_fig = go.Figure()radar_fig.add_trace(go.Scatterpolar(r=scores,theta=labels,fill='toself',name='Topic Distribution'))radar_fig.update_layout(title='Topic Radar Chart',template='plotly_white',height=500,polar=dict(radialaxis=dict(visible=True)),1 unmodified line)return bar_fig, radar_fig@safe_processdef create_correlation_heatmap(corr_matrix, labels):"""Creates a heatmap figure of the provided correlation matrix.If there's insufficient data, shows a placeholder message."""if corr_matrix.ndim == 0:# It's a scalar => shape ()corr_matrix = np.array([[corr_matrix]])if corr_matrix.shape == (1, 1):# Not enough data for correlationfig = go.Figure()fig.add_annotation(text="Not enough topics for correlation", showarrow=False)return figfig = go.Figure(data=go.Heatmap(z=corr_matrix,x=labels,1 unmodified linecolorscale='Viridis'))fig.update_layout(title='Topic Correlation Heatmap',height=500,template='plotly_white')return fig@safe_processdef create_topic_evolution(section_topics):"""Plots topic evolution across sections.section_topics: list of lists, where each inner listis a list of dicts [{'label':..., 'score_mean':...}, ...]"""fig = go.Figure()if not section_topics or len(section_topics) == 0:return figif not section_topics[0]:return fig# For each topic in the first section, track the score across all sectionsfor 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='Topic Evolution Across Sections',xaxis_title='Section',yaxis_title='Score Mean',height=500,template='plotly_white')return fig@safe_processdef create_confidence_gauge(topic_dicts):"""Creates individual gauge indicators for each topic's confidence.A simple heuristic: confidence = (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):# If score_std not present, default to 0 => confidence = 100%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,1 unmodified line)return fig@spaces.GPU()def process_all_analysis(text):"""Main function that calls all analysis steps and returnsstructured JSON plus various Plotly figures."""try:# 1) Suggest topics for the entire textraw_results = clf.suggest_topics(text)all_topics = parse_wbg_results(raw_results)# 2) Sort by 'score_mean' descending to get top 5sorted_topics = sorted(all_topics, key=lambda x: x['score_mean'], reverse=True)top_topics = sorted_topics[:5]# 3) Analyze by sectionssection_topics = analyze_text_sections(text)# 4) Extra analysescorr_matrix, corr_labels = calculate_topic_correlations(all_topics)sentiments_df = perform_sentiment_analysis(text)clusters = create_topic_clusters(all_topics)# 5) Build chartsbar_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) Prepare JSON output (ensure valid JSON with string keys)results = {"top_topics": top_topics, # list of dict"clusters": clusters, # list of ints"sentiments": sentiments_df.to_dict(orient="records")}# Return JSON + Figuresreturn (results, # JSON outputbar_chart, # plot11 unmodified lineheatmap, # plot3evolution_chart,# plot4gauge_chart, # plot5go.Figure() # plot6 (placeholder for sentiment plot, if desired))except Exception as e:print(f"Analysis error: {str(e)}")empty_fig = go.Figure()7 unmodified linesempty_fig)####################################################### Gradio UI Definition #######################################################with gr.Blocks(title="Advanced Document Topic Analyzer") as demo:gr.Markdown("## 📝 Advanced Document Topic Analyzer")gr.Markdown("Enter text, then click 'Start Analysis' to see topic analysis, correlation, ""confidence gauges, sentiment, and more.")with gr.Row():text_input = gr.Textbox(value=SAMPLE_TEXT,label="Text to Analyze",lines=8)with gr.Row():submit_btn = gr.Button("Start Analysis", variant="primary")with gr.Tabs():with gr.TabItem("Main Analysis"):with gr.Row():plot1 = gr.Plot(label="Topic Distribution")plot2 = gr.Plot(label="Radar Chart")with gr.TabItem("Detailed Analysis"):with gr.Row():plot3 = gr.Plot(label="Correlation Heatmap")plot4 = gr.Plot(label="Topic Evolution")with gr.TabItem("Confidence Analysis"):plot5 = gr.Plot(label="Confidence Gauge")with gr.TabItem("Sentiment Analysis"):plot6 = gr.Plot(label="Sentiment Results")with gr.Row():output_json = gr.JSON(label="Detailed Analysis Output")submit_btn.click(fn=process_all_analysis,inputs=[text_input],5 unmodified linesdemo.launch(server_name="0.0.0.0",server_port=7860,share=False, # Set True if you want a public share linkdebug=True)
app.py+148-168