File size: 40,805 Bytes
0459d39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95125e8
0459d39
2219fdf
693b8fd
2219fdf
 
 
 
 
 
 
 
 
 
 
 
fbde3c0
 
 
 
2219fdf
 
 
 
 
 
 
 
 
 
693b8fd
2219fdf
 
 
 
 
 
 
 
 
 
0459d39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2219fdf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0459d39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fbde3c0
 
 
 
 
 
0459d39
fbde3c0
 
2219fdf
 
 
fbde3c0
 
 
 
 
 
 
 
 
 
2219fdf
fbde3c0
 
 
 
 
2219fdf
fbde3c0
 
2219fdf
fbde3c0
 
2219fdf
fbde3c0
 
2219fdf
 
 
 
fbde3c0
 
 
0459d39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fbde3c0
 
2219fdf
0459d39
 
 
2219fdf
 
0459d39
2219fdf
0459d39
 
 
2219fdf
 
0459d39
2219fdf
0459d39
2219fdf
0459d39
 
2219fdf
0459d39
 
2219fdf
 
0459d39
2219fdf
 
 
0459d39
2219fdf
 
 
 
 
 
0459d39
2219fdf
 
 
 
 
 
 
 
fbde3c0
 
0459d39
2219fdf
 
 
0459d39
2219fdf
 
0459d39
2219fdf
 
 
0459d39
2219fdf
 
 
0459d39
2219fdf
 
 
0459d39
2219fdf
 
0459d39
2219fdf
 
0459d39
2219fdf
 
 
 
 
 
0459d39
2219fdf
 
 
0459d39
2219fdf
0459d39
2219fdf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0459d39
 
 
 
 
 
 
 
 
 
 
fbde3c0
 
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 streamlit as st
import pandas as pd
import openpyxl
from PIL import Image as PILImage
import io
from io import BytesIO
import os
import uuid
from openpyxl.styles import Border, Side, Alignment, Font
from openpyxl.drawing.image import Image as XLImage
import zipfile
import tempfile
import shutil
import time
import asyncio
import aiohttp
from openpyxl.utils import get_column_letter

st.set_page_config(page_title="竞品对比 AI版", layout="wide")

st.title("🔩 竞品对比 AI版")
st.markdown("上传卖家精灵的产品数据,自动输出产品卖点、销售额等数据对比")

# 初始化session_state
if 'selling_points_data' not in st.session_state:
    st.session_state.selling_points_data = {}
if 'excel_buffer' not in st.session_state:
    st.session_state.excel_buffer = None
if 'basic_excel_buffer' not in st.session_state:
    st.session_state.basic_excel_buffer = None
if 'analysis_complete' not in st.session_state:
    st.session_state.analysis_complete = False
if 'current_asins' not in st.session_state:
    st.session_state.current_asins = []
if 'analysis_requested' not in st.session_state:
    st.session_state.analysis_requested = False
if 'manual_asins_input' not in st.session_state:
    st.session_state.manual_asins_input = ""

# 显示教程图片按钮
st.link_button(
    "📋 数据源下载步骤",
    "http://objects.mambate.top/example/数据源下载步骤.png",
    help="点击查看数据源下载步骤教程图片"
)

# 添加下载按钮
st.link_button(
    "📊 数据源示例", 
    "https://objects.mambate.top/example/竞品对比数据源模板.xlsx",
    help="点击下载Excel数据源模板文件"
)
st.link_button(
    "📈 下载结果示例", 
    "https://objects.mambate.top/example/竞品对比结果.xlsx",
    help="点击下载竞品对比结果示例文件"
)

st.markdown("---")  # 添加分割线

# 检查API密钥环境变量
api_key = os.environ.get("DIFY_API_KEY", "")
if not api_key:
    st.warning("⚠️ 未设置API密钥环境变量(DIFY_API_KEY),AI卖点解析功能将无法使用。请在环境变量中设置DIFY_API_KEY。")

# 创建图片目录
image_dir = os.path.join(tempfile.gettempdir(), "extracted_images")
if not os.path.exists(image_dir):
    os.makedirs(image_dir, exist_ok=True)

