Update app.py
Browse files14 unmodified lines151617181920212223242526272829303132333435363738394041424344276 unmodified lines32132232332432532612 unmodified lines339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388113 unmodified lines50250350450550650750850913 unmodified lines5235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807815 unmodified lines78778878979079179279379479579679779879980014 unmodified linesimport asyncioimport aiohttpfrom openpyxl.utils import get_column_letterst.set_page_config(page_title="竞品对比 AI版", layout="wide")st.title("竞品对比 AI版")# 检查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 linesexcept Exception as e:pass # 忽略任何清理错误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"])with tab1:# 创建多选组件selected_asins = st.multiselect("选择ASIN", asins)with tab2:# 创建文本输入框manual_asins_input = st.text_area("请输入ASIN,每行一个")# 解析输入的ASINmanual_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")# 合并两个选项卡中选择的ASINfinal_selected_asins = list(set(selected_asins + (manual_asins if 'manual_asins' in locals() 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 linesif 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("正在分析产品卖点,请稍候..."):# 显示进度条progress_bar = st.progress(0)status_text = st.empty()status_text.text("正在准备产品数据...")# 提取需要解析的ASIN数量asin_count = len(filtered_df["ASIN"].dropna().unique())status_text.text(f"正在解析 {asin_count} 个产品的卖点,这可能需要一些时间...")# 直接运行解析函数comparison_result = analyze_selling_points(filtered_df)# 更新进度progress_bar.progress(100)if comparison_result:status_text.text(f"卖点解析完成!成功提取 {len(comparison_result)} 个卖点对比项")selling_points_data = comparison_resultelse:status_text.text("卖点解析未能返回有效结果")# 显示卖点分析结果if selling_points_data:st.success(f"成功解析 {len(selling_points_data)} 个卖点对比项")# 获取选中的ASIN列表selected_asins = list(transposed_df.columns)# 创建卖点展示表格comparison_columns = ["卖点"] + selected_asinscomparison_rows = []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)# 创建DataFramecomparison_df = pd.DataFrame(comparison_rows, columns=comparison_columns)# 显示卖点表格st.subheader("AI卖点对比")st.dataframe(comparison_df)# 创建横向格式的Excel文件try:# 创建一个新的工作簿wb = openpyxl.Workbook()ws = wb.activews.title = "提取结果"# 写入标题行all_fields_in_transposed_df = transposed_df.index.tolist()current_excel_row_for_styling = 1for 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:Bcell_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 + 1if 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_dfmax_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) + 2for 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") + 1for c_idx in range(3, max_col_to_style + 1): # ASIN values start from column Cws.cell(row=asin_header_row_excel, column=c_idx).font = Font(bold=True)# 调整列宽ws.column_dimensions['A'].width = 10ws.column_dimensions['B'].width = 13 # For detailed parameter keysfor 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("图片") + 1ws.row_dimensions[image_row_idx_excel].height = 75# 设置品牌链接行高为45if "品牌链接" in transposed_df.index:brand_link_row_idx_excel = transposed_df.index.tolist().index("品牌链接") + 1ws.row_dimensions[brand_link_row_idx_excel].height = 45resized_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 + 3col_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 textmax_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) // 2paste_y = (max_size[1] - pil_img.height) // 2background.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 = 100img_xl.height = 100ws.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卖点解析结果到Excelif "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_countws.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 + icell = 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 + isell_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_alignedws.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 + iws.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)# 提供下载按钮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文件格式正确且未损坏")5 unmodified linesexcept Exception as e:pass # 忽略任何清理错误else:st.info("请上传Excel文件以开始提取数据")# 添加最终说明st.markdown("""---### 💡 提示* 支持从Excel中自动提取产品图片* 结果将以Excel横向对比表格形式展示,便于直观比较* AI卖点解析功能可自动提取产品的核心卖点,帮助您快速了解竞品优势* 卖点解析结果将在Excel文件底部展示,每个产品最多展示8个卖点""")14 unmodified lines1516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667276 unmodified lines34434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354412 unmodified lines557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602113 unmodified lines71671771871972072113 unmodified lines7357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498505 unmodified lines85685785885914 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版")# 初始化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。")# 创建图片目录image_dir = os.path.join(tempfile.gettempdir(), "extracted_images")if not os.path.exists(image_dir):276 unmodified linesexcept 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.activews.title = "提取结果"# 写入标题行all_fields_in_transposed_df = transposed_df.index.tolist()current_excel_row_for_styling = 1for 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:Bcell_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 + 1if 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_dfmax_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) + 2for 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") + 1for c_idx in range(3, max_col_to_style + 1): # ASIN values start from column Cws.cell(row=asin_header_row_excel, column=c_idx).font = Font(bold=True)# 调整列宽ws.column_dimensions['A'].width = 10ws.column_dimensions['B'].width = 13 # For detailed parameter keysfor 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("图片") + 1ws.row_dimensions[image_row_idx_excel].height = 75# 设置品牌链接行高为45if "品牌链接" in transposed_df.index:brand_link_row_idx_excel = transposed_df.index.tolist().index("品牌链接") + 1ws.row_dimensions[brand_link_row_idx_excel].height = 45resized_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 + 3col_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 textmax_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) // 2paste_y = (max_size[1] - pil_img.height) // 2background.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 = 100img_xl.height = 100ws.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卖点解析结果到Excelif selling_points_data:# 确定卖点开始的行号(直接跟在当前数据后面,不空行)selling_point_start_row = max_row_to_style + 1# 获取需要展示的卖点数量comparison_count = len(selling_points_data)# 创建A列合并单元格"AI卖点解析"# 计算需要合并的单元格数量merge_rows = comparison_countws.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 + icell = 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 + isell_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_alignedws.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 + iws.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_bufferexcept Exception as e:print(f"Excel文件生成错误: {type(e).__name__}: {str(e)}")return Noneuploaded_file = st.file_uploader("上传Excel文件(包含ASIN及产品信息的数据表)", type=["xlsx"],help="请上传包含ASIN列的Excel文件,文件应包含产品信息如品牌、价格、销量等数据。系统将自动提取嵌入的产品图片。")12 unmodified lines# 提取所有ASIN值asins = df['ASIN'].dropna().unique().tolist()# 创建文本输入框manual_asins_input = st.text_area("请输入ASIN,每行一个")# 添加生成表格按钮generate_button = st.button("🚀 开始", type="primary")# 只有点击按钮后才处理ASIN和生成表格if generate_button and 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 not valid_asins:st.error("没有找到有效的ASIN,请检查输入")else:st.success(f"成功找到 {len(valid_asins)} 个有效ASIN")final_selected_asins = valid_asins# 重置分析状态st.session_state.analysis_complete = Falsest.session_state.selling_points_data = {}st.session_state.excel_buffer = Nonest.session_state.basic_excel_buffer = Nonest.session_state.current_asins = final_selected_asinselif 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:asin_to_image = extract_images_from_excel(temp_file)except Exception as e:st.warning(f"处理图片时出现问题: {str(e)}")asin_to_image = {}# 过滤选中的ASIN数据113 unmodified linesif not size_found:new_row["尺寸(cm)"] = ""# 将新行添加到结果列表result_data.append(new_row)13 unmodified lines# 使用st.dataframe显示结果 - 转换为字符串类型避免Arrow错误st.dataframe(transposed_df.astype(str))# 合并的按钮:生成AI卖点分析并下载Excelif 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} 个产品的卖点...")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_resultstatus_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_bufferst.session_state.analysis_complete = Trueprogress_bar.progress(100)status_text.text("✅ 分析完成!Excel文件已生成")else:progress_bar.progress(100)status_text.text("❌ Excel文件生成失败")# 显示卖点分析结果(如果已完成分析)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_asinscomparison_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)# 创建DataFramecomparison_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_stateif 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文件格式正确且未损坏")5 unmodified linesexcept Exception as e:pass # 忽略任何清理错误else:st.info("请上传Excel文件以开始提取数据")
app.py+347-288