Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234347895675 unmodified lines1314152122232416171821 unmodified lines404142525354555657585960616263646566676843444546474849505152535413 unmodified lines68697093949596979899100101102103104105106107108717273112747576775 unmodified lines838485124125868788899091929394959697103 unmodified lines2012022032352042052062382392072082092412102112122135 unmodified lines2192202212532542552562572582592602612622632642652662672682692702222232242252262272282292722302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712762722732742792752812822832842852862762772882892902912782792802812822832932942842852862962972982993003013023033042872882893063073082902912922933103113122942952962972982993003013023033043053063073083093103113123133173143153163173183193203213243223233243253263273283293323333303313323333347 unmodified lines34234334434734834534634734834935035235135235335435535635835935735835936036136236336436636536636736819 unmodified lines3883893903913923933945 unmodified lines40040140240340440540640740840941041141241341440340440540620 unmodified lines4274284294414424434304314324334344354364374384394404454464414424434444454464474484494508 unmodified lines4594604614614624634644654664674684694704624634644654664724734674684694704714724734744754764774784754764774784794804814794804814834844854864874884894904914924934944954964974984995005015024824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225095105115125135145155165175185195205215225235245255265275235245255315325265275285295305 unmodified lines53653753853954054154254354454554623 unmodified lines5705715725735745755765775785795805815825835845855735745752 unmodified lines57857958059459559659759859960058158258310 unmodified lines5945955965975985996006016026036046056066076088 unmodified lines6176186196206216226236246256266276286316296306316326356366336346356366376386396416406416426438 unmodified lines6526536546566576586596606616626636646656666676556566576586596606616626636645 unmodified lines6706716726796806816826836846856866876886896906736746756766776786796806816825 unmodified lines6886896907027037047057067077087097107117127136916926936946956966976986997007177187197017027037047057067227077087097257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707107727737117127137147157167787797177187197207217227847857237247257267277 unmodified lines7357367377387397407419 unmodified lines751752753814815816817818819820821822823824825826827828829830831832754755756757758759760import gradio as grfrom gradio import SelectDataimport torchfrom transformers import AutoTokenizer, AutoModelForSequenceClassificationimport pandas as pdfrom wordcloud import WordCloudfrom PIL import Imageimport numpy as npimport plotly.express as pximport plotly.graph_objects as gofrom sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.decomposition import LatentDirichletAllocation as LDA5 unmodified linesfrom collections import Counterfrom nltk.util import ngramsfrom googletrans import Translatorimport asyncioimport requestsfrom typing import List, Dictimport os
# 下载停用词nltk.download('stopwords', quiet=True)21 unmodified lines 'ja': 'japanese'}
# 设置线程数以充分利用多核CPUtorch.set_num_threads(os.cpu_count()) # 使用所有可用的CPU核心
# 初始化模型和分词器MODEL = "clapAI/modernBERT-base-multilingual-sentiment"tokenizer = AutoTokenizer.from_pretrained(MODEL)model = AutoModelForSequenceClassification.from_pretrained(MODEL)model.eval()
# 从模型配置中获取标签映射id2label = model.config.id2labellabel2sentiment = { "positive": "积极", "negative": "消极", "neutral": "中性" # 如果模型支持中性的话}
# 全局变量current_bigram_samples = []FULL_BIGRAM_DF = pd.DataFrame() # 存储完整的bigram数据last_selected_reviews = [] # 存放最后一次选中的评论列表translator = Translator() # 初始化翻译器results_df = None # 存储完整的分析结果positive_df = None # 存储积极评论negative_df = None # 存储消极评论neutral_df = None # 存储中性评论
def get_stopwords(text): """根据文本语言返回相应的停用词"""13 unmodified lines mask = FULL_BIGRAM_DF["词组"].str.contains(search_text, case=False, na=False) return FULL_BIGRAM_DF[mask]
def analyze_text(text): """分析单个文本的情感""" inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=8192) with torch.inference_mode(): outputs = model(**inputs) prediction = outputs.logits.argmax(dim=-1).item() predicted_label = id2label[prediction] sentiment = label2sentiment.get(predicted_label, predicted_label) return { "文本": text, "整体情感": sentiment }
def preprocess_text(text): """预处理文本""" # 转换为小写 text = text.lower() text = str(text).lower() # 去除特殊字符,只保留字母和空格 text = re.sub(r'[^a-z\s]', ' ', text)5 unmodified lines
def extract_bigrams(texts, min_freq=2, max_freq_ratio=0.9): """提取关键词组(两个单词)""" # 预处理所有文本 processed_texts = [preprocess_text(text) for text in texts] # 预处理所有文本,只处理原文部分 processed_texts = [] original_texts = [] for text in texts: # 分离原文和翻译 parts = text.split("\n\n翻译:") original_text = parts[0] # 只取原文部分 original_texts.append(original_text) processed_texts.append(preprocess_text(original_text)) # 提取所有双词组及其对应的文本 all_bigrams = []103 unmodified lines empty_docs = pd.DataFrame(columns=["文本", "主导主题", "主题概率"]) return empty_topics, empty_docs
def create_pie_chart(positive_count, negative_count):def create_pie_chart(positive_count, negative_count, neutral_count): """创建情感分布饼图""" fig = go.Figure(data=[go.Pie( labels=['积极评价', '消极评价'], values=[positive_count, negative_count], labels=['积极评价', '中性评价', '消极评价'], values=[positive_count, neutral_count, negative_count], hole=.3, marker_colors=['#2ecc71', '#e74c3c'] marker_colors=['#2ecc71', '#f1c40f', '#e74c3c'] )]) fig.update_layout(5 unmodified lines return fig
def analyze_texts_batch(texts, batch_size=32): """批量分析文本的情感""" results = [] for i in range(0, len(texts), batch_size): batch_texts = texts[i:i + batch_size] inputs = tokenizer(batch_texts, return_tensors="pt", truncation=True, max_length=8192, padding=True) with torch.inference_mode(): outputs = model(**inputs) predictions = outputs.logits.argmax(dim=-1) for text, pred in zip(batch_texts, predictions): predicted_label = id2label[pred.item()] sentiment = label2sentiment.get(predicted_label, predicted_label) results.append({ "文本": text, "整体情感": sentiment })def create_time_series_chart(df): """创建评论时间序列折线图""" # 按时间和情感类别统计评论数 time_sentiment_counts = df.groupby(['评论时间', '整体情感']).size().unstack(fill_value=0) # 创建折线图 fig = go.Figure() return results # 添加积极评论折线 fig.add_trace(go.Scatter( x=time_sentiment_counts.index, y=time_sentiment_counts['积极'], name='积极评论', line=dict(color='#2ecc71', width=2), mode='lines+markers' )) # 添加中性评论折线 fig.add_trace(go.Scatter( x=time_sentiment_counts.index, y=time_sentiment_counts['中性'], name='中性评论', line=dict(color='#f1c40f', width=2), mode='lines+markers' )) # 添加消极评论折线 fig.add_trace(go.Scatter( x=time_sentiment_counts.index, y=time_sentiment_counts['消极'], name='消极评论', line=dict(color='#e74c3c', width=2), mode='lines+markers' )) # 更新布局 fig.update_layout( title='评论数量时间趋势', xaxis_title='评论时间', yaxis_title='评论数量', hovermode='x unified', width=800, height=400, showlegend=True ) return fig
def analyze_file(file, progress=gr.Progress()): """分析文件中的多个文本""" global current_bigram_samples, FULL_BIGRAM_DF global current_bigram_samples, FULL_BIGRAM_DF, results_df, positive_df, negative_df, neutral_df try: # 读取文件内容 if file is None: return "请上传文件", None, None, None, None, None, None, None, None, None, None, "" # 读取上传的文件内容 text_content = file.name with open(text_content, 'r', encoding='utf-8') as f: content = f.readlines() return "请上传文件", None, None, None, None, None, None, None, None, None, None, None, "" progress(0, desc="正在预处理文本...") # 处理每一行评论 texts = [line.strip() for line in content if line.strip()] # 预处理所有文本 total_lines = len(texts) progress(0, desc="正在读取Excel文件...") # 读取Excel文件 excel_file = pd.ExcelFile(file.name) # 获取包含评论数量的sheet名 sheet_name = [name for name in excel_file.sheet_names if "Review" in name][0] if total_lines == 0: return "没有找到有效的评论文本", None, None, None, None, None, None, None, None, None, None, "" # 读取数据 df = pd.read_excel(file.name, sheet_name=sheet_name) # 检测语言 all_text = ' '.join(texts) try: lang_code = detect(all_text) detected_lang = LANG_CODE_MAP.get(lang_code, 'english') lang_info = f"检测到语言:{detected_lang},将使用对应的停用词列表" except: detected_lang = 'english' lang_info = "语言检测失败,将使用英语停用词列表" # 提取所需列并重命名 df = df[["内容", "内容(翻译)", "星级", "评论时间"]] progress(0.1, desc="正在进行情感分析...") # 批量处理文本 results = analyze_texts_batch(texts) # 合并原文和翻译 df["内容"] = df.apply(lambda x: f'{x["内容"]}\n\n翻译:{x["内容(翻译)"]}', axis=1) df = df.drop(columns=["内容(翻译)"]) # 删除翻译列 progress(0.3, desc="正在处理结果...") # 创建DataFrame df = pd.DataFrame(results) # 处理评论时间格式 df["评论时间"] = pd.to_datetime(df["评论时间"]).dt.strftime("%Y-%m-%d") # 根据星级判断情感(1-2星消极,3星中性,4-5星积极) df["整体情感"] = df["星级"].apply(lambda x: "积极" if x >= 4 else ("中性" if x == 3 else "消极")) # 保存完整结果到全局变量 results_df = df.copy() # 分别保存各情感类别的数据(只保留需要显示的列) display_columns = ["内容", "整体情感", "评论时间"] positive_df = df[df["整体情感"] == "积极"][display_columns].copy() negative_df = df[df["整体情感"] == "消极"][display_columns].copy() neutral_df = df[df["整体情感"] == "中性"][display_columns].copy()
progress(0.3, desc="正在处理结果...") # 生成统计信息 total = len(df) if total == 0: return "没有找到有效的评论文本", None, None, None, None, None, None, None, None, None, None, "" return "没有找到有效的评论文本", None, None, None, None, None, None, None, None, None, None, None, "" positive = len(df[df["整体情感"] == "积极"]) negative = len(df[df["整体情感"] == "消极"]) neutral = len(df[df["整体情感"] == "中性"]) # 生成分析统计信息 analysis_info = ( f"{lang_info}\n" f"分析完成!共分析{total}条文本\n" f"积极:{positive}条 ({positive/total*100:.1f}%)\n" f"中性:{neutral}条 ({neutral/total*100:.1f}%)\n" f"消极:{negative}条 ({negative/total*100:.1f}%)" ) progress(0.4, desc="正在生成词云...") # 生成词云 positive_text = " ".join(df[df["整体情感"] == "积极"]["文本"]) negative_text = " ".join(df[df["整体情感"] == "消极"]["文本"]) positive_text = " ".join(df[df["整体情感"] == "积极"]["内容"].astype(str)) negative_text = " ".join(df[df["整体情感"] == "消极"]["内容"].astype(str)) pos_wordcloud = None neg_wordcloud = None7 unmodified lines neg_wordcloud = neg_wordcloud.to_image() progress(0.5, desc="正在生成可视化图表...") # 创建饼图 pie_chart = create_pie_chart(positive, negative) # 创建饼图和时间序列图 pie_chart = create_pie_chart(positive, negative, neutral) time_series = create_time_series_chart(df) progress(0.6, desc="正在提取关键词组...") # 提取关键词组 bigrams_df, bigram_samples = extract_bigrams(texts) bigrams_df, bigram_samples = extract_bigrams(df["内容"].tolist()) current_bigram_samples = bigram_samples # 更新全局变量 FULL_BIGRAM_DF = bigrams_df.copy() # 保存完整的bigram数据 progress(0.7, desc="正在进行主题分析...") # 分别对积极和消极评论进行LDA分析 positive_texts = df[df["整体情感"] == "积极"]["文本"].tolist() negative_texts = df[df["整体情感"] == "消极"]["文本"].tolist() positive_texts = df[df["整体情感"] == "积极"]["内容"].tolist() negative_texts = df[df["整体情感"] == "消极"]["内容"].tolist() pos_topics_df, pos_doc_topics_df = perform_lda_analysis(positive_texts, "积极") neg_topics_df, neg_doc_topics_df = perform_lda_analysis(negative_texts, "消极") progress(0.9, desc="正在保存结果...") # 准备显示用的DataFrame display_df = df.copy() display_df = df[["内容", "整体情感", "评论时间"]].copy() # 保存结果到Excel文件,包含多个sheet excel_path = "sentiment_analysis_results.xlsx"19 unmodified lines neg_wordcloud, display_df, pie_chart, time_series, # 添加时间序列图 pos_topics_df, pos_doc_topics_df, neg_topics_df,5 unmodified lines except Exception as e: import traceback error_msg = f"处理文件时出错:{str(e)}\n{traceback.format_exc()}" return error_msg, None, None, None, None, None, None, None, None, None, None, ""
def single_text_interface(text): """单文本分析界面的处理函数""" if not text.strip(): return "请输入要分析的文本" result = analyze_text(text) return ( f"文本:{result['文本']}\n" f"整体情感:{result['整体情感']}" ) return error_msg, None, None, None, None, None, None, None, None, None, None, None, ""
def highlight_keyword(text, keyword): """用 <mark> 给 keyword 做简单的大小写不敏感高亮"""20 unmodified lines # 提取评论内容(去除序号前缀) review_content = review.split(". ", 1)[1] if ". " in review else review # 高亮关键词 highlighted_review = highlight_keyword(review_content, selected_bigram) # 添加序号和样式 # 分离原文和译文 parts = review_content.split("\n\n翻译:") original_text = parts[0] translation = parts[-1] if len(parts) > 1 else "" # 高亮关键词(只在原文中高亮) highlighted_original = highlight_keyword(original_text, selected_bigram) # 添加序号和样式,使用不同的背景色区分原文和译文 highlighted_reviews.append( f'<div style="margin-bottom: 10px; padding: 10px; background-color: #f5f5f5; border-radius: 5px;">' f'<span style="font-weight: bold; color: #666;">#{i}</span> {highlighted_review}' f'<div style="margin-bottom: 15px;">' f'<div style="padding: 10px; background-color: #f5f5f5; border-radius: 5px 5px 0 0;">' f'<span style="font-weight: bold; color: #666;">#{i}</span> {highlighted_original}' f'</div>' f'<div style="padding: 10px; background-color: #e8f4f8; border-radius: 0 0 5px 5px;">' f'{translation}' f'</div>' f'</div>' ) 8 unmodified lines return '<div style="color: #666; padding: 10px;">未找到相关评论</div>'
def translate_single_comment(comment_index): """翻译单条评论""" global last_selected_reviews if not last_selected_reviews: return "请先选择一个词组查看相关评论。" try: comment_index = int(comment_index) except: return "请输入有效的评论序号(数字)"def filter_comments(search_text, df): """过滤评论""" if df is None or len(df) == 0: return df if comment_index < 1 or comment_index > len(last_selected_reviews): return f"评论序号超出范围!可选范围: 1~{len(last_selected_reviews)}" # 当搜索框为空时,返回原始数据 if not search_text.strip(): return df # 不区分大小写的搜索 mask = df["内容"].str.contains(search_text, case=False, na=False) return df[mask].reset_index(drop=True)
def update_sentiment_results(df): """更新各情感类别的结果""" global positive_df, negative_df, neutral_df # 获取原文并去除序号前缀 original_text = last_selected_reviews[comment_index - 1] parts = original_text.split(". ", 1) if len(parts) == 2: original_text = parts[1] else: original_text = parts[0] if df is None or len(df) == 0: return None, None, None, None, None, None try: # 创建异步事件循环 loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) async def translate_async(): async with Translator() as translator: result = await translator.translate(original_text, dest='zh-cn') return result # 运行异步翻译 result = loop.run_until_complete(translate_async()) loop.close() return f"原文:\n{original_text}\n\n中文翻译:\n{result.text}" except Exception as e: # 如果是网络错误,提示用户 if "HTTPSConnectionPool" in str(e): return "网络连接错误,请检查网络连接并重试" return f"翻译出错: {str(e)}" # 更新全局变量 positive_df = df[df["整体情感"] == "积极"].reset_index(drop=True) negative_df = df[df["整体情感"] == "消极"].reset_index(drop=True) neutral_df = df[df["整体情感"] == "中性"].reset_index(drop=True) # 返回原始数据和显示数据的副本 return ( positive_df.copy(), # original_positive_df negative_df.copy(), # original_negative_df neutral_df.copy(), # original_neutral_df positive_df.copy(), # positive_results_df negative_df.copy(), # negative_results_df neutral_df.copy() # neutral_results_df )
def generate_lda_prompt(topics_df: pd.DataFrame) -> str: """生成LDA分析的prompt""" # 将DataFrame转换为文本格式 topics_text = [] for _, row in topics_df.iterrows(): topics_text.append(f"主题 {row['主题']}:{row['关键词']}") lda_results = "\n".join(topics_text) # 从第一个主题的名称中判断是积极还是消极评论 sentiment_type = "积极" if "积极" in topics_df.iloc[0]["主题"] else "消极" prompt = ( f"我对一组产品{sentiment_type}评论进行了 LDA(潜在德里希特分配)分析,得到了以下主题。" f"每个主题都由其最重要的单词列表表示。请分析这些主题,找出并概括客户对产品的主要{sentiment_type}意见或问题\n" f"############\n" f"{lda_results}" ) return prompt
# 创建Gradio界面with gr.Blocks(title="亚马逊评论文本情感分析系统", theme=gr.themes.Soft()) as demo: gr.Markdown("# 亚马逊评论文本情感分析系统") with gr.Tabs(): with gr.TabItem("单文本分析"): with gr.Row(): with gr.Column(): text_input = gr.Textbox( label="输入文本", lines=3, placeholder="请输入要分析的文本...", value="" ) analyze_btn = gr.Button("分析", variant="primary") with gr.Column(): text_output = gr.Textbox(label="分析结果", lines=3) analyze_btn.click( single_text_interface, inputs=[text_input], outputs=[text_output] ) with gr.TabItem("批量文件分析"): with gr.Row(): file_input = gr.File( label="上传文本文件(UTF-8编码的txt文件,每行一条评论)", file_types=[".txt"] label="上传Excel文件(包含评论数据的xlsx文件)", file_types=[".xlsx"] ) analyze_file_btn = gr.Button("开始分析", variant="primary")5 unmodified lines with gr.Column(): gr.Markdown("### 评论情感分布") pie_chart = gr.Plot() with gr.Column(): gr.Markdown("### 评论时间趋势") time_series = gr.Plot() with gr.Row(): with gr.Column(): gr.Markdown("### 词云预览") pos_wordcloud = gr.Image(label="积极评论词云")23 unmodified lines with gr.Column(scale=1): gr.Markdown("#### 选中词组的相关评论") bigram_reviews = gr.HTML() # 添加翻译功能组件 with gr.Row(): comment_index = gr.Number( label="要翻译的评论序号", value=1, precision=0 ) translate_btn = gr.Button("翻译") translate_output = gr.Textbox( label="翻译结果", lines=6 ) # 添加词组选择事件 bigrams_df.select(2 unmodified lines outputs=bigram_reviews ) # 添加翻译按钮事件 translate_btn.click( fn=translate_single_comment, inputs=[comment_index], outputs=[translate_output] ) gr.Markdown("### 主题分析结果") with gr.Row(): with gr.Column():10 unmodified lines wrap=True, label="积极评论主题分布" ) gr.Markdown("#### 积极评论主题分析Prompt") pos_prompt_output = gr.Textbox( label="分析Prompt", lines=8, max_lines=15, interactive=False, container=True, show_copy_button=True ) with gr.Column(): gr.Markdown("#### 消极评论主题分析") neg_topics_df = gr.Dataframe(8 unmodified lines wrap=True, label="消极评论主题分布" ) gr.Markdown("#### 消极评论主题分析Prompt") neg_prompt_output = gr.Textbox( label="分析Prompt", lines=8, max_lines=15, interactive=False, container=True, show_copy_button=True )
gr.Markdown("### 详细分析结果") # 添加一个隐藏的DataFrame用于存储完整结果 results_df = gr.Dataframe( headers=["文本", "整体情感"], datatype=["str", "str"], headers=["内容", "整体情感", "评论时间"], datatype=["str", "str", "str"], wrap=True, line_breaks=True, visible=False # 设置为隐藏 ) # 添加隐藏的DataFrame用于存储各类别的原始数据 # 添加隐藏的DataFrame用于存储原始数据 original_positive_df = gr.Dataframe(visible=False) original_negative_df = gr.Dataframe(visible=False) original_neutral_df = gr.Dataframe(visible=False)8 unmodified lines show_label=True ) with gr.Row(): with gr.Column(scale=2): positive_results_df = gr.Dataframe( headers=["文本", "整体情感"], datatype=["str", "str"], wrap=True, interactive=True ) with gr.Column(scale=1): pos_translate_output = gr.Markdown( label="翻译结果", value="点击左侧评论查看翻译" ) positive_results_df = gr.Dataframe( headers=["内容", "整体情感", "评论时间"], datatype=["str", "str", "str"], wrap=True, line_breaks=True, interactive=True ) # 消极评论 with gr.Row():5 unmodified lines show_label=True ) with gr.Row(): with gr.Column(scale=2): negative_results_df = gr.Dataframe( headers=["文本", "整体情感"], datatype=["str", "str"], wrap=True, interactive=True ) with gr.Column(scale=1): neg_translate_output = gr.Markdown( label="翻译结果", value="点击左侧评论查看翻译" ) negative_results_df = gr.Dataframe( headers=["内容", "整体情感", "评论时间"], datatype=["str", "str", "str"], wrap=True, line_breaks=True, interactive=True ) # 中性评论 with gr.Row():5 unmodified lines show_label=True ) with gr.Row(): with gr.Column(scale=2): neutral_results_df = gr.Dataframe( headers=["文本", "整体情感"], datatype=["str", "str"], wrap=True, interactive=True ) with gr.Column(scale=1): neu_translate_output = gr.Markdown( label="翻译结果", value="点击左侧评论查看翻译" ) neutral_results_df = gr.Dataframe( headers=["内容", "整体情感", "评论时间"], datatype=["str", "str", "str"], wrap=True, line_breaks=True, interactive=True ) file_download = gr.File(label="下载完整分析结果(Excel)")
def filter_comments(search_text, df, original_df): """过滤评论""" if not search_text.strip() or df is None: def filter_comments_with_original(search_text, current_df, original_df): """带有原始数据的评论过滤函数""" if not search_text.strip(): return original_df # 不区分大小写的搜索 mask = original_df["文本"].str.contains(search_text, case=False, na=False) mask = original_df["内容"].str.contains(search_text, case=False, na=False) return original_df[mask].reset_index(drop=True)
def translate_selected_text(evt: gr.SelectData, df): """翻译选中的评论文本""" try: # 获取选中行的文本 selected_text = df.iloc[evt.index[0]]["文本"] # 创建异步事件循环 loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) async def translate_async(): async with Translator() as translator: result = await translator.translate(selected_text, dest='zh-cn') return result # 运行异步翻译 result = loop.run_until_complete(translate_async()) loop.close() # 返回格式化的HTML return f""" <div style='background-color: #f5f5f5; padding: 10px; border-radius: 5px; margin-bottom: 10px;'> <div style='font-weight: bold; color: #666; margin-bottom: 5px;'>原文:</div> <div style='margin-bottom: 10px;'>{selected_text}</div> <div style='font-weight: bold; color: #666; margin-bottom: 5px;'>中文翻译:</div> <div>{result.text}</div> </div> """ except Exception as e: if "HTTPSConnectionPool" in str(e): return "<div style='color: red;'>网络连接错误,请检查网络连接并重试</div>" return f"<div style='color: red;'>翻译出错: {str(e)}</div>"
def update_sentiment_results(df): """更新各情感类别的结果""" if df is None or len(df) == 0: return None, None, None, None, None, None positive_df = df[df["整体情感"] == "积极"].reset_index(drop=True) negative_df = df[df["整体情感"] == "消极"].reset_index(drop=True) neutral_df = df[df["整体情感"] == "中性"].reset_index(drop=True) # 返回原始数据和显示数据 return (positive_df.copy(), negative_df.copy(), neutral_df.copy(), positive_df.copy(), negative_df.copy(), neutral_df.copy()) # 添加搜索事件处理 pos_search.change( fn=filter_comments, pos_search.input( fn=filter_comments_with_original, inputs=[pos_search, positive_results_df, original_positive_df], outputs=[positive_results_df] ) neg_search.change( fn=filter_comments, neg_search.input( fn=filter_comments_with_original, inputs=[neg_search, negative_results_df, original_negative_df], outputs=[negative_results_df] ) neu_search.change( fn=filter_comments, neu_search.input( fn=filter_comments_with_original, inputs=[neu_search, neutral_results_df, original_neutral_df], outputs=[neutral_results_df] )7 unmodified lines neg_wordcloud, results_df, pie_chart, time_series, pos_topics_df, pos_doc_topics_df, neg_topics_df,9 unmodified lines original_positive_df, original_negative_df, original_neutral_df, positive_results_df, negative_results_df, neutral_results_df ] ) # 添加点击事件处理 positive_results_df.select( fn=translate_selected_text, inputs=[positive_results_df], outputs=[pos_translate_output] ) negative_results_df.select( fn=translate_selected_text, inputs=[negative_results_df], outputs=[neg_translate_output] ) neutral_results_df.select( fn=translate_selected_text, inputs=[neutral_results_df], outputs=[neu_translate_output] ).then( lambda x, y: (generate_lda_prompt(x), generate_lda_prompt(y)), inputs=[pos_topics_df, neg_topics_df], outputs=[pos_prompt_output, neg_prompt_output] )
if __name__ == "__main__":app.py+244-319