# AI卖点解析功能
async def fetch_selling_points(session, product_info, product_quantity):
    """调用Dify API获取产品卖点对比"""
    api_url = "https://dify.mambate.top/v1/workflows/run"
    
    # 从环境变量获取API密钥
    api_key = os.environ.get("DIFY_API_KEY", "")
    
    if not api_key:
        st.error("未设置API密钥环境变量(DIFY_API_KEY),无法进行卖点解析")
        return []
        
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }
    payload = {
        "inputs": {
            "Product_Information": product_info,
            "Product_Quantity": product_quantity
        },
        "response_mode": "blocking",
        "user": "waka"
    }
    
    try:
        async with session.post(api_url, headers=headers, json=payload) as response:
            if response.status == 200:
                result = await response.json()
                if (result.get("data") and 
                    result["data"].get("outputs") and 
                    result["data"]["outputs"].get("sellingPoints") and
                    result["data"]["outputs"]["sellingPoints"].get("comparison")):
                    return result["data"]["outputs"]["sellingPoints"]["comparison"]
            return []
    except Exception as e:
        st.error(f"解析产品卖点时出错: {str(e)}")
        return []

async def process_selling_points_batch(product_data_dict, batch_size=10):
    """批量处理产品卖点解析,每批最多10个ASIN"""
    results = {}
    
    # 如果没有产品数据,直接返回空结果
    if not product_data_dict:
        return results
        
    batches = [list(product_data_dict.items())[i:i+batch_size] for i in range(0, len(product_data_dict), batch_size)]
    
    for batch in batches:
        async with aiohttp.ClientSession() as session:
            tasks = []
            for asin, product_info in batch:
                tasks.append(fetch_selling_points(session, product_info, len([asin for asin, info in batch if asin == asin])))
            
            batch_results = await asyncio.gather(*tasks)
            for asin, selling_points in batch_results:
                results[asin] = selling_points
    
    return results

def analyze_selling_points(filtered_df):
    """分析产品卖点并返回结果"""
    # 确保 filtered_df 不是 None
    if filtered_df is None or filtered_df.empty:
        st.error("没有可用的产品数据进行卖点分析")
        return {}
    
    # 检查必要的列是否存在
    if "商品标题" not in filtered_df.columns:
        st.error('Excel文件中缺少"商品标题"列')
        return {}
        
    if "产品卖点" not in filtered_df.columns:
        st.error('Excel文件中缺少"产品卖点"列')
        return {}
    
    # 提取所有选中的ASIN相关信息
    all_product_info = ""
    selected_asins = filtered_df["ASIN"].unique().tolist()
    product_quantity = len(selected_asins)
    
    for _, row in filtered_df.iterrows():
        asin = row.get("ASIN", "")
        if pd.isna(asin) or not asin:
            continue
            
        # 直接获取"商品标题"和"产品卖点"列
        title = row.get("商品标题", "")
        bullet_points = row.get("产品卖点", "")
        
        # 转换为字符串,处理非字符串值
        if not pd.isna(title):
            title = str(title)
        else:
            title = ""
            
        if not pd.isna(bullet_points):
            bullet_points = str(bullet_points)
        else:
            bullet_points = ""
        
        # 添加到所有产品信息中,使用分隔符分割每个商品
        all_product_info += f"ASIN: {asin}\n标题: {title}\n卖点: {bullet_points}\n######################\n"
    
    # 如果没有有效的产品数据,返回错误
    if not all_product_info:
        st.error('没有找到有效的产品信息,请确保"商品标题"和"产品卖点"列有数据')
        return {}
    
    try:
        # 发送请求并获取结果
        async def process_request():
            async with aiohttp.ClientSession() as session:
                return await fetch_selling_points(session, all_product_info, product_quantity)
        
        comparison_result = asyncio.run(process_request())
        return comparison_result
    except Exception as e:
        st.error(f"运行卖点分析时出错: {str(e)}")
        return {}

