import gradio as gr from gradio import SelectData import pandas as pd from wordcloud import WordCloud import plotly.graph_objects as go from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.decomposition import LatentDirichletAllocation as LDA import nltk from nltk.corpus import stopwords from langdetect import detect import langdetect import re from collections import Counter from nltk.util import ngrams from googletrans import Translator # 下载停用词 nltk.download('stopwords', quiet=True) nltk.download('punkt', quiet=True) # 支持的语言 SUPPORTED_LANGUAGES = ['english', 'spanish', 'french', 'german', 'italian', 'portuguese', 'russian', 'arabic', 'japanese'] # 创建语言停用词字典 LANGUAGE_STOPWORDS = {} for lang in SUPPORTED_LANGUAGES: if lang in stopwords.fileids(): LANGUAGE_STOPWORDS[lang] = set(stopwords.words(lang)) # 语言代码映射 LANG_CODE_MAP = { 'en': 'english', 'es': 'spanish', 'fr': 'french', 'de': 'german', 'it': 'italian', 'pt': 'portuguese', 'ru': 'russian', 'ar': 'arabic', '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): """根据文本语言返回相应的停用词""" try: lang_code = detect(text) lang = LANG_CODE_MAP.get(lang_code, 'english') return LANGUAGE_STOPWORDS.get(lang, LANGUAGE_STOPWORDS['english']) except langdetect.LangDetectException: return LANGUAGE_STOPWORDS['english'] def filter_bigrams(search_text): """过滤关键词组""" global FULL_BIGRAM_DF if not search_text.strip(): return FULL_BIGRAM_DF # 不区分大小写的搜索 mask = 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) # 去除多余空格 text = re.sub(r'\s+', ' ', text).strip() return text def 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 = [] bigram_texts = {} # 存储词组对应的原始文本 for idx, (text, processed) in enumerate(zip(texts, processed_texts)): words = processed.split() text_bigrams = list(ngrams(words, 2)) text_bigram_strs = [' '.join(bigram) for bigram in text_bigrams] all_bigrams.extend(text_bigram_strs) # 记录每个词组对应的原始文本 for bigram in text_bigram_strs: if bigram not in bigram_texts: bigram_texts[bigram] = [] bigram_texts[bigram].append(text) # 计算词组频率 bigram_freq = Counter(all_bigrams) total_docs = len(texts) # 总评论数 # 过滤词组 filtered_bigrams = { bigram: freq for bigram, freq in bigram_freq.items() if min_freq <= freq <= total_docs * max_freq_ratio # 保留在频率范围内的词组 } # 创建词组统计DataFrame bigram_stats = [] # 准备Dataset数据 dataset_samples = [] for bigram, freq in sorted(filtered_bigrams.items(), key=lambda x: x[1], reverse=True): # 计算占总评论数的百分比 percentage = freq / total_docs * 100 # 获取该词组对应的所有文本 related_texts = bigram_texts[bigram] # 统计DataFrame数据 bigram_stats.append({ "词组": bigram, "出现次数": freq, "占比": f"{percentage:.2f}%" # 占总评论数的百分比 }) # Dataset数据 formatted_texts = "\n\n".join(f"{i+1}. {text}" for i, text in enumerate(related_texts)) dataset_samples.append([bigram, [formatted_texts]]) return pd.DataFrame(bigram_stats), dataset_samples def perform_lda_analysis(texts, sentiment_type="all", n_topics=15): """执行LDA主题分析""" # 获取动态停用词 stop_words = list(get_stopwords(' '.join(texts))) # 创建TF-IDF向量化器 vectorizer = TfidfVectorizer( max_df=0.9, # 忽略在90%以上文档中出现的词 min_df=2, # 忽略在少于2个文档中出现的词 stop_words=stop_words, # 使用动态停用词 ngram_range=(2, 2) # 使用双词组(bigrams) ) # 预处理文本 processed_texts = [preprocess_text(text) for text in texts] # 转换文本数据 try: tfidf = vectorizer.fit_transform(processed_texts) # 创建并训练LDA模型 lda_model = LDA( n_components=n_topics, random_state=0 ) lda_output = lda_model.fit_transform(tfidf) # 获取特征词 feature_names = vectorizer.get_feature_names_out() # 整理主题词 topics = [] for topic_idx, topic in enumerate(lda_model.components_): top_words_idx = topic.argsort()[:-15:-1] # 获取前15个词组 top_words = [feature_names[i] for i in top_words_idx] topics.append({ "主题": f"{sentiment_type}主题 {topic_idx + 1}", "关键词": ", ".join(top_words) }) # 获取每个文档的主题分布 doc_topics = [] for doc_idx, doc_topics_dist in enumerate(lda_output): dominant_topic = doc_topics_dist.argmax() doc_topics.append({ "文本": texts[doc_idx], # 显示完整文本 "主导主题": f"{sentiment_type}主题 {dominant_topic + 1}", "主题概率": f"{doc_topics_dist[dominant_topic]:.2%}" }) return pd.DataFrame(topics), pd.DataFrame(doc_topics) except ValueError as e: # 如果没有足够的词组进行分析,返回空的DataFrame empty_topics = pd.DataFrame(columns=["主题", "关键词"]) empty_docs = pd.DataFrame(columns=["文本", "主导主题", "主题概率"]) return empty_topics, empty_docs def 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( title="情感分布", showlegend=True, width=400, height=400 ) return fig def create_time_series_chart(df): """创建评论时间序列折线图""" # 按时间和情感类别统计评论数 df_copy = df.copy() # 确保评论时间列是日期类型 df_copy["评论时间"] = pd.to_datetime(df_copy["评论时间"]) # 按日期排序 df_copy = df_copy.sort_values("评论时间") # 分别获取各情感类别的数据 positive_df = df_copy[df_copy["整体情感"] == "积极"] neutral_df = df_copy[df_copy["整体情感"] == "中性"] negative_df = df_copy[df_copy["整体情感"] == "消极"] # 分别按时间统计各情感类别的评论数 positive_counts = positive_df.groupby("评论时间").size() neutral_counts = neutral_df.groupby("评论时间").size() negative_counts = negative_df.groupby("评论时间").size() # 获取所有唯一的日期 all_dates = sorted(set(df_copy["评论时间"].dt.date)) # 创建折线图 fig = go.Figure() # 添加积极评论折线 fig.add_trace(go.Scatter( x=positive_counts.index, y=positive_counts.values, name='积极评论', line=dict(color='#2ecc71', width=2), mode='lines+markers' )) # 添加中性评论折线 fig.add_trace(go.Scatter( x=neutral_counts.index, y=neutral_counts.values, name='中性评论', line=dict(color='#f1c40f', width=2), mode='lines+markers' )) # 添加消极评论折线 fig.add_trace(go.Scatter( x=negative_counts.index, y=negative_counts.values, 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, results_df, positive_df, negative_df, neutral_df try: if file is None: return "请上传文件", None, None, None, None, None, None, None, None, None, None, None, "" progress(0, desc="正在读取Excel文件...") # 读取Excel文件 try: print(f"尝试读取文件: {file.name}") excel_file = pd.ExcelFile(file.name) # 获取包含评论数量的sheet名 sheet_names = excel_file.sheet_names print(f"Excel文件中的sheet名称: {sheet_names}") # 首先尝试查找包含"Review"的sheet review_sheets = [name for name in sheet_names if "Review" in name] # 如果没有找到包含"Review"的sheet,则使用第一个sheet if not review_sheets: print(f"未找到包含'Review'的sheet,将使用第一个sheet: {sheet_names[0]}") sheet_name = sheet_names[0] else: sheet_name = review_sheets[0] print(f"选择的sheet名称: {sheet_name}") # 读取数据 df = pd.read_excel(file.name, sheet_name=sheet_name) print(f"读取的数据形状: {df.shape}, 列名: {list(df.columns)}") # 检查必要的列是否存在 required_columns = ["内容", "内容(翻译)", "星级", "评论时间"] missing_columns = [col for col in required_columns if col not in df.columns] if missing_columns: return f"Excel文件缺少必要的列: {', '.join(missing_columns)},可用的列有: {', '.join(df.columns)}", None, None, None, None, None, None, None, None, None, None, None, "" # 提取所需列并重命名 df = df[["内容", "内容(翻译)", "星级", "评论时间"]] except Exception as e: import traceback error_details = traceback.format_exc() return f"读取Excel文件时出错: {str(e)}\n\n详细错误信息:\n{error_details}", None, None, None, None, None, None, None, None, None, None, None, "" try: # 合并原文和翻译 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 "消极")) except Exception as e: import traceback error_details = traceback.format_exc() return f"处理数据时出错: {str(e)}\n\n详细错误信息:\n{error_details}", None, None, None, None, None, None, None, None, None, None, None, "" # 保存完整结果到全局变量 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="正在生成词云...") # 生成词云 try: positive_text = " ".join(df[df["整体情感"] == "积极"]["内容"].astype(str)) negative_text = " ".join(df[df["整体情感"] == "消极"]["内容"].astype(str)) pos_wordcloud = None neg_wordcloud = None if positive_text: pos_wordcloud = WordCloud(width=400, height=200, background_color='white').generate(positive_text) pos_wordcloud = pos_wordcloud.to_image() if negative_text: neg_wordcloud = WordCloud(width=400, height=200, background_color='white').generate(negative_text) neg_wordcloud = neg_wordcloud.to_image() except Exception as e: import traceback error_details = traceback.format_exc() print(f"生成词云时出错: {str(e)}\n{error_details}") # 继续执行,不中断流程 progress(0.5, desc="正在生成可视化图表...") # 创建饼图和时间序列图 try: pie_chart = create_pie_chart(positive, negative, neutral) time_series = create_time_series_chart(df) except Exception as e: import traceback error_details = traceback.format_exc() print(f"生成图表时出错: {str(e)}\n{error_details}") pie_chart = None time_series = None progress(0.6, desc="正在提取关键词组...") # 提取关键词组 try: bigrams_df, bigram_samples = extract_bigrams(df["内容"].tolist()) current_bigram_samples = bigram_samples # 更新全局变量 FULL_BIGRAM_DF = bigrams_df.copy() # 保存完整的bigram数据 except Exception as e: import traceback error_details = traceback.format_exc() print(f"提取关键词组时出错: {str(e)}\n{error_details}") bigrams_df = pd.DataFrame(columns=["词组", "出现次数", "占比"]) bigram_samples = [] current_bigram_samples = [] FULL_BIGRAM_DF = bigrams_df.copy() progress(0.7, desc="正在进行主题分析...") # 分别对积极和消极评论进行LDA分析 try: 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, "消极") except Exception as e: import traceback error_details = traceback.format_exc() print(f"进行主题分析时出错: {str(e)}\n{error_details}") pos_topics_df = pd.DataFrame(columns=["主题", "关键词"]) pos_doc_topics_df = pd.DataFrame(columns=["文本", "主导主题", "主题概率"]) neg_topics_df = pd.DataFrame(columns=["主题", "关键词"]) neg_doc_topics_df = pd.DataFrame(columns=["文本", "主导主题", "主题概率"]) progress(0.9, desc="正在保存结果...") # 准备显示用的DataFrame display_df = df[["内容", "整体情感", "评论时间"]].copy() # 保存结果到Excel文件,包含多个sheet try: import os # 获取当前工作目录 current_dir = os.getcwd() print(f"当前工作目录: {current_dir}") # 尝试在当前目录下创建results文件夹 results_dir = os.path.join(current_dir, "results") os.makedirs(results_dir, exist_ok=True) print(f"创建结果目录: {results_dir}") # 保存到results文件夹中 excel_path = os.path.join(results_dir, "sentiment_analysis_results.xlsx") print(f"尝试保存结果到: {excel_path}") with pd.ExcelWriter(excel_path, engine='openpyxl') as writer: # 保存情感分析结果 df.to_excel(writer, sheet_name='情感分析结果', index=False) # 保存积极评论LDA主题关键词 pos_topics_df.to_excel(writer, sheet_name='积极评论主题关键词', index=False) pos_doc_topics_df.to_excel(writer, sheet_name='积极评论主题分布', index=False) # 保存消极评论LDA主题关键词 neg_topics_df.to_excel(writer, sheet_name='消极评论主题关键词', index=False) neg_doc_topics_df.to_excel(writer, sheet_name='消极评论主题分布', index=False) # 保存关键词组统计 bigrams_df.to_excel(writer, sheet_name='关键词组统计', index=False) print(f"结果成功保存到: {excel_path}") except Exception as e: import traceback error_details = traceback.format_exc() print(f"保存结果时出错: {str(e)}\n{error_details}") excel_path = "" progress(1.0, desc="分析完成!") return ( analysis_info, pos_wordcloud, neg_wordcloud, display_df, pie_chart, time_series, # 添加时间序列图 pos_topics_df, pos_doc_topics_df, neg_topics_df, neg_doc_topics_df, bigrams_df, '