File size: 35,603 Bytes
b97b654
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb43ca3
 
 
 
b97b654
d6f0825
 
 
 
 
 
 
 
 
b97b654
 
 
 
 
 
 
 
 
 
 
 
bb43ca3
b97b654
 
 
 
 
 
 
 
 
 
 
bb43ca3
 
 
 
 
 
 
 
 
b97b654
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6f0825
b97b654
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6f0825
b97b654
 
 
 
 
 
 
 
 
d6f0825
b97b654
 
 
 
 
 
 
 
 
 
bb43ca3
b97b654
 
bb43ca3
 
b97b654
bb43ca3
b97b654
 
 
 
 
 
 
 
 
 
 
bb43ca3
 
 
c677d98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb43ca3
 
 
b97b654
bb43ca3
 
c677d98
 
bb43ca3
 
 
 
 
 
 
c677d98
 
bb43ca3
 
 
 
 
 
 
c677d98
 
bb43ca3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b97b654
 
 
bb43ca3
b97b654
 
 
bb43ca3
b97b654
bb43ca3
 
c677d98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b97b654
c677d98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb43ca3
 
 
 
 
 
 
 
 
 
 
b97b654
 
 
bb43ca3
b97b654
 
 
bb43ca3
b97b654
 
 
 
 
bb43ca3
b97b654
 
 
 
 
c677d98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b97b654
 
bb43ca3
c677d98
 
 
 
 
 
 
 
 
b97b654
 
 
c677d98
 
 
 
 
 
 
 
 
 
 
 
b97b654
 
d6f0825
c677d98
 
 
 
 
 
 
 
 
 
 
 
 
 
b97b654
 
 
bb43ca3
b97b654
 
c677d98
 
 
 
 
 
 
 
 
 
b97b654
c677d98
 
 
b97b654
c677d98
 
 
 
 
 
 
 
 
 
 
 
 
 
b97b654
c677d98
 
 
 
 
 
b97b654
 
 
 
 
 
 
 
bb43ca3
d6f0825
 
 
 
b97b654
 
 
 
 
 
 
c677d98
bb43ca3
b97b654
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb43ca3
 
 
 
 
 
 
 
 
 
b97b654
bb43ca3
 
 
 
 
 
 
b97b654
 
 
 
 
 
 
 
 
 
 
 
 
 
bb43ca3
 
 
 
b97b654
bb43ca3
 
 
 
 
 
 
 
 
 
 
b97b654
bb43ca3
 
b97b654
bb43ca3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b97b654
 
 
 
 
 
 
ecb5ddf
 
 
 
 
 
 
 
 
 
 
b97b654
 
bb43ca3
 
b97b654
 
 
 
 
 
 
 
 
 
 
bb43ca3
 
 
 
 
b97b654
d6f0825
 
 
b97b654
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6f0825
 
b97b654
 
d6f0825
 
 
 
 
 
 
 
b97b654
bb43ca3
 
 
 
 
 
 
 
 
b97b654
d6f0825
 
 
 
 
 
 
 
b97b654
 
d6f0825
 
b97b654
bb43ca3
 
 
 
 
 
 
 
 
 
b97b654
d6f0825
b97b654
bb43ca3
 
d6f0825
bb43ca3
d6f0825
b97b654
 
bb43ca3
d6f0825
 
 
 
 
 
 
 
 
 
 
 
 
 
bb43ca3
 
 
 
 
 
 
d6f0825
 
 
 
 
 
 
 
 
 
 
bb43ca3
 
 
 
 
 
 
d6f0825
 
 
 
 
 
 
 
 
 
 
bb43ca3
 
 
 
 
 
 
d6f0825
b97b654
d6f0825
bb43ca3
 
 
d6f0825
bb43ca3
d6f0825
bb43ca3
d6f0825
 
 
bb43ca3
 
d6f0825
 
 
 
bb43ca3
 
d6f0825
 
 
 
bb43ca3
 
d6f0825
 
 
b97b654
 
 
 
d6f0825
 
 
 
 
 
bb43ca3
d6f0825
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb43ca3
 
 
 
b97b654
 
 
c677d98
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
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,
            '<div style="color: #666; padding: 10px;">请点击左侧词组查看相关评论</div>',  # 初始HTML提示
            excel_path
        )
    except Exception as e:
        import traceback
        error_msg = f"处理文件时出错:{str(e)}\n{traceback.format_exc()}"
        print(error_msg)  # 打印错误信息到控制台
        return error_msg, None, None, None, None, None, None, None, None, None, None, None, ""

def highlight_keyword(text, keyword):
    """用 <mark> 给 keyword 做简单的大小写不敏感高亮"""
    pattern = re.compile(re.escape(keyword), re.IGNORECASE)
    return pattern.sub(r'<mark style="background-color: #ffd700; padding: 0 2px; border-radius: 2px;">\g<0></mark>', text)