def extract_images_from_excel(excel_file_path):
    """从Excel文件中提取嵌入的图片"""
    # 创建临时目录
    temp_dir = tempfile.mkdtemp()
    
    try:
        # 将xlsx文件解压到临时目录
        with zipfile.ZipFile(excel_file_path, 'r') as zip_ref:
            zip_ref.extractall(temp_dir)
        
        # 查找media文件夹中的图片
        media_dir = os.path.join(temp_dir, 'xl', 'media')
        if not os.path.exists(media_dir):
            return {}
            
        # 确保image_dir存在
        if not os.path.exists(image_dir):
            os.makedirs(image_dir, exist_ok=True)
        
        # 加载Excel以获取ASIN列
        df = pd.read_excel(excel_file_path, engine='openpyxl')
        
        # 获取所有ASIN及其在DataFrame中的顺序
        asins = []
        for i, row in df.iterrows():
            asin = row.get('ASIN', '')
            if asin and not pd.isna(asin):
                asins.append(str(asin))
        
        # 获取media文件夹中的所有图片
        image_files = {}
        for file in os.listdir(media_dir):
            if file.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp')):
                img_path = os.path.join(media_dir, file)
                # 提取图片索引 (通常格式为 image1.png, image2.png 等)
                try:
                    # 尝试提取数字部分作为索引
                    img_idx = int(''.join(filter(str.isdigit, file)))
                    image_files[img_idx] = img_path
                except:
                    # 如果无法提取索引,使用文件名
                    image_files[file] = img_path
        
        # 调试: 打印所有图片文件及其索引
        img_indices = sorted(list(image_files.keys()))
        
        # 创建ASIN到图片路径的映射
        asin_to_image = {}
        
        # 尝试通过索引建立匹配 (假设索引从1开始,匹配ASIN列表的顺序)
        # 这种方法适用于图片索引与ASIN顺序相匹配的情况
        for i, asin in enumerate(asins):
            # 图片索引是从1开始的,所以需要加1
            img_idx = i + 1
            if img_idx in image_files:
                img_path = image_files[img_idx]
                target_path = os.path.join(image_dir, f"{asin}.png")
                # 检查目标文件是否存在,如果存在则尝试删除或重命名
                if os.path.exists(target_path):
                    try:
                        os.remove(target_path)
                    except OSError: # 文件可能被占用
                        base, ext = os.path.splitext(target_path)
                        target_path = f"{base}_{uuid.uuid4().hex[:6]}{ext}"
                # 使用PIL打开并保存图片,避免直接文件复制
                try:
                    img = PILImage.open(img_path)
                    img.save(target_path)
                    asin_to_image[asin] = target_path
                except Exception as e:
                    st.warning(f"保存图片时出错: {str(e)}")
                    continue
        
        # 如果前面的方法没有成功提取所有ASIN的图片
        if len(asin_to_image) != len(asins):
            # 尝试使用工作簿的方式 - 但只处理第一个工作表
            try:
                wb = openpyxl.load_workbook(excel_file_path, read_only=False, data_only=True)
                
                # 只使用第一个工作表
                if len(wb.sheetnames) > 0:
                    first_sheet_name = wb.sheetnames[0]
                    ws = wb[first_sheet_name]
                    
                    # 检查工作表是否有图片
                    if hasattr(ws, '_images') and len(ws._images) > 0:
                        # 直接将图片按顺序与ASIN匹配
                        # 这种方法假设Excel中图片的顺序与ASIN列表的顺序相同
                        for i, asin in enumerate(asins):
                            if i < len(ws._images) and i < len(img_indices):
                                # 获取对应索引的图片
                                img_idx = img_indices[i]
                                if img_idx in image_files:
                                    img_path = image_files[img_idx]
                                    target_path = os.path.join(image_dir, f"{asin}.png")
                                    # 检查目标文件是否存在,如果存在则尝试删除或重命名
                                    if os.path.exists(target_path):
                                        try:
                                            os.remove(target_path)
                                        except OSError: # 文件可能被占用
                                            base, ext = os.path.splitext(target_path)
                                            target_path = f"{base}_{uuid.uuid4().hex[:6]}{ext}"
                                    # 使用PIL打开并保存图片,避免直接文件复制
                                    try:
                                        img = PILImage.open(img_path)
                                        img.save(target_path)
                                        asin_to_image[asin] = target_path
                                    except Exception as e:
                                        st.warning(f"保存图片时出错: {str(e)}")
                                        continue
            except Exception as e:
                pass  # 忽略错误,尝试下一种方法
        
        # 如果依然没有匹配全部图片,使用最后的备用方法
        if len(asin_to_image) != len(asins) and len(asins) == len(image_files):
            # 按照图片索引排序
            sorted_img_indices = sorted(img_indices)
            
            # 清空之前的结果重新匹配
            asin_to_image = {}
            
            # 直接按照排序后的索引与ASIN一一对应
            for i, asin in enumerate(asins):
                if i < len(sorted_img_indices):
                    img_idx = sorted_img_indices[i]
                    img_path = image_files[img_idx]
                    target_path = os.path.join(image_dir, f"{asin}.png")
                    # 检查目标文件是否存在
                    if os.path.exists(target_path):
                        try:
                            os.remove(target_path)
                        except OSError:
                            base, ext = os.path.splitext(target_path)
                            target_path = f"{base}_{uuid.uuid4().hex[:6]}{ext}"
                    # 使用PIL打开并保存图片,避免直接文件复制
                    try:
                        img = PILImage.open(img_path)
                        img.save(target_path)
                        asin_to_image[asin] = target_path
                    except Exception as e:
                        st.warning(f"保存图片时出错: {str(e)}")
                        continue
        
        return asin_to_image
        
    except Exception as e:
        return {}
    finally:
        # 清理临时文件
        try:
            if 'temp_file' in locals() and os.path.exists(temp_file):
                os.remove(temp_file)
        except Exception as e:
            pass  # 忽略任何清理错误

