Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234567891011125 unmodified lines1819202122232425262721 unmodified lines4950515253545556575859606162636465666768697071727374757613 unmodified lines909192939495969798991001011021031041051061071081091101111121131141155 unmodified lines121122123124125126127128103 unmodified lines2322332342352362372382392402412422432445 unmodified lines2502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353367 unmodified lines34434534634734834935035135235335435535635735835936036136236336436536636736836919 unmodified lines3893903913923933945 unmodified lines40040140240340440540640740840941041141241341441541641720 unmodified lines4384394404414424434444454464474484498 unmodified lines4584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355 unmodified lines54154254354454554623 unmodified lines5705715725735745755765775785795805815825835845855865875882 unmodified lines59159259359459559659759859960060160260310 unmodified lines6146156166176186198 unmodified lines6286296306316326336346356366376386396406416426436448 unmodified lines6536546556566576586596606616626636646656666676686696705 unmodified lines6766776786796806816826836846856866876886896906916926935 unmodified lines6997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887 unmodified lines7967977987998008019 unmodified lines811812813814815816817818819820821822823824825826827828829830831832833834835import 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() # 初始化翻译器def get_stopwords(text):"""根据文本语言返回相应的停用词"""13 unmodified linesmask = 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 = re.sub(r'[^a-z\s]', ' ', text)5 unmodified linesdef extract_bigrams(texts, min_freq=2, max_freq_ratio=0.9):"""提取关键词组(两个单词)"""# 预处理所有文本processed_texts = [preprocess_text(text) for text in texts]# 提取所有双词组及其对应的文本all_bigrams = []103 unmodified linesempty_docs = pd.DataFrame(columns=["文本", "主导主题", "主题概率"])return empty_topics, empty_docsdef create_pie_chart(positive_count, negative_count):"""创建情感分布饼图"""fig = go.Figure(data=[go.Pie(labels=['积极评价', '消极评价'],values=[positive_count, negative_count],hole=.3,marker_colors=['#2ecc71', '#e74c3c'])])fig.update_layout(5 unmodified linesreturn figdef 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})return resultsdef analyze_file(file, progress=gr.Progress()):"""分析文件中的多个文本"""global current_bigram_samples, FULL_BIGRAM_DFtry:# 读取文件内容if file is None:return "请上传文件", None, None, None, None, None, None, None, None, None, None, ""# 读取上传的文件内容text_content = file.namewith open(text_content, 'r', encoding='utf-8') as f:content = f.readlines()progress(0, desc="正在预处理文本...")# 处理每一行评论texts = [line.strip() for line in content if line.strip()] # 预处理所有文本total_lines = len(texts)if total_lines == 0:return "没有找到有效的评论文本", None, None, None, None, None, None, None, None, None, None, ""# 检测语言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 = "语言检测失败,将使用英语停用词列表"progress(0.1, desc="正在进行情感分析...")# 批量处理文本results = analyze_texts_batch(texts)progress(0.3, desc="正在处理结果...")# 创建DataFramedf = pd.DataFrame(results)# 生成统计信息total = len(df)if total == 0:return "没有找到有效的评论文本", None, None, None, None, None, None, None, None, None, None, ""positive = len(df[df["整体情感"] == "积极"])negative = len(df[df["整体情感"] == "消极"])# 生成分析统计信息analysis_info = (f"{lang_info}\n"f"分析完成!共分析{total}条文本\n"f"积极:{positive}条 ({positive/total*100:.1f}%)\n"f"消极:{negative}条 ({negative/total*100:.1f}%)")progress(0.4, desc="正在生成词云...")# 生成词云positive_text = " ".join(df[df["整体情感"] == "积极"]["文本"])negative_text = " ".join(df[df["整体情感"] == "消极"]["文本"])pos_wordcloud = Noneneg_wordcloud = None7 unmodified linesneg_wordcloud = neg_wordcloud.to_image()progress(0.5, desc="正在生成可视化图表...")# 创建饼图pie_chart = create_pie_chart(positive, negative)progress(0.6, desc="正在提取关键词组...")# 提取关键词组bigrams_df, bigram_samples = extract_bigrams(texts)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()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="正在保存结果...")# 准备显示用的DataFramedisplay_df = df.copy()# 保存结果到Excel文件,包含多个sheetexcel_path = "sentiment_analysis_results.xlsx"19 unmodified linesneg_wordcloud,display_df,pie_chart,pos_topics_df,pos_doc_topics_df,neg_topics_df,5 unmodified linesexcept Exception as e:import tracebackerror_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['整体情感']}")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)# 添加序号和样式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>')8 unmodified linesreturn '<div style="color: #666; padding: 10px;">未找到相关评论</div>'def translate_single_comment(comment_index):"""翻译单条评论"""global last_selected_reviewsif not last_selected_reviews:return "请先选择一个词组查看相关评论。"try:comment_index = int(comment_index)except:return "请输入有效的评论序号(数字)"if comment_index < 1 or comment_index > len(last_selected_reviews):return f"评论序号超出范围!可选范围: 1~{len(last_selected_reviews)}"# 获取原文并去除序号前缀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]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)}"# 创建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"])analyze_file_btn = gr.Button("开始分析", variant="primary")5 unmodified lineswith gr.Column():gr.Markdown("### 评论情感分布")pie_chart = gr.Plot()with gr.Column():gr.Markdown("### 词云预览")pos_wordcloud = gr.Image(label="积极评论词云")23 unmodified lineswith 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 linesoutputs=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 lineswrap=True,label="积极评论主题分布")with gr.Column():gr.Markdown("#### 消极评论主题分析")neg_topics_df = gr.Dataframe(8 unmodified lineswrap=True,label="消极评论主题分布")gr.Markdown("### 详细分析结果")# 添加一个隐藏的DataFrame用于存储完整结果results_df = gr.Dataframe(headers=["文本", "整体情感"],datatype=["str", "str"],wrap=True,visible=False # 设置为隐藏)# 添加隐藏的DataFrame用于存储各类别的原始数据original_positive_df = gr.Dataframe(visible=False)original_negative_df = gr.Dataframe(visible=False)original_neutral_df = gr.Dataframe(visible=False)8 unmodified linesshow_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="点击左侧评论查看翻译")# 消极评论with gr.Row():5 unmodified linesshow_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="点击左侧评论查看翻译")# 中性评论with gr.Row():5 unmodified linesshow_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="点击左侧评论查看翻译")file_download = gr.File(label="下载完整分析结果(Excel)")def filter_comments(search_text, df, original_df):"""过滤评论"""if not search_text.strip() or df is None:return original_df# 不区分大小写的搜索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()# 返回格式化的HTMLreturn 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, Nonepositive_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,inputs=[pos_search, positive_results_df, original_positive_df],outputs=[positive_results_df])neg_search.change(fn=filter_comments,inputs=[neg_search, negative_results_df, original_negative_df],outputs=[negative_results_df])neu_search.change(fn=filter_comments,inputs=[neu_search, neutral_results_df, original_neutral_df],outputs=[neutral_results_df])7 unmodified linesneg_wordcloud,results_df,pie_chart,pos_topics_df,pos_doc_topics_df,neg_topics_df,9 unmodified linesoriginal_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])if __name__ == "__main__":12345675 unmodified lines13141516171821 unmodified lines40414243444546474849505152535413 unmodified lines686970717273747576775 unmodified lines838485868788899091929394959697103 unmodified lines2012022032042052062072082092102112122135 unmodified lines2192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333347 unmodified lines34234334434534634734834935035135235335435535635735835936036136236336436536636736819 unmodified lines3883893903913923933945 unmodified lines40040140240340440540620 unmodified lines4274284294304314324334344354364374384394404414424434444454464474484494508 unmodified lines4594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305 unmodified lines53653753853954054154254354454554623 unmodified lines5705715725735745752 unmodified lines57857958058158258310 unmodified lines5945955965975985996006016026036046056066076088 unmodified lines6176186196206216226236246256266276286296306316326336346356366376386396406416426438 unmodified lines6526536546556566576586596606616626636645 unmodified lines6706716726736746756766776786796806816825 unmodified lines6886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277 unmodified lines7357367377387397407419 unmodified lines751752753754755756757758759760import gradio as grfrom gradio import SelectDataimport pandas as pdfrom wordcloud import WordCloudimport 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 Translator# 下载停用词nltk.download('stopwords', quiet=True)21 unmodified lines'ja': 'japanese'}# 全局变量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 linesmask = FULL_BIGRAM_DF["词组"].str.contains(search_text, case=False, na=False)return FULL_BIGRAM_DF[mask]def preprocess_text(text):"""预处理文本"""# 转换为小写text = str(text).lower()# 去除特殊字符,只保留字母和空格text = re.sub(r'[^a-z\s]', ' ', text)5 unmodified linesdef extract_bigrams(texts, min_freq=2, max_freq_ratio=0.9):"""提取关键词组(两个单词)"""# 预处理所有文本,只处理原文部分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 linesempty_docs = pd.DataFrame(columns=["文本", "主导主题", "主题概率"])return empty_topics, empty_docsdef create_pie_chart(positive_count, negative_count, neutral_count):"""创建情感分布饼图"""fig = go.Figure(data=[go.Pie(labels=['积极评价', '中性评价', '消极评价'],values=[positive_count, neutral_count, negative_count],hole=.3,marker_colors=['#2ecc71', '#f1c40f', '#e74c3c'])])fig.update_layout(5 unmodified linesreturn figdef create_time_series_chart(df):"""创建评论时间序列折线图"""# 按时间和情感类别统计评论数time_sentiment_counts = df.groupby(['评论时间', '整体情感']).size().unstack(fill_value=0)# 创建折线图fig = go.Figure()# 添加积极评论折线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 figdef analyze_file(file, progress=gr.Progress()):"""分析文件中的多个文本"""global current_bigram_samples, FULL_BIGRAM_DF, results_df, positive_df, negative_df, neutral_dftry:if file is None:return "请上传文件", None, None, None, None, None, None, None, None, None, None, None, ""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]# 读取数据df = pd.read_excel(file.name, sheet_name=sheet_name)# 提取所需列并重命名df = df[["内容", "内容(翻译)", "星级", "评论时间"]]# 合并原文和翻译df["内容"] = df.apply(lambda x: f'{x["内容"]}\n\n翻译:{x["内容(翻译)"]}', axis=1)df = df.drop(columns=["内容(翻译)"]) # 删除翻译列# 处理评论时间格式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, None, ""positive = len(df[df["整体情感"] == "积极"])negative = len(df[df["整体情感"] == "消极"])neutral = len(df[df["整体情感"] == "中性"])# 生成分析统计信息analysis_info = (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["整体情感"] == "积极"]["内容"].astype(str))negative_text = " ".join(df[df["整体情感"] == "消极"]["内容"].astype(str))pos_wordcloud = Noneneg_wordcloud = None7 unmodified linesneg_wordcloud = neg_wordcloud.to_image()progress(0.5, desc="正在生成可视化图表...")# 创建饼图和时间序列图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(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()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="正在保存结果...")# 准备显示用的DataFramedisplay_df = df[["内容", "整体情感", "评论时间"]].copy()# 保存结果到Excel文件,包含多个sheetexcel_path = "sentiment_analysis_results.xlsx"19 unmodified linesneg_wordcloud,display_df,pie_chart,time_series, # 添加时间序列图pos_topics_df,pos_doc_topics_df,neg_topics_df,5 unmodified linesexcept Exception as e:import tracebackerror_msg = f"处理文件时出错:{str(e)}\n{traceback.format_exc()}"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# 分离原文和译文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: 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 linesreturn '<div style="color: #666; padding: 10px;">未找到相关评论</div>'def filter_comments(search_text, df):"""过滤评论"""if df is None or len(df) == 0:return df# 当搜索框为空时,返回原始数据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_dfif 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(), # original_positive_dfnegative_df.copy(), # original_negative_dfneutral_df.copy(), # original_neutral_dfpositive_df.copy(), # positive_results_dfnegative_df.copy(), # negative_results_dfneutral_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():file_input = gr.File(label="上传Excel文件(包含评论数据的xlsx文件)",file_types=[".xlsx"])analyze_file_btn = gr.Button("开始分析", variant="primary")5 unmodified lineswith 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 lineswith gr.Column(scale=1):gr.Markdown("#### 选中词组的相关评论")bigram_reviews = gr.HTML()# 添加词组选择事件bigrams_df.select(2 unmodified linesoutputs=bigram_reviews)gr.Markdown("### 主题分析结果")with gr.Row():with gr.Column():10 unmodified lineswrap=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 lineswrap=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", "str"],wrap=True,line_breaks=True,visible=False # 设置为隐藏)# 添加隐藏的DataFrame用于存储原始数据original_positive_df = gr.Dataframe(visible=False)original_negative_df = gr.Dataframe(visible=False)original_neutral_df = gr.Dataframe(visible=False)8 unmodified linesshow_label=True)with gr.Row():positive_results_df = gr.Dataframe(headers=["内容", "整体情感", "评论时间"],datatype=["str", "str", "str"],wrap=True,line_breaks=True,interactive=True)# 消极评论with gr.Row():5 unmodified linesshow_label=True)with gr.Row():negative_results_df = gr.Dataframe(headers=["内容", "整体情感", "评论时间"],datatype=["str", "str", "str"],wrap=True,line_breaks=True,interactive=True)# 中性评论with gr.Row():5 unmodified linesshow_label=True)with gr.Row():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_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)return original_df[mask].reset_index(drop=True)# 添加搜索事件处理pos_search.input(fn=filter_comments_with_original,inputs=[pos_search, positive_results_df, original_positive_df],outputs=[positive_results_df])neg_search.input(fn=filter_comments_with_original,inputs=[neg_search, negative_results_df, original_negative_df],outputs=[negative_results_df])neu_search.input(fn=filter_comments_with_original,inputs=[neu_search, neutral_results_df, original_neutral_df],outputs=[neutral_results_df])7 unmodified linesneg_wordcloud,results_df,pie_chart,time_series,pos_topics_df,pos_doc_topics_df,neg_topics_df,9 unmodified linesoriginal_positive_df, original_negative_df, original_neutral_df,positive_results_df, negative_results_df, neutral_results_df]).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