File size: 34,590 Bytes
2d21f1c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
from openpyxl.utils import get_column_letter
from openpyxl.utils.cell import column_index_from_string
from openpyxl.utils.cell import coordinate_from_string
from collections import defaultdict

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

st.title("竞品对比")

# 添加应用说明
st.markdown("""
## 📊 功能介绍
本工具可帮助您分析不同产品的竞争情况,提取关键产品信息并进行横向对比。

### 📋 使用说明
1. 上传包含产品数据的Excel文件(.xlsx格式)(请使用卖家精灵导出的Top100数据)
2. 文件必须包含"ASIN"列以及其他产品信息(如品牌、价格、月销量等)
3. 选择要对比的ASIN(可从列表选择或手动输入)
4. 系统将自动提取关键数据并生成可下载的横向对比表格

### 📎 支持的数据列
品牌、品牌链接、卖家所属地、ASIN、大类排名、小类排名、月销量、月销售额、价格、变体数、评分数、评分、上架时间、重量、尺寸等
""")

# 创建图片目录
image_dir = "extracted_images"
if not os.path.exists(image_dir):
    os.makedirs(image_dir)

def parse_key_value_pairs(text):
    """解析键值对字符串,返回字典"""
    if pd.isna(text) or not isinstance(text, str): # 确保是字符串类型
        return {}
    pairs = [pair.strip() for pair in text.split("|")]
    result = {}
    for pair in pairs:
        if ":" in pair:
            key, value = pair.split(":", 1)
            result[key.strip()] = value.strip()
    return result

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 {}
        
        # 加载Excel以获取ASIN列
        df = pd.read_excel(excel_file_path, engine='openpyxl')
        
        # ------------- BEGIN NEW CODE INTEGRATION: 解析详细参数 -------------
        detailed_param_keys = [] # 用于存储从'详细参数'提取的列名
        if '详细参数' in df.columns and not df['详细参数'].isna().all():
            st.write("正在解析 '详细参数' 列...")
            all_keys_set = set()
            parsed_data_list = []
            
            for text_entry in df['详细参数'].astype(str): # 确保处理的是字符串
                if pd.isna(text_entry) or text_entry.lower() == 'nan' or not text_entry.strip():
                    parsed_pairs = {}
                else:
                    parsed_pairs = parse_key_value_pairs(text_entry)
                parsed_data_list.append(parsed_pairs)
                all_keys_set.update(parsed_pairs.keys())
            
            detailed_param_keys = sorted(list(all_keys_set))

            if detailed_param_keys:
                temp_new_data = defaultdict(list)
                for parsed_pairs_item in parsed_data_list:
                    for key_item in detailed_param_keys:
                        temp_new_data[key_item].append(parsed_pairs_item.get(key_item, None))
                
                for key_item in detailed_param_keys:
                    # 将解析出的列添加到df,如果列名已存在则覆盖
                    df[key_item] = pd.Series(temp_new_data[key_item], index=df.index)
                
                st.success(f"成功从 '详细参数' 提取并更新/添加了 {len(detailed_param_keys)} 个列。")
            else:
                st.info("'详细参数' 列中未找到可解析的键值对数据。")
        elif '详细参数' not in df.columns:
            st.info("上传的文件中未找到 '详细参数' 列,跳过解析。")
        # ------------- END NEW CODE INTEGRATION -------------
        
        # 获取所有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}"
                shutil.copy2(img_path, target_path)
                asin_to_image[asin] = target_path
        
        # 如果前面的方法没有成功提取所有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}"
                                    shutil.copy2(img_path, target_path)
                                    asin_to_image[asin] = target_path
            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}"
                    shutil.copy2(img_path, target_path)
                    asin_to_image[asin] = target_path
        
        return asin_to_image
        
    except Exception as e:
        return {}
    finally:
        # 清理临时文件
        shutil.rmtree(temp_dir)

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