def generate_excel_file(result_df, transposed_df, asin_to_image, selling_points_data=None):
    """生成Excel文件并返回buffer"""
    try:
        # 创建一个新的工作簿
        wb = openpyxl.Workbook()
        ws = wb.active
        ws.title = "提取结果"
        
        # 写入标题行
        all_fields_in_transposed_df = transposed_df.index.tolist()
        current_excel_row_for_styling = 1

        for field_name in all_fields_in_transposed_df:
            # 标准字段
            ws.merge_cells(start_row=current_excel_row_for_styling, start_column=1, end_row=current_excel_row_for_styling, end_column=2) # Merge A:B
            cell_to_style = ws.cell(row=current_excel_row_for_styling, column=1, value=field_name)
            cell_to_style.font = Font(bold=True) # 标题加粗
            current_excel_row_for_styling += 1

        # 写入数据 - 每个ASIN一列,从第三列开始
        for col_idx, asin in enumerate(transposed_df.columns):
            col_pos = col_idx + 3  # 数据从第三列(C列)开始
            
            for row_idx, field in enumerate(transposed_df.index):
                excel_row_for_data = row_idx + 1
                if field == "图片":
                    continue  # 图片处理在后面单独进行
                
                cell = ws.cell(row=excel_row_for_data, column=col_pos)
                cell.value = str(transposed_df.loc[field, asin])
        
        # 设置单元格样式 (全局边框和居中)
        thin_border = Border(
            left=Side(style='thin'),
            right=Side(style='thin'),
            top=Side(style='thin'),
            bottom=Side(style='thin')
        )
        center_aligned = Alignment(horizontal='center', vertical='center', wrap_text=True)
        
        # 遍历所有相关单元格设置边框和居中对齐
        # Max row is determined by the number of fields in transposed_df
        max_row_to_style = len(transposed_df.index)
        # Max col is ASINs + 2 (for A and B columns)
        max_col_to_style = len(transposed_df.columns) + 2 

        for r_idx in range(1, max_row_to_style + 1):
            for c_idx in range(1, max_col_to_style + 1):
                cell = ws.cell(row=r_idx, column=c_idx)
                cell.border = thin_border
                # 应用居中对齐
                cell.alignment = center_aligned
        
        # 标题已经设置为加粗

        # 设置ASIN行(列标题, 即ASIN值本身在数据中的行)加粗
        # This logic needs to find the row where field name is "ASIN"
        if "ASIN" in transposed_df.index:
            asin_header_row_excel = transposed_df.index.tolist().index("ASIN") + 1
            for c_idx in range(3, max_col_to_style + 1): # ASIN values start from column C
                 ws.cell(row=asin_header_row_excel, column=c_idx).font = Font(bold=True)

        # 调整列宽
        ws.column_dimensions['A'].width = 10 
        ws.column_dimensions['B'].width = 13 # For detailed parameter keys
        
        for idx_cw in range(len(transposed_df.columns)):
            col_letter = get_column_letter(idx_cw + 3) # Data columns C, D, ...
            ws.column_dimensions[col_letter].width = 13
        
        # 添加图片到Excel - 处理"图片"行
        if "图片" in transposed_df.index:
            image_row_idx_excel = transposed_df.index.tolist().index("图片") + 1
            ws.row_dimensions[image_row_idx_excel].height = 75
        
            # 设置品牌链接行高为45
            if "品牌链接" in transposed_df.index:
                brand_link_row_idx_excel = transposed_df.index.tolist().index("品牌链接") + 1
                ws.row_dimensions[brand_link_row_idx_excel].height = 45
            
            resized_img_paths = []
            for col_idx, asin_val in enumerate(transposed_df.columns):
                img_path_val = transposed_df.loc["图片", asin_val]
                if img_path_val and isinstance(img_path_val, str) and os.path.exists(img_path_val):
                    try:
                        col_pos_img = col_idx + 3
                        col_letter_img = get_column_letter(col_pos_img)
                        
                        cell_img_text = ws.cell(row=image_row_idx_excel, column=col_pos_img)
                        cell_img_text.value = None # Clear any text
                        
                        max_size = (100, 100)
                        pil_img = PILImage.open(img_path_val)
                        pil_img.thumbnail(max_size, PILImage.LANCZOS)
                        background = PILImage.new('RGB', max_size, (255, 255, 255))
                        paste_x = (max_size[0] - pil_img.width) // 2
                        paste_y = (max_size[1] - pil_img.height) // 2
                        background.paste(pil_img, (paste_x, paste_y))
                        
                        # 使用临时目录创建调整大小后的图片
                        temp_img_id = str(uuid.uuid4())
                        resized_img_path = os.path.join(tempfile.gettempdir(), f"temp_resized_{temp_img_id}.png")
                        background.save(resized_img_path)
                        resized_img_paths.append(resized_img_path)
                        
                        img_xl = XLImage(resized_img_path)
                        img_xl.width = 100
                        img_xl.height = 100
                        ws.add_image(img_xl, f"{col_letter_img}{image_row_idx_excel}")
                    except Exception as e_img:
                        st.error(f"处理图片时出错: {str(e_img)}")
                        pass # Ignore image adding errors

        # 添加AI卖点解析结果到Excel
        if selling_points_data:
            # 确定卖点开始的行号(直接跟在当前数据后面,不空行)
            selling_point_start_row = max_row_to_style + 1
            
            # 获取需要展示的卖点数量
            comparison_count = len(selling_points_data)
            
            # 创建A列合并单元格"AI卖点解析"
            # 计算需要合并的单元格数量
            merge_rows = comparison_count
            ws.merge_cells(start_row=selling_point_start_row, start_column=1, 
                          end_row=selling_point_start_row + merge_rows - 1, end_column=1)
         
            # 设置合并单元格的值和样式
            ai_cell = ws.cell(row=selling_point_start_row, column=1, value="AI卖点解析")
            ai_cell.font = Font(bold=True)
            ai_cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)

            # 为合并区域内的每个单元格设置边框,确保底部边框正确显示
            for i in range(merge_rows):
                row_idx = selling_point_start_row + i
                cell = ws.cell(row=row_idx, column=1)
                cell.border = thin_border
                
                # 特别强调底部单元格的底部边框
                if i == merge_rows - 1:  # 最后一行
                    bottom_border = Border(
                        left=Side(style='thin'),
                        right=Side(style='thin'),
                        top=Side(style='thin'),
                        bottom=Side(style='thin')  # 确保底部是实线
                    )
                    cell.border = bottom_border
            
            # 添加卖点到B列和后续列
            selected_asins = list(transposed_df.columns)
            
            for i, comparison_item in enumerate(selling_points_data):
                row_idx = selling_point_start_row + i
                sell_point = comparison_item.get("sellPoint", "")
                values = comparison_item.get("values", [])
                
                # B列为卖点名称
                ws.cell(row=row_idx, column=2, value=sell_point).font = Font(bold=True)
                ws.cell(row=row_idx, column=2).alignment = center_aligned
                ws.cell(row=row_idx, column=2).border = thin_border
                
                # 添加每个ASIN的卖点值,从C列开始
                for col_idx, asin in enumerate(selected_asins):
                    col_pos = col_idx + 3  # 数据从第三列(C列)开始
                    
                    if col_idx < len(values):
                        cell = ws.cell(row=row_idx, column=col_pos, value=values[col_idx])
                    else:
                        cell = ws.cell(row=row_idx, column=col_pos, value="")
                    
                    cell.alignment = Alignment(horizontal='left', vertical='center', wrap_text=True)
                    cell.border = thin_border
            
            # 调整卖点行高
            for i in range(comparison_count):
                row_idx = selling_point_start_row + i
                ws.row_dimensions[row_idx].height = 55  # 设置更高的行高以容纳卖点文本
        
        # 保存到内存中
        excel_buffer = io.BytesIO()
        wb.save(excel_buffer)
        excel_buffer.seek(0)
        
        # 在wb.save(excel_buffer)之后清理临时图片
        if "resized_img_paths" in locals():
            for path in resized_img_paths:
                if os.path.exists(path):
                    os.remove(path)
        
        return excel_buffer
        
    except Exception as e:
        print(f"Excel文件生成错误: {type(e).__name__}: {str(e)}")
        return None

