Spaces:
Sleeping
Sleeping
Upload 2 files
Browse filesFiles changed (2)
- app.pyAdded+504
- requirements.txtAdded+4
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504import streamlit as stimport pandas as pdimport openpyxlfrom PIL import Image as PILImageimport iofrom io import BytesIOimport osimport uuidfrom openpyxl.styles import Border, Side, Alignment, Fontfrom openpyxl.drawing.image import Image as XLImageimport zipfileimport tempfileimport shutilimport timefrom openpyxl.utils import get_column_letterfrom openpyxl.utils.cell import column_index_from_stringfrom openpyxl.utils.cell import coordinate_from_string
st.set_page_config(page_title="竞品对比", layout="wide")
st.title("竞品对比")
# 创建图片目录image_dir = "extracted_images"if not os.path.exists(image_dir): os.makedirs(image_dir)
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') # 获取所有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") 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") 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") 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文件", type=["xlsx"])
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') # 提取所有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)] # 创建一个空列表用于存储结果数据 result_data = [] # 处理每个选中的ASIN for i, (idx, row) in enumerate(filtered_df.iterrows()): current_asin = row.get("ASIN", "") if not isinstance(current_asin, str): current_asin = str(current_asin) # 确保ASIN是字符串 # 创建新行数据 new_row = {} # 检查是否有对应的图片 if current_asin in asin_to_image: new_row["图片"] = asin_to_image[current_asin] else: new_row["图片"] = "" # 提取其他字段并确保所有值都是字符串 new_row["品牌"] = str(row.get("品牌", "")) new_row["品牌链接"] = str(row.get("品牌链接", "")) new_row["ASIN"] = current_asin new_row["近30天月销量"] = str(row.get("月销量", "")) # 处理月销售额 - 匹配开头 monthly_sales_found = False for col in df.columns: if "月销售额" in col: new_row["近30天月销售额"] = str(row.get(col, "")) monthly_sales_found = True break if not monthly_sales_found: new_row["近30天月销售额"] = "" # 处理价格 - 匹配开头 price_found = False for col in df.columns: if "价格" in col: new_row["价格"] = str(row.get(col, "")) price_found = True break if not price_found: new_row["价格"] = "" new_row["变体"] = str(row.get("变体数", "")) new_row["RV数量"] = str(row.get("评分数", "")) new_row["RV评分"] = str(row.get("评分", "")) new_row["上架时间"] = str(row.get("上架时间", "")) # 处理重量 - 优先查找"重量.1"列,其次查找包含g的值 weight_found = False # 优先查找"重量.1"列 if "重量.1" in df.columns: value = str(row.get("重量.1", "")).strip() if value: new_row["重量(g)"] = value weight_found = True # 如果没找到,再查找所有包含"重量"且以g结尾的列 if not weight_found: for col in df.columns: if "重量" in col: value = str(row.get(col, "")).strip() if value.lower().endswith("g"): new_row["重量(g)"] = value weight_found = True break if not weight_found: new_row["重量(g)"] = "" # 处理尺寸 - 专门检查"体积.1"列 size_found = False # 首先检查"体积.1"列 if "体积.1" in df.columns: value = str(row.get("体积.1", "")).strip() if value: new_row["尺寸(cm)"] = value size_found = True # 如果没找到,再搜索其他可能包含尺寸的列 if not size_found: for col in df.columns: if any(term in col for term in ["尺寸", "体积"]): value = str(row.get(col, "")).strip() if "cm" in value.lower() or " x " in value.lower(): new_row["尺寸(cm)"] = value size_found = True break if not size_found: new_row["尺寸(cm)"] = "" # 将新行添加到结果列表 result_data.append(new_row) # 创建结果DataFrame columns = ["图片", "品牌", "品牌链接", "ASIN", "近30天月销量", "近30天月销售额", "价格", "变体", "RV数量", "RV评分", "上架时间", "重量(g)", "尺寸(cm)"] result_df = pd.DataFrame(result_data, columns=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 = "提取结果" # 合并A列和B列 for i in range(1, len(transposed_df.index) + 1): ws.merge_cells(f'A{i}:B{i}') # 写入标题行 - 写入到合并后的A列 for i, field in enumerate(transposed_df.index): # 写入到合并单元格的左上角单元格 ws.cell(row=i+1, column=1).value = field # 写入数据 - 每个ASIN一列,从第三列开始 for col_idx, asin in enumerate(transposed_df.columns): # 列标题是ASIN col_pos = col_idx + 3 # 第二列是字段名称,从第三列开始数据 # 写入每个字段的值,跳过"图片"行 for row_idx, field in enumerate(transposed_df.index): if field == "图片": continue # 不写入图片行的内容 cell = ws.cell(row=row_idx+1, 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) bold_font = Font(bold=True) # 遍历所有单元格设置边框和居中对齐 for row in ws.iter_rows(): for cell in row: cell.border = thin_border cell.alignment = center_aligned # 为合并后的字段名称(标题)设置加粗字体 for row_idx in range(1, len(transposed_df.index) + 1): # 由于A列和B列已合并,只需设置A列的字体 ws.cell(row=row_idx, column=1).font = bold_font # 设置ASIN行(列标题)加粗 for col_idx in range(3, len(transposed_df.columns) + 3): # 从第三列开始 ws.cell(row=list(transposed_df.index).index("ASIN") + 1, column=col_idx).font = bold_font # 调整列宽 ws.column_dimensions['A'].width = 8 # 合并列的一半 ws.column_dimensions['B'].width = 8 # 合并列的一半 # 对其他列设置固定宽度 for idx in range(2, len(transposed_df.columns) + 2): col_letter = openpyxl.utils.get_column_letter(idx + 1) # +1 因为数据从第三列开始 ws.column_dimensions[col_letter].width = 13 # 添加图片到Excel - 处理"图片"行 image_row_idx = list(transposed_df.index).index("图片") + 1 # +1 因为Excel行从1开始 # 设置行高以容纳图片 ws.row_dimensions[image_row_idx].height = 75 # 图片单元格行高为75 # 设置品牌链接行高为45 brand_link_row_idx = list(transposed_df.index).index("品牌链接") + 1 ws.row_dimensions[brand_link_row_idx].height = 45 # 添加"主要卖点对比"区域 - 在所有字段后面 last_row_idx = len(transposed_df.index) start_selling_point_row = last_row_idx + 1 # 直接在原有内容下方,不空行 # 只合并A列的单元格用于"主要卖点对比"标题 selling_point_range = f'A{start_selling_point_row}:A{start_selling_point_row+3}' ws.merge_cells(selling_point_range) # 设置"主要卖点对比"标题 selling_point_cell = ws.cell(row=start_selling_point_row, column=1) selling_point_cell.value = "主要卖点对比" selling_point_cell.font = Font(bold=True) selling_point_cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True) # 为合并单元格的所有边添加边框 # 注意:合并单元格的边框需要分别为每个被合并的单元格设置 for row_idx in range(start_selling_point_row, start_selling_point_row + 4): cell = ws.cell(row=row_idx, column=1) cell.border = thin_border # 为B列和其他列添加对应的空白单元格并设置样式 for col_idx in range(len(transposed_df.columns) + 1): # +1 包括B列 col_pos = col_idx + 2 # 从第二列(B列)开始 for row_offset in range(4): # 四行高度 row_idx = start_selling_point_row + row_offset cell = ws.cell(row=row_idx, column=col_pos) cell.value = "" # 空值 cell.border = thin_border # 使用已定义的边框样式 # 设置行高 for row_offset in range(4): row_idx = start_selling_point_row + row_offset ws.row_dimensions[row_idx].height = 30 # 设置合适的行高 # 在添加图片前,定义一个列表 resized_img_paths = [] # 为每个ASIN添加图片 for col_idx, asin in enumerate(transposed_df.columns): # 查找对应的图片路径 img_path = "" for row_data in result_data: if row_data['ASIN'] == asin and row_data['图片']: img_path = row_data['图片'] break if img_path and os.path.exists(img_path): try: # 计算图片应该放在哪一列,从第三列开始 col_pos = col_idx + 3 # 第二列是字段名称,从第三列开始数据 col_letter = openpyxl.utils.get_column_letter(col_pos) # 清除单元格中的��本值 cell = ws.cell(row=image_row_idx, column=col_pos) cell.value = None # 强制生成100x100白底图片,内容居中 max_size = (100, 100) pil_img = PILImage.open(img_path) pil_img.thumbnail(max_size, PILImage.LANCZOS) # 保持比例缩放到不超过100x100 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) # 添加图片到Excel img = XLImage(resized_img_path) img.width = 100 img.height = 100 # 设置图片位置 img_cell = f"{col_letter}{image_row_idx}" ws.add_image(img, img_cell) # 在for循环里,每次生成resized_img_path后 resized_img_paths.append(resized_img_path) except Exception as e: pass # 忽略添加图片时的错误 # 保存到内存中 excel_buffer = io.BytesIO() wb.save(excel_buffer) excel_buffer.seek(0) # 在wb.save(excel_buffer)之后 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文件以开始提取数据")1234streamlit
pandas
openpyxl
Pillowapp.pyAdded+504
requirements.txtAdded+4