Update app.py
Browse files14 unmodified lines1516171819202122232421252627282930313233343536373839404142434445464748495051525354555657585960616263642829303132333435363738394041656667276 unmodified lines34434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354412 unmodified lines557558559342343560561562345346347563564565349350351566567568569353354355356357358359360361362363364365366367368369570571572573574575576577578579580581582583584585586587588589590591592593594595596374597376377378379380381382598599385600601602113 unmodified lines71671771850550671972072113 unmodified lines7357367375265275285297387397407417427437447457467477487497505377517527535397547555415425437567577587597605477615495505515525537627637645555567657667677685585595607697707717727737747755625635645655665675685695705715725735745755765775787767777787797807817827837845805815825835845855865875885895905915925935945955965975985996006016026036046056066076087857867877886106116126136146156166177897907916196206216226236246256266276286296307927937947956326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297967977987997317327337348008018028037367377387397407417427437447457467477487497507517527537547557567577587597607618048058067637647657667678078088097698108118128138148158167717727738178188198208218228238248258268278288298308318327767777788338348358368378388398408418428438448458468478488498505 unmodified lines85685785879079179279379479579679779879980085914 unmodified linesimport asyncioimport aiohttpfrom openpyxl.utils import get_column_letterfrom dotenv import load_dotenv
# 加载 .env 文件中的环境变量load_dotenv()
st.set_page_config(page_title="竞品对比 AI版", layout="wide")
st.title("竞品对比 AI版")st.title("🔩 竞品对比 AI版")
# 初始化session_stateif '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 = Noneif 'basic_excel_buffer' not in st.session_state: st.session_state.basic_excel_buffer = Noneif 'analysis_complete' not in st.session_state: st.session_state.analysis_complete = Falseif 'current_asins' not in st.session_state: st.session_state.current_asins = []
# 显示教程图片按钮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。")
# 添加应用说明st.markdown("""## 📊 功能介绍本工具可帮助您分析不同产品的竞争情况,提取关键产品信息并进行横向对比。### 📋 使用说明1. 上传包含产品数据的Excel文件(.xlsx格式)(请使用卖家精灵导出的Top100数据)2. 文件必须包含"ASIN"列以及其他产品信息(如品牌、价格、月销量等)3. 选择要对比的ASIN(可从列表选择或手动输入)4. 系统将自动提取关键数据并生成可下载的横向对比表格5. 点击"解析产品卖点"按钮,使用AI自动分析产品卖点### 📎 支持的数据列品牌、品牌链接、卖家所属地、ASIN、大类排名、小类排名、月销量、月销售额、价格、变体数、评分数、评分、上架时间、重量、尺寸等""")
# 创建图片目录image_dir = os.path.join(tempfile.gettempdir(), "extracted_images")if not os.path.exists(image_dir):276 unmodified lines 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文件,文件应包含产品信息如品牌、价格、销量等数据。系统将自动提取嵌入的产品图片。")
12 unmodified lines # 提取所有ASIN值 asins = df['ASIN'].dropna().unique().tolist() # 创建两个选项卡 tab1, tab2 = st.tabs(["从列表选择ASIN", "手动输入ASIN"]) # 创建文本输入框 manual_asins_input = st.text_area("请输入ASIN,每行一个") with tab1: # 创建多选组件 selected_asins = st.multiselect("选择ASIN", asins) # 添加生成表格按钮 generate_button = st.button("🚀 开始", type="primary") with tab2: # 创建文本输入框 manual_asins_input = st.text_area("请输入ASIN,每行一个") # 只有点击按钮后才处理ASIN和生成表格 if generate_button and manual_asins_input: manual_asins = [asin.strip() for asin in manual_asins_input.split('\n') if asin.strip()] # 解析输入的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 []))) # 验证输入的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 not valid_asins: st.error("没有找到有效的ASIN,请检查输入") else: st.success(f"成功找到 {len(valid_asins)} 个有效ASIN") final_selected_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.current_asins = final_selected_asins elif generate_button and not manual_asins_input: st.warning("请先输入ASIN再点击生成按钮") final_selected_asins = [] else: final_selected_asins = st.session_state.current_asins if st.session_state.current_asins else [] if final_selected_asins: # 提取Excel文件中的图片 try: st.info(f"开始提取图片,临时目录: {tempfile.gettempdir()}") asin_to_image = extract_images_from_excel(temp_file) st.success(f"成功提取 {len(asin_to_image)} 个ASIN对应的图片") # 显示提取的图片路径 if asin_to_image: with st.expander("查看图片路径信息"): for asin, path in list(asin_to_image.items())[:5]: # 仅显示前5个 st.text(f"ASIN: {asin}, 图片路径: {path}, 文件存在: {os.path.exists(path)}") except Exception as e: st.warning(f"处理图片时出现问题: {str(e)}") st.warning(f"错误类型: {type(e).__name__}") asin_to_image = {} # 过滤选中的ASIN数据113 unmodified lines if not size_found: new_row["尺寸(cm)"] = ""
# 将新行添加到结果列表 result_data.append(new_row)13 unmodified lines # 使用st.dataframe显示结果 - 转换为字符串类型避免Arrow错误 st.dataframe(transposed_df.astype(str)) # 添加AI卖点解析按钮 selling_points_data = {} if st.button("解析产品卖点", key="analyze_selling_points"): with st.spinner("正在分析产品卖点,请稍候..."): # 合并的按钮:生成AI卖点分析并下载Excel if st.button("🤖 AI卖点分析", type="primary", key="analyze_and_download"): 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} 个产品的卖点,这可能需要一些时间...") status_text.text(f"正在解析 {asin_count} 个产品的卖点...") progress_bar.progress(40) # 直接运行解析函数 # 运行卖点解析 comparison_result = analyze_selling_points(filtered_df) # 更新进度 progress_bar.progress(100) progress_bar.progress(70) if comparison_result: st.session_state.selling_points_data = comparison_result status_text.text(f"卖点解析完成!成功提取 {len(comparison_result)} 个卖点对比项") selling_points_data = comparison_result else: status_text.text("卖点解析未能返回有效结果") # 显示卖点分析结果 if selling_points_data: st.success(f"成功解析 {len(selling_points_data)} 个卖点对比项") status_text.text("卖点解析未能返回有效结果,将生成不含卖点的Excel文件") st.session_state.selling_points_data = {} # 获取选中的ASIN列表 selected_asins = list(transposed_df.columns) # 第二步:生成Excel文件 status_text.text("正在生成Excel文件...") progress_bar.progress(90) # 创建卖点展示表格 comparison_columns = ["卖点"] + selected_asins comparison_rows = [] excel_buffer = generate_excel_file( result_df, transposed_df, asin_to_image, st.session_state.selling_points_data ) for item in 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) 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文件生成失败") # 创建横向格式的Excel文件 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]) # 显示卖点分析结果(如果已完成分析) if st.session_state.selling_points_data: st.success(f"✅ 成功解析 {len(st.session_state.selling_points_data)} 个卖点对比项") # 设置单元格样式 (全局边框和居中) 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) # 获取选中的ASIN列表 selected_asins = list(transposed_df.columns) # 遍历所有相关单元格设置边框和居中对齐 # 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 # 创建卖点展示表格 comparison_columns = ["卖点"] + selected_asins comparison_rows = [] # 标题已经设置为加粗
# 设置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 # Image cleanup loop will be at the end
# 添加AI卖点解析结果到Excel if "selling_points_data" in locals() and 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 item in st.session_state.selling_points_data: sell_point = item.get("sellPoint", "") values = item.get("values", []) 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", []) # 确保values长度与ASIN数量一致 while len(values) < len(selected_asins): values.append("") # 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) row = [sell_point] + values[:len(selected_asins)] comparison_rows.append(row) # 在wb.save(excel_buffer)之后清理临时图片 if "resized_img_paths" in locals(): for path in resized_img_paths: if os.path.exists(path): os.remove(path) # 创建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文件(横向格式)", data=excel_buffer, file_name='asin_extract_result_horizontal.xlsx', 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.error(f"错误详情: {type(e).__name__}: {str(e)}") 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文件格式正确且未损坏")5 unmodified lines except Exception as e: pass # 忽略任何清理错误else: st.info("请上传Excel文件以开始提取数据")
# 添加最终说明st.markdown("""---### 💡 提示* 支持从Excel中自动提取产品图片* 结果将以Excel横向对比表格形式展示,便于直观比较* AI卖点解析功能可自动提取产品的核心卖点,帮助您快速了解竞品优势* 卖点解析结果将在Excel文件底部展示,每个产品最多展示8个卖点""") st.info("请上传Excel文件以开始提取数据")app.py+347-288