uploaded_file = st.file_uploader("上传Excel文件(包含ASIN及产品信息的数据表)", type=["xlsx"], 
                                help="请上传包含ASIN列的Excel文件,文件应包含产品信息如品牌、价格、销量等数据。系统将自动提取嵌入的产品图片。")

if uploaded_file is not None:
    try:
        # 使用临时文件系统创建临时文件
        temp_fd, temp_file = tempfile.mkstemp(suffix=".xlsx")
        
        # 保存上传的文件到临时位置
        with os.fdopen(temp_fd, "wb") as f:
            f.write(uploaded_file.getvalue())
        
        # 读取Excel文件
        df = pd.read_excel(temp_file, engine='openpyxl')
        
        # 提取所有ASIN值
        asins = df['ASIN'].dropna().unique().tolist()
        
        # 创建文本输入框(手动输入,点击按钮后再触发)
        manual_asins_input = st.text_area(
            "请输入ASIN,每行一个",
            key="manual_asins_input",
            placeholder="每行一个 ASIN,例如:B0A12BC34D"
        )
        
        # 展示校验提示,但不在此处变更选择(避免频繁触发分析)
        if manual_asins_input:
            manual_asins = [asin.strip() for asin in manual_asins_input.split('\n') if asin.strip()]
            invalid_asins = [asin for asin in manual_asins if asin not in asins]
            if invalid_asins:
                st.warning(f"以下ASIN在数据中找不到: {', '.join(invalid_asins)}")
            elif st.session_state.get('current_asins'):
                st.success(f"成功找到 {len(st.session_state.current_asins)} 个有效ASIN")
        
        # 点击按钮才触发选择与分析
        if st.button("🚀 开始分析", type="primary"):
            s = st.session_state.get("manual_asins_input", "")
            manual_asins = [asin.strip() for asin in s.split('\n') if asin.strip()]
            invalid_asins = [asin for asin in manual_asins if asin not in asins]
            valid_asins = [asin for asin in manual_asins if asin in asins]
            
            if not s.strip():
                st.warning("请先输入 ASIN 再点击开始分析")
                st.session_state.current_asins = []
                st.session_state.analysis_requested = False
            elif not valid_asins:
                st.error("没有找到有效的ASIN,请检查输入")
                st.session_state.current_asins = []
                st.session_state.analysis_requested = False
            else:
                if invalid_asins:
                    st.warning(f"以下ASIN在数据中找不到: {', '.join(invalid_asins)}")
                st.success(f"成功找到 {len(valid_asins)} 个有效ASIN")
                # 设置当前选择并触发分析
                st.session_state.current_asins = valid_asins
                st.session_state.analysis_complete = False
                st.session_state.selling_points_data = {}
                st.session_state.excel_buffer = None
                st.session_state.basic_excel_buffer = None
                st.session_state.analysis_requested = True
        
        final_selected_asins = st.session_state.current_asins if st.session_state.current_asins else []
        
        if final_selected_asins:
            # 提取Excel文件中的图片
            try:
                asin_to_image = extract_images_from_excel(temp_file)
            except Exception as e:
                st.warning(f"处理图片时出现问题: {str(e)}")
                asin_to_image = {}
            
            # 过滤选中的ASIN数据
            filtered_df = df[df['ASIN'].isin(final_selected_asins)]

            # 创建一个空列表用于存储结果数据
            result_data = []
            
            # 定义基础列名 (这些是代码中特别处理的列)
            base_columns = ["图片", "品牌", "品牌链接", "卖家所属地", "ASIN", "大类排名", "小类排名", 
                            "近30天月销量", "近30天月销售额", "价格", "变体", "RV数量", "RV评分", 
                            "上架时间", "重量(g)", "尺寸(cm)"]
            
            # 设置显示列
            final_display_columns = base_columns[:]
            
            # 处理每个选中的ASIN
            for i, (idx, row) in enumerate(filtered_df.iterrows()):
                current_asin_val = row.get("ASIN", "") # Get raw ASIN value
                if not isinstance(current_asin_val, str): # Ensure ASIN is string
                    current_asin_val = str(current_asin_val)
                
                # 创建新行数据
                new_row = {}
                
                # 检查是否有对应的图片
                if current_asin_val in asin_to_image:
                    new_row["图片"] = asin_to_image[current_asin_val]
                else:
                    new_row["图片"] = "" # 图片为空字符串
                        
                # Helper function to get string value or empty if None/NaN
                def get_value_as_str_or_empty(r, k):
                    v = r.get(k)
                    return "" if pd.isna(v) else str(v)

                new_row["品牌"] = get_value_as_str_or_empty(row, "品牌")
                new_row["品牌链接"] = get_value_as_str_or_empty(row, "品牌链接")
                new_row["卖家所属地"] = get_value_as_str_or_empty(row, "卖家所属地")
                new_row["ASIN"] = current_asin_val # Already processed ASIN
                new_row["大类排名"] = get_value_as_str_or_empty(row, "大类BSR")
                new_row["小类排名"] = get_value_as_str_or_empty(row, "小类BSR")
                new_row["近30天月销量"] = get_value_as_str_or_empty(row, "月销量")
                
                # 处理月销售额 - 匹配开头
                monthly_sales_found = False
                for col in df.columns: # 使用更新后的df.columns
                    if "月销售额" in col:
                        val_ms = row.get(col)
                        new_row["近30天月销售额"] = "" if pd.isna(val_ms) else str(val_ms)
                        monthly_sales_found = True
                        break
                
                if not monthly_sales_found:
                    new_row["近30天月销售额"] = ""
                
                # 处理价格 - 匹配开头
                price_found = False
                for col in df.columns: # 使用更新后的df.columns
                    if "价格" in col:
                        val_price = row.get(col)
                        new_row["价格"] = "" if pd.isna(val_price) else str(val_price)
                        price_found = True
                        break
                
                if not price_found:
                    new_row["价格"] = ""
                
                new_row["变体"] = get_value_as_str_or_empty(row, "变体数")
                new_row["RV数量"] = get_value_as_str_or_empty(row, "评分数")
                new_row["RV评分"] = get_value_as_str_or_empty(row, "评分")
                new_row["上架时间"] = get_value_as_str_or_empty(row, "上架时间")
                
                # 处理重量 - 优先查找"重量.1"列,其次查找包含g的值
                weight_found = False
                # 优先查找"重量.1"列
                if "重量.1" in df.columns: # 使用更新后的df.columns
                    raw_weight_1 = row.get("重量.1")
                    value_w1 = "" if pd.isna(raw_weight_1) else str(raw_weight_1).strip()
                    if value_w1: # Check if non-empty after strip
                        new_row["重量(g)"] = value_w1
                        weight_found = True
                # 如果没找到,再查找所有包含"重量"且以g结尾的列
                if not weight_found:
                    for col in df.columns: # 使用更新后的df.columns
                        if "重量" in col:
                            raw_weight_col = row.get(col)
                            value_wc = "" if pd.isna(raw_weight_col) else str(raw_weight_col).strip()
                            if value_wc.lower().endswith("g"):
                                new_row["重量(g)"] = value_wc
                                weight_found = True
                                break
                if not weight_found:
                    new_row["重量(g)"] = ""
                
                # 处理尺寸 - 专门检查"体积.1"列
                size_found = False
                
                # 首先检查"体积.1"列
                if "体积.1" in df.columns: # 使用更新后的df.columns
                    raw_size_1 = row.get("体积.1")
                    value_s1 = "" if pd.isna(raw_size_1) else str(raw_size_1).strip()
                    if value_s1: # Check if non-empty after strip
                        new_row["尺寸(cm)"] = value_s1
                        size_found = True
                
                # 如果没找到,再搜索其他可能包含尺寸的列
                if not size_found:
                    for col in df.columns: # 使用更新后的df.columns
                        if any(term in col for term in ["尺寸", "体积"]):
                            raw_size_col = row.get(col)
                            value_sc = "" if pd.isna(raw_size_col) else str(raw_size_col).strip()
                            if "cm" in value_sc.lower() or " x " in value_sc.lower():
                                new_row["尺寸(cm)"] = value_sc
                                size_found = True
                                break
                
                if not size_found:
                    new_row["尺寸(cm)"] = ""
                
                # 将新行添加到结果列表
                result_data.append(new_row)
            
            # 创建结果DataFrame,使用final_display_columns确保包含新列且顺序正确
            result_df = pd.DataFrame(result_data, columns=final_display_columns)
            
            # 显示结果表格 - 使用转换为字符串的方式避免Arrow错误
            st.subheader("提取结果")
            
            # 将DataFrame转置,实现横向显示(第一列是标题)
            transposed_df = result_df.T
            
            # 将ASIN值作为列名
            transposed_df.columns = result_df['ASIN']
            
            # 使用st.dataframe显示结果 - 转换为字符串类型避免Arrow错误
            st.dataframe(transposed_df.astype(str))
            
            # 自动触发:生成AI卖点分析并生成Excel(无须点击)
            if st.session_state.get('analysis_requested', False):
                with st.spinner("正在分析产品卖点并生成Excel文件,请稍候..."):
                    # 显示进度条
                    progress_bar = st.progress(0)
                    status_text = st.empty()
                    
                    # 第一步:分析卖点
                    status_text.text("正在准备产品数据...")
                    progress_bar.progress(20)
                    
                    # 提取需要解析的ASIN数量
                    asin_count = len(filtered_df["ASIN"].dropna().unique())
                    status_text.text(f"正在解析 {asin_count} 个产品的卖点...")
                    progress_bar.progress(40)
                    
                    # 运行卖点解析
                    comparison_result = analyze_selling_points(filtered_df)
                    progress_bar.progress(70)
                    
                    if comparison_result:
                        st.session_state.selling_points_data = comparison_result
                        status_text.text(f"卖点解析完成!成功提取 {len(comparison_result)} 个卖点对比项")
                    else:
                        status_text.text("卖点解析未能返回有效结果,将生成不含卖点的Excel文件")
                        st.session_state.selling_points_data = {}
                    
                    # 第二步:生成Excel文件
                    status_text.text("正在生成Excel文件...")
                    progress_bar.progress(90)
                    
                    excel_buffer = generate_excel_file(
                        result_df, 
                        transposed_df, 
                        asin_to_image, 
                        st.session_state.selling_points_data
                    )
                    
                    if excel_buffer:
                        st.session_state.excel_buffer = excel_buffer
                        st.session_state.analysis_complete = True
                        progress_bar.progress(100)
                        status_text.text("✅ 分析完成!Excel文件已生成")
                    else:
                        progress_bar.progress(100)
                        status_text.text("❌ Excel文件生成失败")
                # 清除触发标记,避免重复分析
                st.session_state.analysis_requested = False
            
            # 显示卖点分析结果(如果已完成分析)
            if st.session_state.selling_points_data:
                st.success(f"✅ 成功解析 {len(st.session_state.selling_points_data)} 个卖点对比项")
                
                # 获取选中的ASIN列表
                selected_asins = list(transposed_df.columns)
                
                # 创建卖点展示表格
                comparison_columns = ["卖点"] + selected_asins
                comparison_rows = []
                
                for item in st.session_state.selling_points_data:
                    sell_point = item.get("sellPoint", "")
                    values = item.get("values", [])
                    
                    # 确保values长度与ASIN数量一致
                    while len(values) < len(selected_asins):
                        values.append("")
                        
                    row = [sell_point] + values[:len(selected_asins)]
                    comparison_rows.append(row)
                
                # 创建DataFrame
                comparison_df = pd.DataFrame(comparison_rows, columns=comparison_columns)
                
                # 显示卖点表格
                st.subheader("🎯 AI卖点对比")
                st.dataframe(comparison_df)
            
            # 提供下载按钮(如果Excel文件已生成)
            if st.session_state.excel_buffer is not None:
                st.download_button(
                    label="📥 下载Excel文件(包含AI卖点分析)",
                    data=st.session_state.excel_buffer,
                    file_name='竞品对比结果_含AI卖点分析.xlsx',
                    mime='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                    key="download_excel"
                )
            
            # 如果还没有进行分析,提供仅基础数据的下载选项
            elif not st.session_state.analysis_complete:
                # 生成基础Excel文件并存储到session_state
                if st.session_state.basic_excel_buffer is None:
                    with st.spinner("正在准备Excel文件..."):
                        try:
                            st.session_state.basic_excel_buffer = generate_excel_file(result_df, transposed_df, asin_to_image)
                            if st.session_state.basic_excel_buffer is None:
                                st.error("生成Excel文件失败,请检查数据格式")
                        except Exception as e:
                            st.error(f"生成Excel文件时出错: {str(e)}")
                            st.session_state.basic_excel_buffer = None
                
                # 提供直接下载按钮
                if st.session_state.basic_excel_buffer is not None:
                    st.download_button(
                        label="📋 下载表格结果",
                        data=st.session_state.basic_excel_buffer,
                        file_name='竞品对比结果_基础版.xlsx',
                        mime='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                        key="download_basic_direct",
                        type="primary"
                    )
                            
    except Exception as e:
        st.error(f"读取Excel文件时出错: {str(e)}")
        st.info("请确保上传的Excel文件格式正确且未损坏")
    finally:
        # 清理临时文件
        try:
            if 'temp_file' in locals() and os.path.exists(temp_file):
                os.remove(temp_file)
        except Exception as e:
            pass  # 忽略任何清理错误
else:
    st.info("请上传Excel文件以开始提取数据")