if uploaded_file is not None:
    try:
        # 使用唯一文件名避免冲突
        unique_id = str(uuid.uuid4())
        temp_file = f"temp_upload_{unique_id}.xlsx"
        
        # 保存上传的文件到临时位置
        with open(temp_file, "wb") as f:
            f.write(uploaded_file.getvalue())
        
        # 读取Excel文件
        df = pd.read_excel(temp_file, engine='openpyxl')
        
        # ------------- BEGIN NEW CODE INTEGRATION: 解析详细参数 -------------
        detailed_param_keys = [] # 用于存储从'详细参数'提取的列名
        if '详细参数' in df.columns and not df['详细参数'].isna().all():
            st.write("正在解析 '详细参数' 列...")
            all_keys_set = set()
            parsed_data_list = []
            
            for text_entry in df['详细参数'].astype(str): # 确保处理的是字符串
                if pd.isna(text_entry) or text_entry.lower() == 'nan' or not text_entry.strip():
                    parsed_pairs = {}
                else:
                    parsed_pairs = parse_key_value_pairs(text_entry)
                parsed_data_list.append(parsed_pairs)
                all_keys_set.update(parsed_pairs.keys())
            
            detailed_param_keys = sorted(list(all_keys_set))

            if detailed_param_keys:
                temp_new_data = defaultdict(list)
                for parsed_pairs_item in parsed_data_list:
                    for key_item in detailed_param_keys:
                        temp_new_data[key_item].append(parsed_pairs_item.get(key_item, None))
                
                for key_item in detailed_param_keys:
                    # 将解析出的列添加到df,如果列名已存在则覆盖
                    df[key_item] = pd.Series(temp_new_data[key_item], index=df.index)
                
                st.success(f"成功从 '详细参数' 提取并更新/添加了 {len(detailed_param_keys)} 个列。")
            else:
                st.info("'详细参数' 列中未找到可解析的键值对数据。")
        elif '详细参数' not in df.columns:
            st.info("上传的文件中未找到 '详细参数' 列,跳过解析。")
        # ------------- END NEW CODE INTEGRATION -------------
        
        # 提取所有ASIN值
        asins = df['ASIN'].dropna().unique().tolist()
        
        # 创建两个选项卡
        tab1, tab2 = st.tabs(["从列表选择ASIN", "手动输入ASIN"])
        
        with tab1:
            # 创建多选组件
            selected_asins = st.multiselect("选择ASIN", asins)
        
        with tab2:
            # 创建文本输入框
            manual_asins_input = st.text_area("请输入ASIN,每行一个")
            
            # 解析输入的ASIN
            manual_asins = []
            if manual_asins_input:
                manual_asins = [asin.strip() for asin in manual_asins_input.split('\n') if asin.strip()]
                
                # 验证输入的ASIN是否存在于数据中
                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 invalid_asins:
                    st.error(f"以下ASIN在数据中找不到: {', '.join(invalid_asins)}")
                
                if valid_asins:
                    st.success(f"成功找到 {len(valid_asins)} 个有效ASIN")
        
        # 合并两个选项卡中选择的ASIN
        final_selected_asins = list(set(selected_asins + (manual_asins if 'manual_asins' in locals() else [])))
        
        if final_selected_asins:
            # 提取Excel文件中的图片
            try:
                asin_to_image = extract_images_from_excel(temp_file)
                st.success(f"成功提取 {len(asin_to_image)} 个ASIN对应的图片")
            except Exception as e:
                st.warning(f"处理图片时出现问题: {str(e)}")
                asin_to_image = {}
            
            # 过滤选中的ASIN数据
            filtered_df = df[df['ASIN'].isin(final_selected_asins)]
            
            # ------------- BEGIN FILTERING EMPTY DETAILED PARAMETERS FOR SELECTED ASINS -------------
            if detailed_param_keys and not filtered_df.empty:
                st.write(f"初步找到 {len(detailed_param_keys)} 个详细参数键。正在检查所选ASIN中的空值...")
                non_empty_detailed_param_keys_for_selected = []
                removed_keys_count = 0
                for dp_key in detailed_param_keys:
                    if dp_key in filtered_df.columns: # Key must exist in the filtered dataframe columns
                        is_empty_for_all_selected = True
                        # Check all values for this key in the filtered_df
                        for value_in_filtered_df in filtered_df[dp_key]:
                            if not (pd.isna(value_in_filtered_df) or str(value_in_filtered_df).strip() == ""):
                                is_empty_for_all_selected = False
                                break # Found a non-empty value, so this key is kept
                        
                        if not is_empty_for_all_selected:
                            non_empty_detailed_param_keys_for_selected.append(dp_key)
                        else:
                            # st.write(f"详细参数 \'{dp_key}\' 在所有选定ASIN中均为空,将不被包含在结果中。")
                            removed_keys_count += 1
                    # If dp_key is not in filtered_df.columns, it means it wasn't relevant or couldn't be processed earlier.
                    # It won't be included by default as subsequent logic relies on columns in filtered_df.
                
                if removed_keys_count > 0:
                    st.info(f"已移除 {removed_keys_count} 个在所选ASIN中值全为空的详细参数。")
                
                detailed_param_keys = non_empty_detailed_param_keys_for_selected # Update the list
            elif detailed_param_keys and filtered_df.empty:
                st.warning("没有选择任何有效的ASIN,或所选ASIN无数据,无法过滤详细参数。")
            # ------------- END FILTERING EMPTY DETAILED PARAMETERS -------------

            # 创建一个空列表用于存储结果数据
            result_data = []
            
            # 定义基础列名 (这些是代码中特别处理的列)
            base_columns = ["图片", "品牌", "品牌链接", "卖家所属地", "ASIN", "大类排名", "小类排名", 
                            "近30天月销量", "近30天月销售额", "价格", "变体", "RV数量", "RV评分", 
                            "上架时间", "重量(g)", "尺寸(cm)"]
            
            # 合并基础列和从'详细参数'提取的列,确保唯一性并保持顺序
            final_display_columns = base_columns[:]
            for key in detailed_param_keys:
                if key not in final_display_columns:
                    final_display_columns.append(key)
            
            # 处理每个选中的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)"] = ""

                # 添加从\'详细参数\'提取的列到new_row
                for key in detailed_param_keys:
                    val_dp = row.get(key)
                    new_row[key] = "" if pd.isna(val_dp) else str(val_dp)
                
                # 将新行添加到结果列表
                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))
            
            # 创建横向格式的Excel文件
            try:
                # 创建一个新的工作簿
                wb = openpyxl.Workbook()
                ws = wb.active
                ws.title = "提取结果"
                
                # --- BEGIN MODIFIED HEADER AND FIELD NAME WRITING ---
                all_fields_in_transposed_df = transposed_df.index.tolist()
                first_detailed_key_processed = False
                
                current_excel_row_for_styling = 1

                for field_name in all_fields_in_transposed_df:
                    if field_name not in detailed_param_keys:
                        # Standard field
                        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) # Standard fields are bold
                        current_excel_row_for_styling += 1
                    else:
                        # Detailed parameter key
                        if not first_detailed_key_processed:
                            start_dp_excel_row = current_excel_row_for_styling
                            num_dp_keys = len(detailed_param_keys)
                            # Ensure detailed_param_keys are contiguous as expected
                            actual_dp_keys_in_order = [f for f in all_fields_in_transposed_df if f in detailed_param_keys]
                            if len(actual_dp_keys_in_order) == num_dp_keys : # basic check
                                end_dp_excel_row = start_dp_excel_row + num_dp_keys - 1
                                ws.merge_cells(start_row=start_dp_excel_row, start_column=1, end_row=end_dp_excel_row, end_column=1) # Merge A column only
                                title_cell = ws.cell(row=start_dp_excel_row, column=1, value="详细参数")
                                title_cell.font = Font(bold=True)
                                title_cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
                            first_detailed_key_processed = True
                        
                        # Write the actual detailed parameter key in column B
                        ws.cell(row=current_excel_row_for_styling, column=2, value=field_name)
                        ws.row_dimensions[current_excel_row_for_styling].height = 25 # Set height for detailed param rows
                        current_excel_row_for_styling += 1
                # --- END MODIFIED HEADER AND FIELD NAME WRITING ---

                # 写入数据 - 每个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
                        # Apply general center alignment, specific cells can override
                        if not (c_idx == 1 and ws.cell(row=r_idx, column=c_idx).value == "详细参数"): # Avoid double-setting for merged title
                             cell.alignment = center_aligned
                
                # Specific styling for "详细参数" title already done (bold, alignment)
                # Standard field names in A:B are already bolded

                # 设置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 = openpyxl.utils.get_column_letter(idx_cw + 3) # Data columns C, D, ...
                    ws.column_dimensions[col_letter].width = 13
                
                # 添加图片到Excel - 处理"图片"行 (This logic should remain largely the same)
                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 = openpyxl.utils.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 = 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:
                                pass # Ignore image adding errors
                    # Image cleanup loop will be at the end

                # 保存到内存中
                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)
                
                # 提供下载按钮
                st.download_button(
                    label="下载Excel文件(横向格式)",
                    data=excel_buffer,
                    file_name='asin_extract_result_horizontal.xlsx',
                    mime='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                )
            except Exception as e:
                st.error(f"创建Excel文件时出错: {str(e)}")
                st.error(f"错误详情: {type(e).__name__}: {str(e)}")
    except Exception as e:
        st.error(f"读取Excel文件时出错: {str(e)}")
        st.info("请确保上传的Excel文件格式正确且未损坏")
    finally:
        # 清理临时文件 - 使用延迟和尝试多次删除
        try:
            if os.path.exists(temp_file):
                try:
                    os.remove(temp_file)
                except PermissionError:
                    # 如果文件被占用,等待一会儿再尝试
                    time.sleep(1)
                    try:
                        os.remove(temp_file)
                    except:
                        pass  # 忽略最终的错误
        except:
            pass  # 忽略任何清理错误
else:
    st.info("请上传Excel文件以开始提取数据")

# 添加最终说明
st.markdown("""
---
### 💡 提示
* 支持从Excel中自动提取产品图片
* 生成的对比表格包含"主要卖点对比"区域,方便您填写产品优势分析
* 结果将以Excel横向对比表格形式展示,便于直观比较
""")