def show_bigram_reviews(evt: gr.SelectData, df):
    """显示选中词组的相关评论"""
    global current_bigram_samples, last_selected_reviews
    selected_bigram = df.iloc[evt.index[0]]["词组"]  # 获取选中行的词组
    
    # 清空上一次的评论列表
    last_selected_reviews = []
    
    for sample in current_bigram_samples:
        if sample[0] == selected_bigram:
            # 将评论转换为HTML格式
            reviews = sample[1][0].split("\n\n")
            highlighted_reviews = []
            
            for i, review in enumerate(reviews, start=1):
                # 保存原文评论(含序号)到全局变量
                last_selected_reviews.append(review)
                
                # 提取评论内容(去除序号前缀)
                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>'
                )
            
            # 拼接成完整的HTML
            html_content = (
                '<div style="max-height: 500px; overflow-y: auto; padding: 10px;">'
                f'<div style="margin-bottom: 10px; color: #333;">找到 {len(reviews)} 条包含 "<b>{selected_bigram}</b>" 的评论:</div>'
                f'{"".join(highlighted_reviews)}'
                '</div>'
            )
            return html_content
    
    return '<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_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(),  # 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("批量文件分析"):
            gr.Markdown("""
            ### 文件格式要求
            请上传符合以下格式的Excel文件(卖家精灵导出的评论数据):
            
            | 列名(必须一字不差) | 作用 | 数据要求 |
            |-------------------|------|---------|
            | **内容** | 原始评论文本 | 任意字符串 |
            | **内容(翻译)** | 评论的机器/人工翻译 | 若没有翻译可留空,但仍需保留此列 |
            | **星级** | 1–5 颗星 | 数值或可以转换成数值的文本 (1、2、3、4、5) |
            | **评论时间** | 评论日期/时间 | Excel 日期、`YYYY-MM-DD` 或其他常见日期格式,程序会自动解析 |
            """)
            with gr.Row():
                file_input = gr.File(
                    label="上传Excel文件(包含评论数据的xlsx文件)",
                    file_types=[".xlsx"]
                )
            
            analyze_file_btn = gr.Button("开始分析", variant="primary")
            
            with gr.Row():
                file_output = gr.Textbox(label="分析统计", lines=4)
            
            with gr.Row():
                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="积极评论词云")
                    neg_wordcloud = gr.Image(label="消极评论词云")
            
            gr.Markdown("### 关键词组统计")
            with gr.Row():
                with gr.Column(scale=1):
                    # 添加搜索框
                    search_box = gr.Textbox(
                        label="搜索关键词组",
                        placeholder="输入关键词以过滤词组...",
                        show_label=True
                    )
                    bigrams_df = gr.Dataframe(
                        headers=["词组", "出现次数", "占比"],
                        datatype=["str", "number", "str"],
                        wrap=True,
                        interactive=True
                    )
                    # 添加搜索事件
                    search_box.change(
                        fn=filter_bigrams,
                        inputs=[search_box],
                        outputs=[bigrams_df]
                    )
                with gr.Column(scale=1):
                    gr.Markdown("#### 选中词组的相关评论")
                    bigram_reviews = gr.HTML()
            
            # 添加词组选择事件
            bigrams_df.select(
                fn=show_bigram_reviews,
                inputs=[bigrams_df],
                outputs=bigram_reviews
            )
            
            gr.Markdown("### 主题分析结果")
            with gr.Row():
                with gr.Column():
                    gr.Markdown("#### 积极评论主题分析")
                    pos_topics_df = gr.Dataframe(
                        headers=["主题", "关键词"],
                        datatype=["str", "str"],
                        wrap=True,
                        label="积极评论主题关键词"
                    )
                    pos_doc_topics_df = gr.Dataframe(
                        headers=["文本", "主导主题", "主题概率"],
                        datatype=["str", "str", "str"],
                        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(
                        headers=["主题", "关键词"],
                        datatype=["str", "str"],
                        wrap=True,
                        label="消极评论主题关键词"
                    )
                    neg_doc_topics_df = gr.Dataframe(
                        headers=["文本", "主导主题", "主题概率"],
                        datatype=["str", "str", "str"],
                        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", "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)
            
            # 积极评论
            with gr.Row():
                gr.Markdown("#### 积极评论")
            with gr.Row():
                pos_search = gr.Textbox(
                    label="搜索积极评论",
                    placeholder="输入关键词搜索...",
                    show_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():
                gr.Markdown("#### 消极评论")
            with gr.Row():
                neg_search = gr.Textbox(
                    label="搜索消极评论",
                    placeholder="输入关键词搜索...",
                    show_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():
                gr.Markdown("#### 中性评论")
            with gr.Row():
                neu_search = gr.Textbox(
                    label="搜索中性评论",
                    placeholder="输入关键词搜索...",
                    show_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]
            )
            
            analyze_file_btn.click(
                analyze_file,
                inputs=[file_input],
                outputs=[
                    file_output,
                    pos_wordcloud,
                    neg_wordcloud,
                    results_df,
                    pie_chart,
                    time_series,
                    pos_topics_df,
                    pos_doc_topics_df,
                    neg_topics_df,
                    neg_doc_topics_df,
                    bigrams_df,
                    bigram_reviews,
                    file_download
                ]
            ).then(
                update_sentiment_results,
                inputs=[results_df],
                outputs=[
                    original_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__":
    demo.launch(share=False)