Spaces:
Sleeping
Sleeping
Gnanashri Kota Venkatesh commited on
Update app.py with feedback appv2 changes
Browse files
app.py
CHANGED
|
@@ -1,26 +1,30 @@
|
|
|
|
|
| 1 |
import os
|
| 2 |
import re
|
|
|
|
|
|
|
| 3 |
import tempfile
|
| 4 |
import zipfile
|
| 5 |
-
import streamlit as st
|
| 6 |
-
from pathlib import Path
|
| 7 |
from collections import defaultdict
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
from reportlab.lib.pagesizes import A4
|
|
|
|
| 9 |
from reportlab.platypus import (
|
| 10 |
-
SimpleDocTemplate, Table, TableStyle, Image as RLImage,
|
|
|
|
| 11 |
)
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
from PIL import Image as PILImage
|
| 15 |
-
import io
|
| 16 |
-
import shutil
|
| 17 |
-
import cv2
|
| 18 |
-
import pandas as pd
|
| 19 |
-
import numpy as np
|
| 20 |
-
|
| 21 |
# Configure Streamlit page
|
| 22 |
st.set_page_config(
|
| 23 |
-
page_title="Brand
|
| 24 |
page_icon="🔧",
|
| 25 |
layout="wide"
|
| 26 |
)
|
|
@@ -28,7 +32,10 @@ st.set_page_config(
|
|
| 28 |
# Defined file types
|
| 29 |
ALLOWED_IMAGE_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.bmp', '.gif', '.tiff', '.webp'}
|
| 30 |
ALLOWED_TEXT_EXTENSIONS = {'.txt', '.md', '.csv'}
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
# Helper functions from both files
|
| 34 |
def extract_zip_to_temp(uploaded_file):
|
|
@@ -621,7 +628,7 @@ def generate_two_section_pdf_report(input_folder, erste_marke=None):
|
|
| 621 |
|
| 622 |
def brand_renamer_tool():
|
| 623 |
st.header("Advanced Brand File Processor")
|
| 624 |
-
st.markdown("Automatically rename and organize brand assets with
|
| 625 |
|
| 626 |
# Initialize session state for persistent results
|
| 627 |
if 'processing_complete' not in st.session_state:
|
|
@@ -632,7 +639,6 @@ def brand_renamer_tool():
|
|
| 632 |
uploaded_file = st.file_uploader(
|
| 633 |
"Choose a ZIP file",
|
| 634 |
type=['zip'],
|
| 635 |
-
help="Upload a zip file containing your brand folders with assets."
|
| 636 |
)
|
| 637 |
|
| 638 |
# Reset processing state when new file is uploaded
|
|
@@ -840,21 +846,20 @@ def brand_renamer_tool():
|
|
| 840 |
""")
|
| 841 |
|
| 842 |
def pdf_generator_tool():
|
| 843 |
-
st.header("
|
| 844 |
-
st.markdown("Upload a zip file containing brand assets to generate
|
| 845 |
|
| 846 |
# Analysis method selection
|
| 847 |
analysis_method = st.radio(
|
| 848 |
-
"Choose
|
| 849 |
-
["
|
| 850 |
-
help="
|
| 851 |
)
|
| 852 |
|
| 853 |
# File upload
|
| 854 |
uploaded_file = st.file_uploader(
|
| 855 |
"Choose a ZIP file",
|
| 856 |
type=['zip'],
|
| 857 |
-
help="Upload a zip file containing your brand assets.",
|
| 858 |
key="pdf_zip_upload"
|
| 859 |
)
|
| 860 |
|
|
@@ -870,7 +875,7 @@ def pdf_generator_tool():
|
|
| 870 |
if len(items) == 1 and os.path.isdir(os.path.join(temp_dir, items[0])):
|
| 871 |
input_folder = os.path.join(temp_dir, items[0])
|
| 872 |
|
| 873 |
-
if analysis_method == "
|
| 874 |
# Original folder-based analysis
|
| 875 |
marken = erkenne_marken_aus_ordnern(input_folder)
|
| 876 |
|
|
@@ -910,7 +915,7 @@ def pdf_generator_tool():
|
|
| 910 |
)
|
| 911 |
|
| 912 |
else:
|
| 913 |
-
# Filename-based analysis
|
| 914 |
marken_set, renamed_files_by_folder_and_marke, all_files = analyze_files_by_filename(input_folder)
|
| 915 |
|
| 916 |
if not marken_set:
|
|
@@ -938,18 +943,19 @@ def pdf_generator_tool():
|
|
| 938 |
# Generate PDF button
|
| 939 |
if st.button("Generate PDF Report", type="primary"):
|
| 940 |
with st.spinner("Generating PDF report..."):
|
| 941 |
-
|
|
|
|
| 942 |
|
| 943 |
if error:
|
| 944 |
st.error(f"{error}")
|
| 945 |
elif pdf_buffer:
|
| 946 |
-
st.success("PDF report generated successfully!")
|
| 947 |
|
| 948 |
# Download button
|
| 949 |
st.download_button(
|
| 950 |
-
label="📥 Download PDF Report",
|
| 951 |
data=pdf_buffer.getvalue(),
|
| 952 |
-
file_name="
|
| 953 |
mime="application/pdf"
|
| 954 |
)
|
| 955 |
|
|
@@ -966,24 +972,895 @@ def pdf_generator_tool():
|
|
| 966 |
st.markdown("""
|
| 967 |
**How to use this tool:**
|
| 968 |
|
| 969 |
-
**
|
| 970 |
- Create folders named after your brands
|
| 971 |
- Place brand assets inside each brand folder
|
|
|
|
| 972 |
- Zip the entire structure
|
|
|
|
| 973 |
|
| 974 |
-
**
|
| 975 |
-
- Name your files with brand identifiers at the beginning (e.g., 'Brand1_asset.jpg', 'Brand2_document.pdf')
|
| 976 |
-
- Organize files in any folder structure
|
| 977 |
- The tool will extract brand names from filenames automatically
|
|
|
|
| 978 |
|
| 979 |
**Supported file types:**
|
| 980 |
- **Images:** JPG, JPEG, PNG, BMP, GIF, TIFF, WEBP
|
| 981 |
- **Text files:** TXT, MD, CSV
|
| 982 |
""")
|
| 983 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 984 |
def excel_extractor_tool():
|
| 985 |
st.header("Excel Image Extractor")
|
| 986 |
-
st.markdown("Upload Excel files (.xlsx) to extract embedded images from
|
| 987 |
|
| 988 |
# File upload for Excel files
|
| 989 |
uploaded_files = st.file_uploader(
|
|
@@ -991,49 +1868,133 @@ def excel_extractor_tool():
|
|
| 991 |
type=['xlsx'],
|
| 992 |
accept_multiple_files=True,
|
| 993 |
help="Upload one or more .xlsx files to extract embedded images.",
|
| 994 |
-
key="
|
| 995 |
)
|
| 996 |
|
| 997 |
if uploaded_files:
|
| 998 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 999 |
temp_dir = tempfile.mkdtemp()
|
| 1000 |
all_extracted_files = []
|
| 1001 |
total_images = 0
|
|
|
|
| 1002 |
|
| 1003 |
progress_bar = st.progress(0)
|
| 1004 |
status_text = st.empty()
|
| 1005 |
|
| 1006 |
for i, uploaded_file in enumerate(uploaded_files):
|
| 1007 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1008 |
progress_bar.progress((i + 1) / len(uploaded_files))
|
| 1009 |
|
| 1010 |
# Save uploaded file temporarily
|
| 1011 |
-
temp_xlsx_path = os.path.join(temp_dir,
|
| 1012 |
with open(temp_xlsx_path, 'wb') as f:
|
| 1013 |
f.write(uploaded_file.getbuffer())
|
| 1014 |
|
| 1015 |
# Create output directory for this file
|
| 1016 |
-
output_dir = os.path.join(temp_dir, f"{Path(
|
| 1017 |
os.makedirs(output_dir, exist_ok=True)
|
| 1018 |
|
| 1019 |
-
# Extract images
|
| 1020 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1021 |
|
| 1022 |
-
|
| 1023 |
-
|
| 1024 |
-
|
| 1025 |
-
st.success(f"Extracted {count} image(s) from {uploaded_file.name}")
|
| 1026 |
-
all_extracted_files.extend(extracted_files)
|
| 1027 |
-
total_images += count
|
| 1028 |
else:
|
| 1029 |
-
st.
|
| 1030 |
|
| 1031 |
status_text.empty()
|
| 1032 |
progress_bar.empty()
|
| 1033 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1034 |
if total_images > 0:
|
| 1035 |
st.success(f"Total: {total_images} images extracted from {len(uploaded_files)} file(s)")
|
| 1036 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1037 |
# Create zip file with all extracted images
|
| 1038 |
zip_buffer = io.BytesIO()
|
| 1039 |
with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
|
|
@@ -1048,47 +2009,19 @@ def excel_extractor_tool():
|
|
| 1048 |
st.download_button(
|
| 1049 |
label="Download All Extracted Images (ZIP)",
|
| 1050 |
data=zip_buffer.getvalue(),
|
| 1051 |
-
file_name="
|
| 1052 |
mime="application/zip"
|
| 1053 |
)
|
| 1054 |
-
|
| 1055 |
-
# Show preview of extracted images
|
| 1056 |
-
with st.expander("Preview Extracted Images"):
|
| 1057 |
-
cols = st.columns(3)
|
| 1058 |
-
col_idx = 0
|
| 1059 |
-
|
| 1060 |
-
for file_path in all_extracted_files[:12]: # Show max 12 images
|
| 1061 |
-
try:
|
| 1062 |
-
with cols[col_idx % 3]:
|
| 1063 |
-
img = PILImage.open(file_path)
|
| 1064 |
-
st.image(img, caption=os.path.basename(file_path), use_column_width =True)
|
| 1065 |
-
col_idx += 1
|
| 1066 |
-
except Exception as e:
|
| 1067 |
-
st.write(f"Could not preview {os.path.basename(file_path)}")
|
| 1068 |
-
|
| 1069 |
-
if len(all_extracted_files) > 12:
|
| 1070 |
-
st.info(f"Showing first 12 images. Total extracted: {len(all_extracted_files)}")
|
| 1071 |
|
| 1072 |
else:
|
| 1073 |
-
st.info("No images were found in the uploaded Excel file(s).")
|
| 1074 |
|
| 1075 |
else:
|
| 1076 |
-
st.info("
|
| 1077 |
|
| 1078 |
-
|
| 1079 |
-
with st.expander("📖 How to use Excel Image Extractor"):
|
| 1080 |
st.markdown("""
|
| 1081 |
-
|
| 1082 |
-
|
| 1083 |
-
1. Upload one or more Excel files (.xlsx format)
|
| 1084 |
-
2. The tool will scan for embedded images in the Excel files
|
| 1085 |
-
3. All found images will be extracted and made available for download
|
| 1086 |
-
4. Images are packaged in a ZIP file for easy download
|
| 1087 |
-
|
| 1088 |
-
**Note:**
|
| 1089 |
-
- Only .xlsx files are supported (not .xls)
|
| 1090 |
-
- Images must be embedded in the Excel file (not linked)
|
| 1091 |
-
- Common image formats (PNG, JPG, etc.) are extracted
|
| 1092 |
""")
|
| 1093 |
|
| 1094 |
def file_renamer_tool():
|
|
@@ -1099,7 +2032,7 @@ def file_renamer_tool():
|
|
| 1099 |
uploaded_file = st.file_uploader(
|
| 1100 |
"Choose a ZIP file",
|
| 1101 |
type=['zip'],
|
| 1102 |
-
help="Upload a zip file containing your brand folders with assets.",
|
| 1103 |
key="renamer_zip_upload"
|
| 1104 |
)
|
| 1105 |
|
|
@@ -1122,6 +2055,7 @@ def file_renamer_tool():
|
|
| 1122 |
# Process files
|
| 1123 |
total_files = 0
|
| 1124 |
processed_files = []
|
|
|
|
| 1125 |
|
| 1126 |
for subfolder in input_folder.iterdir():
|
| 1127 |
if subfolder.is_dir():
|
|
@@ -1136,10 +2070,21 @@ def file_renamer_tool():
|
|
| 1136 |
shutil.copy2(file, target_path)
|
| 1137 |
processed_files.append((file.name, new_name, markenname))
|
| 1138 |
total_files += 1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1139 |
|
| 1140 |
if total_files > 0:
|
| 1141 |
st.success(f"Successfully renamed and copied {total_files} files")
|
| 1142 |
|
|
|
|
|
|
|
|
|
|
| 1143 |
# Show preview
|
| 1144 |
with st.expander("📋 Preview renamed files"):
|
| 1145 |
preview_df = pd.DataFrame(
|
|
@@ -1194,21 +2139,12 @@ def file_renamer_tool():
|
|
| 1194 |
- Provide a zip file with all renamed files
|
| 1195 |
|
| 1196 |
**Supported file types:**
|
| 1197 |
-
- Images: JPG, JPEG, PNG, BMP, GIF, TIFF, WEBP
|
| 1198 |
-
- Text files: TXT, MD, CSV
|
|
|
|
| 1199 |
""")
|
| 1200 |
|
| 1201 |
-
def main():
|
| 1202 |
-
st.title("🔧 Brand Assets Tools")
|
| 1203 |
|
| 1204 |
-
tab1, tab2, tab3 = st.tabs(["PDF Report Generator", "Excel Image Extractor", "Brand File Renamer"])
|
| 1205 |
-
|
| 1206 |
-
with tab1:
|
| 1207 |
-
pdf_generator_tool()
|
| 1208 |
-
with tab2:
|
| 1209 |
-
excel_extractor_tool()
|
| 1210 |
-
with tab3:
|
| 1211 |
-
file_renamer_tool()
|
| 1212 |
|
| 1213 |
def white_to_transparent_tool():
|
| 1214 |
st.header("White Background to Transparent")
|
|
@@ -1289,7 +2225,8 @@ def white_to_transparent_tool():
|
|
| 1289 |
|
| 1290 |
# Save the processed image
|
| 1291 |
new_filename = os.path.splitext(uploaded_file.name)[0] + ".png"
|
| 1292 |
-
processed_path = os.path.join(temp_dir,
|
|
|
|
| 1293 |
result_img.save(processed_path)
|
| 1294 |
processed_files.append(processed_path)
|
| 1295 |
else:
|
|
@@ -1326,7 +2263,7 @@ def white_to_transparent_tool():
|
|
| 1326 |
for i, file_path in enumerate(processed_files[:6]): # Show max 6 images
|
| 1327 |
with cols[i % 3]:
|
| 1328 |
img = PILImage.open(file_path)
|
| 1329 |
-
st.image(img, caption=os.path.basename(file_path),
|
| 1330 |
|
| 1331 |
if len(processed_files) > 6:
|
| 1332 |
st.info(f"Showing first 6 images. Total processed: {len(processed_files)}")
|
|
@@ -1418,12 +2355,12 @@ def find_smallest_dimensions_tool():
|
|
| 1418 |
with col1:
|
| 1419 |
st.subheader("Smallest Width")
|
| 1420 |
st.write(f"Dimensions: {min_width} × {height_at_min_width} px")
|
| 1421 |
-
st.image(file_min_width, caption=os.path.basename(file_min_width),
|
| 1422 |
|
| 1423 |
with col2:
|
| 1424 |
st.subheader("Smallest Height")
|
| 1425 |
st.write(f"Dimensions: {width_at_min_height} × {min_height} px")
|
| 1426 |
-
st.image(file_min_height, caption=os.path.basename(file_min_height),
|
| 1427 |
else:
|
| 1428 |
st.warning("No valid image files found in the uploaded zip.")
|
| 1429 |
|
|
@@ -1611,7 +2548,7 @@ def resize_with_transparent_canvas_tool():
|
|
| 1611 |
for i, file_path in enumerate(sample_files):
|
| 1612 |
with cols[i % 3]:
|
| 1613 |
img = PILImage.open(file_path)
|
| 1614 |
-
st.image(img, caption=os.path.basename(file_path),
|
| 1615 |
|
| 1616 |
if processed_count > 6:
|
| 1617 |
st.info(f"Showing sample images. Total processed: {processed_count}")
|
|
@@ -1764,7 +2701,7 @@ def center_on_canvas_tool():
|
|
| 1764 |
for i, file_path in enumerate(sample_files):
|
| 1765 |
with cols[i % 3]:
|
| 1766 |
img = PILImage.open(file_path)
|
| 1767 |
-
st.image(img, caption=os.path.basename(file_path),
|
| 1768 |
|
| 1769 |
if processed_count > 6:
|
| 1770 |
st.info(f"Showing sample images. Total processed: {processed_count}")
|
|
@@ -2151,7 +3088,7 @@ def brand_renamer_tool():
|
|
| 2151 |
uploaded_file = st.file_uploader(
|
| 2152 |
"Choose a ZIP file",
|
| 2153 |
type=['zip'],
|
| 2154 |
-
|
| 2155 |
)
|
| 2156 |
|
| 2157 |
# Reset processing state when new file is uploaded
|
|
@@ -2354,14 +3291,14 @@ def main():
|
|
| 2354 |
st.title("🔧 Brand Assets Tools")
|
| 2355 |
|
| 2356 |
tab1, tab2, tab3, tab4, tab5, tab6, tab7, tab8 = st.tabs([
|
| 2357 |
-
"
|
| 2358 |
-
"
|
| 2359 |
-
"
|
| 2360 |
-
"
|
| 2361 |
"Find Smallest Dimensions",
|
| 2362 |
-
"Resize
|
| 2363 |
-
"
|
| 2364 |
-
"
|
| 2365 |
])
|
| 2366 |
|
| 2367 |
with tab1:
|
|
|
|
| 1 |
+
import io
|
| 2 |
import os
|
| 3 |
import re
|
| 4 |
+
import shutil
|
| 5 |
+
import struct
|
| 6 |
import tempfile
|
| 7 |
import zipfile
|
|
|
|
|
|
|
| 8 |
from collections import defaultdict
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
import cv2
|
| 11 |
+
import numpy as np
|
| 12 |
+
import pandas as pd
|
| 13 |
+
import streamlit as st
|
| 14 |
+
import xlrd
|
| 15 |
+
from PIL import Image as PILImage
|
| 16 |
+
from reportlab.lib import colors
|
| 17 |
from reportlab.lib.pagesizes import A4
|
| 18 |
+
from reportlab.lib.styles import getSampleStyleSheet
|
| 19 |
from reportlab.platypus import (
|
| 20 |
+
SimpleDocTemplate, Table, TableStyle, Image as RLImage,
|
| 21 |
+
Paragraph, Spacer, PageBreak, KeepInFrame
|
| 22 |
)
|
| 23 |
+
import xml.etree.ElementTree as ET
|
| 24 |
+
import openpyxl
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
# Configure Streamlit page
|
| 26 |
st.set_page_config(
|
| 27 |
+
page_title="Brand Asset Management Tools",
|
| 28 |
page_icon="🔧",
|
| 29 |
layout="wide"
|
| 30 |
)
|
|
|
|
| 32 |
# Defined file types
|
| 33 |
ALLOWED_IMAGE_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.bmp', '.gif', '.tiff', '.webp'}
|
| 34 |
ALLOWED_TEXT_EXTENSIONS = {'.txt', '.md', '.csv'}
|
| 35 |
+
ALLOWED_VIDEO_EXTENSIONS = {'.mp4', '.avi', '.mov', '.wmv', '.flv', '.mkv', '.webm', '.m4v', '.3gp', '.ogv'}
|
| 36 |
+
ALLOWED_AUDIO_EXTENSIONS = {'.mp3', '.wav', '.aac', '.flac', '.ogg', '.m4a', '.wma'}
|
| 37 |
+
ALL_ALLOWED_EXTENSIONS = ALLOWED_IMAGE_EXTENSIONS.union(ALLOWED_TEXT_EXTENSIONS).union(ALLOWED_VIDEO_EXTENSIONS).union(ALLOWED_AUDIO_EXTENSIONS)
|
| 38 |
+
|
| 39 |
|
| 40 |
# Helper functions from both files
|
| 41 |
def extract_zip_to_temp(uploaded_file):
|
|
|
|
| 628 |
|
| 629 |
def brand_renamer_tool():
|
| 630 |
st.header("Advanced Brand File Processor")
|
| 631 |
+
st.markdown("Automatically rename and organize brand assets with final names and outputs (pdf overview, excel output) for programming")
|
| 632 |
|
| 633 |
# Initialize session state for persistent results
|
| 634 |
if 'processing_complete' not in st.session_state:
|
|
|
|
| 639 |
uploaded_file = st.file_uploader(
|
| 640 |
"Choose a ZIP file",
|
| 641 |
type=['zip'],
|
|
|
|
| 642 |
)
|
| 643 |
|
| 644 |
# Reset processing state when new file is uploaded
|
|
|
|
| 846 |
""")
|
| 847 |
|
| 848 |
def pdf_generator_tool():
|
| 849 |
+
st.header("Asset Overview")
|
| 850 |
+
st.markdown("Upload a zip file containing brand assets to generate asset overview by brand")
|
| 851 |
|
| 852 |
# Analysis method selection
|
| 853 |
analysis_method = st.radio(
|
| 854 |
+
"Choose:",
|
| 855 |
+
["Overview by Brand", "Overview by Asset Type"],
|
| 856 |
+
help="Overview by Brand: assets are organized by brand folders (they do NOT include brandname_ (underscore \"_\") in filename) . Overview by Asset Type: assets are organized by blocks AND include brandname_ (underscore \"_\") in filename)"
|
| 857 |
)
|
| 858 |
|
| 859 |
# File upload
|
| 860 |
uploaded_file = st.file_uploader(
|
| 861 |
"Choose a ZIP file",
|
| 862 |
type=['zip'],
|
|
|
|
| 863 |
key="pdf_zip_upload"
|
| 864 |
)
|
| 865 |
|
|
|
|
| 875 |
if len(items) == 1 and os.path.isdir(os.path.join(temp_dir, items[0])):
|
| 876 |
input_folder = os.path.join(temp_dir, items[0])
|
| 877 |
|
| 878 |
+
if analysis_method == "Overview by Brand":
|
| 879 |
# Original folder-based analysis
|
| 880 |
marken = erkenne_marken_aus_ordnern(input_folder)
|
| 881 |
|
|
|
|
| 915 |
)
|
| 916 |
|
| 917 |
else:
|
| 918 |
+
# Filename-based analysis (Overview by Asset Type)
|
| 919 |
marken_set, renamed_files_by_folder_and_marke, all_files = analyze_files_by_filename(input_folder)
|
| 920 |
|
| 921 |
if not marken_set:
|
|
|
|
| 943 |
# Generate PDF button
|
| 944 |
if st.button("Generate PDF Report", type="primary"):
|
| 945 |
with st.spinner("Generating PDF report..."):
|
| 946 |
+
# Use the two-section report function for filename-based analysis
|
| 947 |
+
pdf_buffer, error = generate_two_section_pdf_report(input_folder, erste_marke)
|
| 948 |
|
| 949 |
if error:
|
| 950 |
st.error(f"{error}")
|
| 951 |
elif pdf_buffer:
|
| 952 |
+
st.success("PDF report generated successfully! (Contains two sections: by Brand and by Asset Type)")
|
| 953 |
|
| 954 |
# Download button
|
| 955 |
st.download_button(
|
| 956 |
+
label="📥 Download PDF Report (Two Sections)",
|
| 957 |
data=pdf_buffer.getvalue(),
|
| 958 |
+
file_name="IcAt_Overview by Brand and Asset Type.pdf",
|
| 959 |
mime="application/pdf"
|
| 960 |
)
|
| 961 |
|
|
|
|
| 972 |
st.markdown("""
|
| 973 |
**How to use this tool:**
|
| 974 |
|
| 975 |
+
**Overview by Brand:**
|
| 976 |
- Create folders named after your brands
|
| 977 |
- Place brand assets inside each brand folder
|
| 978 |
+
- Assets do NOT need brand names in their filenames
|
| 979 |
- Zip the entire structure
|
| 980 |
+
- Generates single-section PDF report organized by brand
|
| 981 |
|
| 982 |
+
**Overview by Asset Type:**
|
| 983 |
+
- Name your files with brand identifiers at the beginning followed by an underscore (e.g., 'Brand1_asset.jpg', 'Brand2_document.pdf')
|
| 984 |
+
- Organize files in any folder structure (blocks/categories)
|
| 985 |
- The tool will extract brand names from filenames automatically
|
| 986 |
+
- Generates two-section PDF report: Section 1 (by Asset Type/Block) and Section 2 (by Brand)
|
| 987 |
|
| 988 |
**Supported file types:**
|
| 989 |
- **Images:** JPG, JPEG, PNG, BMP, GIF, TIFF, WEBP
|
| 990 |
- **Text files:** TXT, MD, CSV
|
| 991 |
""")
|
| 992 |
|
| 993 |
+
|
| 994 |
+
|
| 995 |
+
def extract_images_from_xlsx_worksheet_specific(excel_file_path, output_dir, target_worksheet=None):
|
| 996 |
+
"""
|
| 997 |
+
Extract images from specific worksheet in .xlsx files
|
| 998 |
+
"""
|
| 999 |
+
extracted_files = []
|
| 1000 |
+
available_worksheets = []
|
| 1001 |
+
|
| 1002 |
+
try:
|
| 1003 |
+
# First, get worksheet information using openpyxl
|
| 1004 |
+
try:
|
| 1005 |
+
from openpyxl import load_workbook
|
| 1006 |
+
wb = load_workbook(excel_file_path, read_only=True)
|
| 1007 |
+
available_worksheets = wb.sheetnames
|
| 1008 |
+
wb.close()
|
| 1009 |
+
except ImportError:
|
| 1010 |
+
# Fallback: read worksheet names from zip structure
|
| 1011 |
+
with zipfile.ZipFile(excel_file_path, 'r') as z:
|
| 1012 |
+
try:
|
| 1013 |
+
workbook_xml = z.read('xl/workbook.xml').decode('utf-8')
|
| 1014 |
+
root = ET.fromstring(workbook_xml)
|
| 1015 |
+
sheets = root.findall('.//{http://schemas.openxmlformats.org/spreadsheetml/2006/main}sheet')
|
| 1016 |
+
available_worksheets = [sheet.get('name') for sheet in sheets]
|
| 1017 |
+
except:
|
| 1018 |
+
available_worksheets = ["Sheet1"] # Default fallback
|
| 1019 |
+
|
| 1020 |
+
with zipfile.ZipFile(excel_file_path, 'r') as z:
|
| 1021 |
+
# Get all relationships and media files
|
| 1022 |
+
worksheet_media_map = {}
|
| 1023 |
+
|
| 1024 |
+
# Parse worksheet relationships to find which images belong to which worksheet
|
| 1025 |
+
if target_worksheet and target_worksheet != "All worksheets":
|
| 1026 |
+
# Find the worksheet ID for the target worksheet
|
| 1027 |
+
target_sheet_id = None
|
| 1028 |
+
try:
|
| 1029 |
+
workbook_xml = z.read('xl/workbook.xml').decode('utf-8')
|
| 1030 |
+
root = ET.fromstring(workbook_xml)
|
| 1031 |
+
sheets = root.findall('.//{http://schemas.openxmlformats.org/spreadsheetml/2006/main}sheet')
|
| 1032 |
+
|
| 1033 |
+
for sheet in sheets:
|
| 1034 |
+
if sheet.get('name') == target_worksheet:
|
| 1035 |
+
target_sheet_id = sheet.get('sheetId')
|
| 1036 |
+
break
|
| 1037 |
+
except Exception as e:
|
| 1038 |
+
print(f"Error parsing workbook.xml: {e}")
|
| 1039 |
+
target_sheet_id = "1" # Default to first sheet
|
| 1040 |
+
|
| 1041 |
+
if target_sheet_id:
|
| 1042 |
+
# Parse worksheet relationships
|
| 1043 |
+
try:
|
| 1044 |
+
worksheet_rels_path = f'xl/worksheets/_rels/sheet{target_sheet_id}.xml.rels'
|
| 1045 |
+
if worksheet_rels_path not in z.namelist():
|
| 1046 |
+
# Try alternative naming
|
| 1047 |
+
worksheet_rels_path = f'xl/worksheets/_rels/sheet1.xml.rels'
|
| 1048 |
+
|
| 1049 |
+
if worksheet_rels_path in z.namelist():
|
| 1050 |
+
rels_xml = z.read(worksheet_rels_path).decode('utf-8')
|
| 1051 |
+
rels_root = ET.fromstring(rels_xml)
|
| 1052 |
+
|
| 1053 |
+
# Find image relationships
|
| 1054 |
+
relationships = rels_root.findall('.//{http://schemas.openxmlformats.org/package/2006/relationships}Relationship')
|
| 1055 |
+
worksheet_images = []
|
| 1056 |
+
|
| 1057 |
+
for rel in relationships:
|
| 1058 |
+
target_path = rel.get('Target')
|
| 1059 |
+
rel_type = rel.get('Type')
|
| 1060 |
+
|
| 1061 |
+
# Check if this is an image relationship
|
| 1062 |
+
if 'image' in rel_type.lower() and target_path:
|
| 1063 |
+
# Convert relative path to absolute path in zip
|
| 1064 |
+
if target_path.startswith('../'):
|
| 1065 |
+
img_path = 'xl/' + target_path[3:]
|
| 1066 |
+
else:
|
| 1067 |
+
img_path = f'xl/worksheets/{target_path}'
|
| 1068 |
+
|
| 1069 |
+
if img_path in z.namelist():
|
| 1070 |
+
worksheet_images.append(img_path)
|
| 1071 |
+
|
| 1072 |
+
# Extract only images from this worksheet
|
| 1073 |
+
count = 0
|
| 1074 |
+
for img_path in worksheet_images:
|
| 1075 |
+
filename = Path(img_path).name
|
| 1076 |
+
target_path = Path(output_dir) / f"ws_{target_worksheet}_{filename}"
|
| 1077 |
+
|
| 1078 |
+
with z.open(img_path) as source, open(target_path, 'wb') as target_file:
|
| 1079 |
+
shutil.copyfileobj(source, target_file)
|
| 1080 |
+
|
| 1081 |
+
extracted_files.append(str(target_path))
|
| 1082 |
+
count += 1
|
| 1083 |
+
|
| 1084 |
+
return count, extracted_files, None, available_worksheets
|
| 1085 |
+
|
| 1086 |
+
except Exception as e:
|
| 1087 |
+
print(f"Error parsing worksheet relationships: {e}")
|
| 1088 |
+
# Fall back to extracting all images
|
| 1089 |
+
pass
|
| 1090 |
+
|
| 1091 |
+
# If target_worksheet is "All worksheets" or parsing failed, extract all images
|
| 1092 |
+
media_files = [f for f in z.infolist() if f.filename.startswith("xl/media/")]
|
| 1093 |
+
count = 0
|
| 1094 |
+
|
| 1095 |
+
for file_info in media_files:
|
| 1096 |
+
filename = Path(file_info.filename).name
|
| 1097 |
+
if target_worksheet == "All worksheets":
|
| 1098 |
+
target_path = Path(output_dir) / filename
|
| 1099 |
+
else:
|
| 1100 |
+
target_path = Path(output_dir) / f"all_{filename}"
|
| 1101 |
+
|
| 1102 |
+
with z.open(file_info) as source, open(target_path, 'wb') as target_file:
|
| 1103 |
+
shutil.copyfileobj(source, target_file)
|
| 1104 |
+
|
| 1105 |
+
extracted_files.append(str(target_path))
|
| 1106 |
+
count += 1
|
| 1107 |
+
|
| 1108 |
+
return count, extracted_files, None, available_worksheets
|
| 1109 |
+
|
| 1110 |
+
except Exception as e:
|
| 1111 |
+
return 0, [], f"Error processing .xlsx file: {str(e)}", available_worksheets
|
| 1112 |
+
|
| 1113 |
+
|
| 1114 |
+
def extract_images_from_xls_worksheet_specific(xls_file_path, output_dir, target_worksheet=None):
|
| 1115 |
+
"""
|
| 1116 |
+
Extract images from .xls files with basic worksheet awareness
|
| 1117 |
+
Note: .xls format has limitations for precise worksheet-specific extraction
|
| 1118 |
+
"""
|
| 1119 |
+
extracted_files = []
|
| 1120 |
+
available_worksheets = []
|
| 1121 |
+
|
| 1122 |
+
try:
|
| 1123 |
+
# Get worksheet information
|
| 1124 |
+
try:
|
| 1125 |
+
import xlrd
|
| 1126 |
+
workbook = xlrd.open_workbook(xls_file_path, formatting_info=True)
|
| 1127 |
+
available_worksheets = workbook.sheet_names()
|
| 1128 |
+
|
| 1129 |
+
if target_worksheet and target_worksheet != "All worksheets" and target_worksheet in available_worksheets:
|
| 1130 |
+
# For .xls, we can only provide basic filtering
|
| 1131 |
+
# The binary extraction method extracts all images, but we can at least validate the worksheet exists
|
| 1132 |
+
sheet_index = available_worksheets.index(target_worksheet)
|
| 1133 |
+
print(f"Extracting from worksheet '{target_worksheet}' (index: {sheet_index})")
|
| 1134 |
+
except ImportError:
|
| 1135 |
+
available_worksheets = ["All worksheets"]
|
| 1136 |
+
except Exception as e:
|
| 1137 |
+
print(f"Error reading .xls worksheets: {e}")
|
| 1138 |
+
available_worksheets = ["Sheet1"]
|
| 1139 |
+
|
| 1140 |
+
# Use the comprehensive binary extraction method
|
| 1141 |
+
count, extracted_files, error = extract_ole_images_from_xls_comprehensive(xls_file_path, output_dir)
|
| 1142 |
+
|
| 1143 |
+
# Rename files to indicate worksheet limitation
|
| 1144 |
+
if target_worksheet and target_worksheet != "All worksheets" and count > 0:
|
| 1145 |
+
renamed_files = []
|
| 1146 |
+
for i, file_path in enumerate(extracted_files):
|
| 1147 |
+
old_path = Path(file_path)
|
| 1148 |
+
new_path = old_path.parent / f"xls_{target_worksheet}_{old_path.name}"
|
| 1149 |
+
try:
|
| 1150 |
+
os.rename(old_path, new_path)
|
| 1151 |
+
renamed_files.append(str(new_path))
|
| 1152 |
+
except:
|
| 1153 |
+
renamed_files.append(file_path) # Keep original if rename fails
|
| 1154 |
+
extracted_files = renamed_files
|
| 1155 |
+
|
| 1156 |
+
warning_msg = None
|
| 1157 |
+
if target_worksheet and target_worksheet != "All worksheets":
|
| 1158 |
+
warning_msg = f"Note: .xls format limitations - extracted images may be from multiple worksheets, not just '{target_worksheet}'"
|
| 1159 |
+
|
| 1160 |
+
return count, extracted_files, warning_msg, available_worksheets
|
| 1161 |
+
|
| 1162 |
+
except Exception as e:
|
| 1163 |
+
return 0, [], f"Error processing .xls file: {str(e)}", available_worksheets
|
| 1164 |
+
|
| 1165 |
+
|
| 1166 |
+
def extract_ole_images_from_xls_comprehensive(xls_file_path, output_dir):
|
| 1167 |
+
"""
|
| 1168 |
+
Comprehensive extraction of embedded images from .xls files
|
| 1169 |
+
"""
|
| 1170 |
+
extracted_files = []
|
| 1171 |
+
count = 0
|
| 1172 |
+
|
| 1173 |
+
try:
|
| 1174 |
+
# Read the entire file as binary
|
| 1175 |
+
with open(xls_file_path, 'rb') as f:
|
| 1176 |
+
data = f.read()
|
| 1177 |
+
|
| 1178 |
+
# Enhanced image signatures
|
| 1179 |
+
image_signatures = [
|
| 1180 |
+
(b'\xFF\xD8\xFF\xE0', b'\xFF\xD9', 'jpg', 4), # JFIF
|
| 1181 |
+
(b'\xFF\xD8\xFF\xE1', b'\xFF\xD9', 'jpg', 4), # EXIF
|
| 1182 |
+
(b'\xFF\xD8\xFF\xDB', b'\xFF\xD9', 'jpg', 4), # Standard JPEG
|
| 1183 |
+
(b'\x89PNG\r\n\x1A\n', b'IEND\xaeB`\x82', 'png', 8), # PNG
|
| 1184 |
+
(b'GIF87a', b'\x00\x3B', 'gif', 6), # GIF87a
|
| 1185 |
+
(b'GIF89a', b'\x00\x3B', 'gif', 6), # GIF89a
|
| 1186 |
+
(b'BM', None, 'bmp', 2), # BMP
|
| 1187 |
+
]
|
| 1188 |
+
|
| 1189 |
+
found_positions = set()
|
| 1190 |
+
|
| 1191 |
+
# Direct image signature search
|
| 1192 |
+
for start_sig, end_sig, ext, min_header_size in image_signatures:
|
| 1193 |
+
pos = 0
|
| 1194 |
+
while True:
|
| 1195 |
+
pos = data.find(start_sig, pos)
|
| 1196 |
+
if pos == -1:
|
| 1197 |
+
break
|
| 1198 |
+
|
| 1199 |
+
if pos in found_positions:
|
| 1200 |
+
pos += len(start_sig)
|
| 1201 |
+
continue
|
| 1202 |
+
|
| 1203 |
+
try:
|
| 1204 |
+
image_data = None
|
| 1205 |
+
|
| 1206 |
+
if ext == 'jpg':
|
| 1207 |
+
# JPEG extraction
|
| 1208 |
+
end_pos = pos + len(start_sig)
|
| 1209 |
+
while end_pos < len(data) - 1:
|
| 1210 |
+
if data[end_pos] == 0xFF and data[end_pos + 1] == 0xD9:
|
| 1211 |
+
end_pos += 2
|
| 1212 |
+
image_data = data[pos:end_pos]
|
| 1213 |
+
break
|
| 1214 |
+
end_pos += 1
|
| 1215 |
+
if end_pos - pos > 10 * 1024 * 1024: # 10MB max
|
| 1216 |
+
break
|
| 1217 |
+
|
| 1218 |
+
elif ext == 'png':
|
| 1219 |
+
# PNG extraction
|
| 1220 |
+
end_pos = data.find(end_sig, pos)
|
| 1221 |
+
if end_pos != -1:
|
| 1222 |
+
end_pos += len(end_sig)
|
| 1223 |
+
image_data = data[pos:end_pos]
|
| 1224 |
+
|
| 1225 |
+
elif ext == 'gif':
|
| 1226 |
+
# GIF extraction
|
| 1227 |
+
end_pos = data.find(end_sig, pos)
|
| 1228 |
+
if end_pos != -1:
|
| 1229 |
+
end_pos += len(end_sig)
|
| 1230 |
+
image_data = data[pos:end_pos]
|
| 1231 |
+
|
| 1232 |
+
elif ext == 'bmp':
|
| 1233 |
+
# BMP extraction
|
| 1234 |
+
if pos + 18 <= len(data):
|
| 1235 |
+
try:
|
| 1236 |
+
file_size = struct.unpack('<I', data[pos + 2:pos + 6])[0]
|
| 1237 |
+
if 54 <= file_size <= 50 * 1024 * 1024 and pos + file_size <= len(data):
|
| 1238 |
+
image_data = data[pos:pos + file_size]
|
| 1239 |
+
except struct.error:
|
| 1240 |
+
pass
|
| 1241 |
+
|
| 1242 |
+
# Validate and save image
|
| 1243 |
+
if image_data and len(image_data) >= min_header_size:
|
| 1244 |
+
if validate_and_save_image_improved(image_data, output_dir, ext, count):
|
| 1245 |
+
found_positions.add(pos)
|
| 1246 |
+
extracted_files.append(f"{output_dir}/extracted_image_{count + 1:03d}.{ext}")
|
| 1247 |
+
count += 1
|
| 1248 |
+
|
| 1249 |
+
except Exception as e:
|
| 1250 |
+
print(f"Error processing {ext} at position {pos}: {e}")
|
| 1251 |
+
|
| 1252 |
+
pos += 1
|
| 1253 |
+
|
| 1254 |
+
return count, extracted_files, None if count > 0 else "No images found using binary extraction"
|
| 1255 |
+
|
| 1256 |
+
except Exception as e:
|
| 1257 |
+
return 0, [], f"Error reading .xls file: {str(e)}"
|
| 1258 |
+
|
| 1259 |
+
|
| 1260 |
+
def validate_and_save_image_improved(image_data, output_dir, ext, count):
|
| 1261 |
+
"""
|
| 1262 |
+
Improved image validation and saving
|
| 1263 |
+
"""
|
| 1264 |
+
try:
|
| 1265 |
+
img_buffer = io.BytesIO(image_data)
|
| 1266 |
+
|
| 1267 |
+
with PILImage.open(img_buffer) as img:
|
| 1268 |
+
img.verify()
|
| 1269 |
+
|
| 1270 |
+
img_buffer.seek(0)
|
| 1271 |
+
with PILImage.open(img_buffer) as img:
|
| 1272 |
+
width, height = img.size
|
| 1273 |
+
|
| 1274 |
+
# Validate dimensions
|
| 1275 |
+
if width < 1 or height < 1 or width > 20000 or height > 20000:
|
| 1276 |
+
return False
|
| 1277 |
+
|
| 1278 |
+
if width * height < 16: # Less than 4x4 pixels
|
| 1279 |
+
return False
|
| 1280 |
+
|
| 1281 |
+
# Convert problematic modes
|
| 1282 |
+
if img.mode in ('P', 'LA'):
|
| 1283 |
+
img = img.convert('RGBA')
|
| 1284 |
+
elif img.mode == '1':
|
| 1285 |
+
img = img.convert('L')
|
| 1286 |
+
|
| 1287 |
+
# Handle transparency for JPEG
|
| 1288 |
+
if ext == 'jpg' and img.mode in ('RGBA', 'LA'):
|
| 1289 |
+
background = PILImage.new('RGB', img.size, (255, 255, 255))
|
| 1290 |
+
if img.mode == 'RGBA':
|
| 1291 |
+
background.paste(img, mask=img.split()[-1])
|
| 1292 |
+
else:
|
| 1293 |
+
background.paste(img.convert('RGBA'), mask=img.split()[-1])
|
| 1294 |
+
img = background
|
| 1295 |
+
|
| 1296 |
+
# Save image
|
| 1297 |
+
output_path = f"{output_dir}/extracted_image_{count + 1:03d}.{ext}"
|
| 1298 |
+
|
| 1299 |
+
if ext == 'jpg':
|
| 1300 |
+
img.save(output_path, 'JPEG', quality=95, optimize=True)
|
| 1301 |
+
elif ext == 'png':
|
| 1302 |
+
img.save(output_path, 'PNG', optimize=True)
|
| 1303 |
+
elif ext == 'gif':
|
| 1304 |
+
if img.mode != 'P':
|
| 1305 |
+
img = img.convert('P', palette=PILImage.ADAPTIVE)
|
| 1306 |
+
img.save(output_path, 'GIF', optimize=True)
|
| 1307 |
+
else:
|
| 1308 |
+
img.save(output_path)
|
| 1309 |
+
|
| 1310 |
+
return True
|
| 1311 |
+
|
| 1312 |
+
except Exception as e:
|
| 1313 |
+
print(f"Image validation failed: {e}")
|
| 1314 |
+
return False
|
| 1315 |
+
|
| 1316 |
+
|
| 1317 |
+
def extract_images_from_excel_with_worksheet_improved(excel_file_path, output_dir, target_worksheet=None):
|
| 1318 |
+
"""
|
| 1319 |
+
Main improved extraction function with proper worksheet support
|
| 1320 |
+
"""
|
| 1321 |
+
try:
|
| 1322 |
+
file_ext = Path(excel_file_path).suffix.lower()
|
| 1323 |
+
|
| 1324 |
+
if file_ext == '.xlsx':
|
| 1325 |
+
return extract_images_from_xlsx_worksheet_specific(excel_file_path, output_dir, target_worksheet)
|
| 1326 |
+
elif file_ext == '.xls':
|
| 1327 |
+
return extract_images_from_xls_worksheet_specific(excel_file_path, output_dir, target_worksheet)
|
| 1328 |
+
else:
|
| 1329 |
+
return 0, [], f"Unsupported file format: {file_ext}", []
|
| 1330 |
+
|
| 1331 |
+
except Exception as e:
|
| 1332 |
+
return 0, [], str(e), []
|
| 1333 |
+
|
| 1334 |
+
|
| 1335 |
+
def get_excel_worksheets(excel_file_path):
|
| 1336 |
+
"""Get list of worksheet names from Excel file"""
|
| 1337 |
+
try:
|
| 1338 |
+
file_ext = Path(excel_file_path).suffix.lower()
|
| 1339 |
+
|
| 1340 |
+
if file_ext == '.xlsx':
|
| 1341 |
+
try:
|
| 1342 |
+
from openpyxl import load_workbook
|
| 1343 |
+
wb = load_workbook(excel_file_path, read_only=True)
|
| 1344 |
+
worksheets = wb.sheetnames
|
| 1345 |
+
wb.close()
|
| 1346 |
+
return worksheets
|
| 1347 |
+
except ImportError:
|
| 1348 |
+
# Fallback method using zipfile
|
| 1349 |
+
with zipfile.ZipFile(excel_file_path, 'r') as z:
|
| 1350 |
+
try:
|
| 1351 |
+
workbook_xml = z.read('xl/workbook.xml').decode('utf-8')
|
| 1352 |
+
root = ET.fromstring(workbook_xml)
|
| 1353 |
+
sheets = root.findall('.//{http://schemas.openxmlformats.org/spreadsheetml/2006/main}sheet')
|
| 1354 |
+
return [sheet.get('name') for sheet in sheets]
|
| 1355 |
+
except:
|
| 1356 |
+
return ["Sheet1"]
|
| 1357 |
+
|
| 1358 |
+
elif file_ext == '.xls':
|
| 1359 |
+
try:
|
| 1360 |
+
import xlrd
|
| 1361 |
+
workbook = xlrd.open_workbook(excel_file_path)
|
| 1362 |
+
return workbook.sheet_names()
|
| 1363 |
+
except ImportError:
|
| 1364 |
+
return ["All worksheets"]
|
| 1365 |
+
|
| 1366 |
+
return []
|
| 1367 |
+
|
| 1368 |
+
except Exception:
|
| 1369 |
+
return []
|
| 1370 |
+
|
| 1371 |
+
def extract_images_from_xlsx_improved(xlsx_path, output_dir, target_sheets=None):
|
| 1372 |
+
"""
|
| 1373 |
+
Improved extraction of images from .xlsx files with proper sheet mapping
|
| 1374 |
+
"""
|
| 1375 |
+
try:
|
| 1376 |
+
extracted_files = []
|
| 1377 |
+
image_count = 0
|
| 1378 |
+
|
| 1379 |
+
with zipfile.ZipFile(xlsx_path, 'r') as zip_ref:
|
| 1380 |
+
# Get all files in the archive
|
| 1381 |
+
file_list = zip_ref.namelist()
|
| 1382 |
+
|
| 1383 |
+
# Find media files
|
| 1384 |
+
media_files = [f for f in file_list if f.startswith('xl/media/')]
|
| 1385 |
+
if not media_files:
|
| 1386 |
+
return 0, [], "No images found in the Excel file", []
|
| 1387 |
+
|
| 1388 |
+
# Get worksheet information
|
| 1389 |
+
sheet_mapping = {} # Maps sheet IDs to names
|
| 1390 |
+
sheet_rids = {} # Maps sheet names to rIds
|
| 1391 |
+
|
| 1392 |
+
if 'xl/workbook.xml' in file_list:
|
| 1393 |
+
with zip_ref.open('xl/workbook.xml') as f:
|
| 1394 |
+
content = f.read().decode('utf-8')
|
| 1395 |
+
import re
|
| 1396 |
+
# Extract sheet information
|
| 1397 |
+
sheet_matches = re.findall(r'<sheet name="([^"]+)" sheetId="(\d+)" r:id="(rId\d+)"', content)
|
| 1398 |
+
for name, sheet_id, r_id in sheet_matches:
|
| 1399 |
+
sheet_mapping[sheet_id] = name
|
| 1400 |
+
sheet_rids[name] = r_id
|
| 1401 |
+
|
| 1402 |
+
available_sheets = list(sheet_mapping.values())
|
| 1403 |
+
|
| 1404 |
+
# If target_sheets is None, extract from all sheets
|
| 1405 |
+
if target_sheets is None:
|
| 1406 |
+
target_sheets = available_sheets
|
| 1407 |
+
elif isinstance(target_sheets, str):
|
| 1408 |
+
target_sheets = [target_sheets] if target_sheets != "All worksheets" else available_sheets
|
| 1409 |
+
|
| 1410 |
+
# Map images to sheets by analyzing drawing relationships
|
| 1411 |
+
sheet_images = {} # Maps sheet names to their image files
|
| 1412 |
+
|
| 1413 |
+
# Check each worksheet for drawing relationships
|
| 1414 |
+
for sheet_id, sheet_name in sheet_mapping.items():
|
| 1415 |
+
if sheet_name not in target_sheets:
|
| 1416 |
+
continue
|
| 1417 |
+
|
| 1418 |
+
sheet_images[sheet_name] = []
|
| 1419 |
+
|
| 1420 |
+
# Look for drawing relationships for this sheet
|
| 1421 |
+
drawing_rels_file = f'xl/worksheets/_rels/sheet{sheet_id}.xml.rels'
|
| 1422 |
+
if drawing_rels_file not in file_list:
|
| 1423 |
+
# Try alternative naming patterns
|
| 1424 |
+
possible_names = [
|
| 1425 |
+
f'xl/worksheets/_rels/sheet{sheet_id}.xml.rels',
|
| 1426 |
+
f'xl/worksheets/_rels/sheet{int(sheet_id)}.xml.rels'
|
| 1427 |
+
]
|
| 1428 |
+
drawing_rels_file = None
|
| 1429 |
+
for possible in possible_names:
|
| 1430 |
+
if possible in file_list:
|
| 1431 |
+
drawing_rels_file = possible
|
| 1432 |
+
break
|
| 1433 |
+
|
| 1434 |
+
if drawing_rels_file:
|
| 1435 |
+
try:
|
| 1436 |
+
with zip_ref.open(drawing_rels_file) as f:
|
| 1437 |
+
rels_content = f.read().decode('utf-8')
|
| 1438 |
+
|
| 1439 |
+
# Find drawing references
|
| 1440 |
+
drawing_matches = re.findall(r'Target="([^"]*drawing\d+\.xml)"', rels_content)
|
| 1441 |
+
|
| 1442 |
+
for drawing_file in drawing_matches:
|
| 1443 |
+
drawing_path = f'xl/{drawing_file}'
|
| 1444 |
+
if drawing_path in file_list:
|
| 1445 |
+
# Now get the drawing relationships
|
| 1446 |
+
drawing_rels_path = drawing_path.replace('.xml', '.xml.rels').replace('xl/', 'xl/').replace('drawings/', 'drawings/_rels/')
|
| 1447 |
+
|
| 1448 |
+
if drawing_rels_path in file_list:
|
| 1449 |
+
with zip_ref.open(drawing_rels_path) as f:
|
| 1450 |
+
drawing_rels_content = f.read().decode('utf-8')
|
| 1451 |
+
|
| 1452 |
+
# Extract image references
|
| 1453 |
+
image_matches = re.findall(r'Target="([^"]*media/[^"]+)"', drawing_rels_content)
|
| 1454 |
+
for img_ref in image_matches:
|
| 1455 |
+
img_path = f'xl/drawings/{img_ref}' if not img_ref.startswith('../') else f'xl/{img_ref[3:]}'
|
| 1456 |
+
if img_path in file_list:
|
| 1457 |
+
sheet_images[sheet_name].append(img_path)
|
| 1458 |
+
except Exception as e:
|
| 1459 |
+
print(f"Error processing relationships for sheet {sheet_name}: {e}")
|
| 1460 |
+
|
| 1461 |
+
# If no sheet-specific images found, fall back to extracting all images
|
| 1462 |
+
if not any(sheet_images.values()):
|
| 1463 |
+
print("No sheet-specific images found, extracting all images")
|
| 1464 |
+
for sheet_name in target_sheets:
|
| 1465 |
+
sheet_images[sheet_name] = media_files.copy()
|
| 1466 |
+
|
| 1467 |
+
# Extract images for target sheets
|
| 1468 |
+
extracted_media = set() # Avoid duplicates
|
| 1469 |
+
|
| 1470 |
+
for sheet_name in target_sheets:
|
| 1471 |
+
if sheet_name in sheet_images:
|
| 1472 |
+
for media_file in sheet_images[sheet_name]:
|
| 1473 |
+
if media_file not in extracted_media:
|
| 1474 |
+
try:
|
| 1475 |
+
# Extract the image
|
| 1476 |
+
image_data = zip_ref.read(media_file)
|
| 1477 |
+
|
| 1478 |
+
# Get original filename and extension
|
| 1479 |
+
original_filename = os.path.basename(media_file)
|
| 1480 |
+
name, ext = os.path.splitext(original_filename)
|
| 1481 |
+
|
| 1482 |
+
# Create output filename with sheet context
|
| 1483 |
+
if len(target_sheets) > 1:
|
| 1484 |
+
output_filename = f"{sheet_name}_{original_filename}"
|
| 1485 |
+
else:
|
| 1486 |
+
output_filename = original_filename
|
| 1487 |
+
|
| 1488 |
+
output_path = os.path.join(output_dir, output_filename)
|
| 1489 |
+
|
| 1490 |
+
# Save the image
|
| 1491 |
+
with open(output_path, 'wb') as img_file:
|
| 1492 |
+
img_file.write(image_data)
|
| 1493 |
+
|
| 1494 |
+
extracted_files.append(output_path)
|
| 1495 |
+
extracted_media.add(media_file)
|
| 1496 |
+
image_count += 1
|
| 1497 |
+
|
| 1498 |
+
except Exception as e:
|
| 1499 |
+
print(f"Error extracting {media_file}: {e}")
|
| 1500 |
+
|
| 1501 |
+
return image_count, extracted_files, None, available_sheets
|
| 1502 |
+
|
| 1503 |
+
except Exception as e:
|
| 1504 |
+
return 0, [], f"Error processing Excel file: {str(e)}", []
|
| 1505 |
+
|
| 1506 |
+
|
| 1507 |
+
|
| 1508 |
+
def get_excel_worksheets_simple(excel_file_path):
|
| 1509 |
+
"""Get list of worksheet names from Excel file - simplified version"""
|
| 1510 |
+
try:
|
| 1511 |
+
file_ext = Path(excel_file_path).suffix.lower()
|
| 1512 |
+
|
| 1513 |
+
if file_ext == '.xlsx':
|
| 1514 |
+
try:
|
| 1515 |
+
workbook = openpyxl.load_workbook(excel_file_path, read_only=True)
|
| 1516 |
+
worksheets = workbook.sheetnames
|
| 1517 |
+
workbook.close()
|
| 1518 |
+
return worksheets
|
| 1519 |
+
except Exception:
|
| 1520 |
+
return ["Sheet1"] # Fallback
|
| 1521 |
+
|
| 1522 |
+
elif file_ext == '.xls':
|
| 1523 |
+
try:
|
| 1524 |
+
import xlrd
|
| 1525 |
+
workbook = xlrd.open_workbook(excel_file_path)
|
| 1526 |
+
return workbook.sheet_names()
|
| 1527 |
+
except ImportError:
|
| 1528 |
+
return ["Sheet1"] # Fallback instead of "All worksheets"
|
| 1529 |
+
except Exception:
|
| 1530 |
+
return ["Sheet1"]
|
| 1531 |
+
|
| 1532 |
+
return []
|
| 1533 |
+
|
| 1534 |
+
except Exception:
|
| 1535 |
+
return []
|
| 1536 |
+
|
| 1537 |
+
# Add the missing extract_ole_images_from_xls_comprehensive function that was referenced
|
| 1538 |
+
def extract_ole_images_from_xls_comprehensive(xls_file_path, output_dir):
|
| 1539 |
+
"""
|
| 1540 |
+
Comprehensive extraction of embedded images from .xls files using binary parsing
|
| 1541 |
+
"""
|
| 1542 |
+
extracted_files = []
|
| 1543 |
+
count = 0
|
| 1544 |
+
|
| 1545 |
+
try:
|
| 1546 |
+
# Read the entire file as binary
|
| 1547 |
+
with open(xls_file_path, 'rb') as f:
|
| 1548 |
+
data = f.read()
|
| 1549 |
+
|
| 1550 |
+
# Enhanced image signatures
|
| 1551 |
+
image_signatures = [
|
| 1552 |
+
(b'\xFF\xD8\xFF\xE0', b'\xFF\xD9', 'jpg', 4), # JFIF
|
| 1553 |
+
(b'\xFF\xD8\xFF\xE1', b'\xFF\xD9', 'jpg', 4), # EXIF
|
| 1554 |
+
(b'\xFF\xD8\xFF\xDB', b'\xFF\xD9', 'jpg', 4), # Standard JPEG
|
| 1555 |
+
(b'\x89PNG\r\n\x1A\n', b'IEND\xaeB`\x82', 'png', 8), # PNG
|
| 1556 |
+
(b'GIF87a', b'\x00\x3B', 'gif', 6), # GIF87a
|
| 1557 |
+
(b'GIF89a', b'\x00\x3B', 'gif', 6), # GIF89a
|
| 1558 |
+
(b'BM', None, 'bmp', 2), # BMP
|
| 1559 |
+
]
|
| 1560 |
+
|
| 1561 |
+
found_positions = set()
|
| 1562 |
+
|
| 1563 |
+
# Direct image signature search
|
| 1564 |
+
for start_sig, end_sig, ext, min_header_size in image_signatures:
|
| 1565 |
+
pos = 0
|
| 1566 |
+
while True:
|
| 1567 |
+
pos = data.find(start_sig, pos)
|
| 1568 |
+
if pos == -1:
|
| 1569 |
+
break
|
| 1570 |
+
|
| 1571 |
+
if pos in found_positions:
|
| 1572 |
+
pos += len(start_sig)
|
| 1573 |
+
continue
|
| 1574 |
+
|
| 1575 |
+
try:
|
| 1576 |
+
image_data = None
|
| 1577 |
+
|
| 1578 |
+
if ext == 'jpg':
|
| 1579 |
+
# JPEG extraction
|
| 1580 |
+
end_pos = pos + len(start_sig)
|
| 1581 |
+
while end_pos < len(data) - 1:
|
| 1582 |
+
if data[end_pos] == 0xFF and data[end_pos + 1] == 0xD9:
|
| 1583 |
+
end_pos += 2
|
| 1584 |
+
image_data = data[pos:end_pos]
|
| 1585 |
+
break
|
| 1586 |
+
end_pos += 1
|
| 1587 |
+
if end_pos - pos > 10 * 1024 * 1024: # 10MB max
|
| 1588 |
+
break
|
| 1589 |
+
|
| 1590 |
+
elif ext == 'png':
|
| 1591 |
+
# PNG extraction
|
| 1592 |
+
end_pos = data.find(end_sig, pos)
|
| 1593 |
+
if end_pos != -1:
|
| 1594 |
+
end_pos += len(end_sig)
|
| 1595 |
+
image_data = data[pos:end_pos]
|
| 1596 |
+
|
| 1597 |
+
elif ext == 'gif':
|
| 1598 |
+
# GIF extraction
|
| 1599 |
+
end_pos = data.find(end_sig, pos)
|
| 1600 |
+
if end_pos != -1:
|
| 1601 |
+
end_pos += len(end_sig)
|
| 1602 |
+
image_data = data[pos:end_pos]
|
| 1603 |
+
|
| 1604 |
+
elif ext == 'bmp':
|
| 1605 |
+
# BMP extraction
|
| 1606 |
+
if pos + 18 <= len(data):
|
| 1607 |
+
try:
|
| 1608 |
+
import struct
|
| 1609 |
+
file_size = struct.unpack('<I', data[pos + 2:pos + 6])[0]
|
| 1610 |
+
if 54 <= file_size <= 50 * 1024 * 1024 and pos + file_size <= len(data):
|
| 1611 |
+
image_data = data[pos:pos + file_size]
|
| 1612 |
+
except:
|
| 1613 |
+
pass
|
| 1614 |
+
|
| 1615 |
+
# Validate and save image
|
| 1616 |
+
if image_data and len(image_data) >= min_header_size:
|
| 1617 |
+
if validate_and_save_image_improved(image_data, output_dir, ext, count):
|
| 1618 |
+
found_positions.add(pos)
|
| 1619 |
+
extracted_files.append(f"{output_dir}/extracted_image_{count + 1:03d}.{ext}")
|
| 1620 |
+
count += 1
|
| 1621 |
+
|
| 1622 |
+
except Exception as e:
|
| 1623 |
+
print(f"Error processing {ext} at position {pos}: {e}")
|
| 1624 |
+
|
| 1625 |
+
pos += 1
|
| 1626 |
+
|
| 1627 |
+
return count, extracted_files, None if count > 0 else "No images found using binary extraction"
|
| 1628 |
+
|
| 1629 |
+
except Exception as e:
|
| 1630 |
+
return 0, [], f"Error reading .xls file: {str(e)}"
|
| 1631 |
+
|
| 1632 |
+
def validate_and_save_image_improved(image_data, output_dir, ext, count):
|
| 1633 |
+
"""
|
| 1634 |
+
Improved image validation and saving
|
| 1635 |
+
"""
|
| 1636 |
+
try:
|
| 1637 |
+
img_buffer = io.BytesIO(image_data)
|
| 1638 |
+
|
| 1639 |
+
with PILImage.open(img_buffer) as img:
|
| 1640 |
+
img.verify()
|
| 1641 |
+
|
| 1642 |
+
img_buffer.seek(0)
|
| 1643 |
+
with PILImage.open(img_buffer) as img:
|
| 1644 |
+
width, height = img.size
|
| 1645 |
+
|
| 1646 |
+
# Validate dimensions
|
| 1647 |
+
if width < 1 or height < 1 or width > 20000 or height > 20000:
|
| 1648 |
+
return False
|
| 1649 |
+
|
| 1650 |
+
if width * height < 16: # Less than 4x4 pixels
|
| 1651 |
+
return False
|
| 1652 |
+
|
| 1653 |
+
# Convert problematic modes
|
| 1654 |
+
if img.mode in ('P', 'LA'):
|
| 1655 |
+
img = img.convert('RGBA')
|
| 1656 |
+
elif img.mode == '1':
|
| 1657 |
+
img = img.convert('L')
|
| 1658 |
+
|
| 1659 |
+
# Handle transparency for JPEG
|
| 1660 |
+
if ext == 'jpg' and img.mode in ('RGBA', 'LA'):
|
| 1661 |
+
background = PILImage.new('RGB', img.size, (255, 255, 255))
|
| 1662 |
+
if img.mode == 'RGBA':
|
| 1663 |
+
background.paste(img, mask=img.split()[-1])
|
| 1664 |
+
else:
|
| 1665 |
+
background.paste(img.convert('RGBA'), mask=img.split()[-1])
|
| 1666 |
+
img = background
|
| 1667 |
+
|
| 1668 |
+
# Save image
|
| 1669 |
+
output_path = f"{output_dir}/extracted_image_{count + 1:03d}.{ext}"
|
| 1670 |
+
|
| 1671 |
+
if ext == 'jpg':
|
| 1672 |
+
img.save(output_path, 'JPEG', quality=95, optimize=True)
|
| 1673 |
+
elif ext == 'png':
|
| 1674 |
+
img.save(output_path, 'PNG', optimize=True)
|
| 1675 |
+
elif ext == 'gif':
|
| 1676 |
+
if img.mode != 'P':
|
| 1677 |
+
img = img.convert('P', palette=PILImage.ADAPTIVE)
|
| 1678 |
+
img.save(output_path, 'GIF', optimize=True)
|
| 1679 |
+
else:
|
| 1680 |
+
img.save(output_path)
|
| 1681 |
+
|
| 1682 |
+
return True
|
| 1683 |
+
|
| 1684 |
+
except Exception as e:
|
| 1685 |
+
print(f"Image validation failed: {e}")
|
| 1686 |
+
return False
|
| 1687 |
+
|
| 1688 |
+
def extract_images_from_xlsx_by_sheet(xlsx_path, output_dir, target_sheet=None):
|
| 1689 |
+
"""
|
| 1690 |
+
Extract images from .xlsx files with reliable sheet-specific extraction
|
| 1691 |
+
Uses openpyxl to directly access worksheet images
|
| 1692 |
+
"""
|
| 1693 |
+
try:
|
| 1694 |
+
extracted_files = []
|
| 1695 |
+
image_count = 0
|
| 1696 |
+
|
| 1697 |
+
# Load workbook with openpyxl
|
| 1698 |
+
workbook = openpyxl.load_workbook(xlsx_path, data_only=True)
|
| 1699 |
+
available_sheets = workbook.sheetnames
|
| 1700 |
+
|
| 1701 |
+
# Determine which sheets to process
|
| 1702 |
+
if target_sheet is None or target_sheet == "All worksheets":
|
| 1703 |
+
sheets_to_process = available_sheets
|
| 1704 |
+
else:
|
| 1705 |
+
sheets_to_process = [target_sheet] if target_sheet in available_sheets else []
|
| 1706 |
+
|
| 1707 |
+
if not sheets_to_process:
|
| 1708 |
+
workbook.close()
|
| 1709 |
+
return 0, [], "No valid sheets found to extract from", available_sheets
|
| 1710 |
+
|
| 1711 |
+
# Process each sheet
|
| 1712 |
+
for sheet_name in sheets_to_process:
|
| 1713 |
+
try:
|
| 1714 |
+
worksheet = workbook[sheet_name]
|
| 1715 |
+
|
| 1716 |
+
# Check if worksheet has any images
|
| 1717 |
+
if hasattr(worksheet, '_images') and worksheet._images:
|
| 1718 |
+
sheet_image_count = 0
|
| 1719 |
+
for image in worksheet._images:
|
| 1720 |
+
try:
|
| 1721 |
+
# Get image data
|
| 1722 |
+
if hasattr(image, '_data'):
|
| 1723 |
+
image_data = image._data()
|
| 1724 |
+
else:
|
| 1725 |
+
# Try alternative method
|
| 1726 |
+
continue
|
| 1727 |
+
|
| 1728 |
+
# Determine file extension from image format
|
| 1729 |
+
image_format = 'png' # default
|
| 1730 |
+
if hasattr(image, 'format') and image.format:
|
| 1731 |
+
image_format = image.format.lower()
|
| 1732 |
+
elif len(image_data) > 4:
|
| 1733 |
+
# Try to detect format from data
|
| 1734 |
+
if image_data[:4] == b'\x89PNG':
|
| 1735 |
+
image_format = 'png'
|
| 1736 |
+
elif image_data[:3] == b'\xFF\xD8\xFF':
|
| 1737 |
+
image_format = 'jpg'
|
| 1738 |
+
elif image_data[:6] == b'GIF87a' or image_data[:6] == b'GIF89a':
|
| 1739 |
+
image_format = 'gif'
|
| 1740 |
+
|
| 1741 |
+
# Create filename
|
| 1742 |
+
if len(sheets_to_process) > 1:
|
| 1743 |
+
filename = f"{sheet_name}_image_{sheet_image_count + 1:03d}.{image_format}"
|
| 1744 |
+
else:
|
| 1745 |
+
filename = f"image_{sheet_image_count + 1:03d}.{image_format}"
|
| 1746 |
+
|
| 1747 |
+
# Save image
|
| 1748 |
+
output_path = os.path.join(output_dir, filename)
|
| 1749 |
+
with open(output_path, 'wb') as f:
|
| 1750 |
+
f.write(image_data)
|
| 1751 |
+
|
| 1752 |
+
extracted_files.append(output_path)
|
| 1753 |
+
sheet_image_count += 1
|
| 1754 |
+
image_count += 1
|
| 1755 |
+
|
| 1756 |
+
except Exception as e:
|
| 1757 |
+
print(f"Error extracting image from {sheet_name}: {e}")
|
| 1758 |
+
continue
|
| 1759 |
+
|
| 1760 |
+
print(f"Extracted {sheet_image_count} images from sheet: {sheet_name}")
|
| 1761 |
+
|
| 1762 |
+
# Also check for drawing objects (alternative method)
|
| 1763 |
+
if hasattr(worksheet, 'drawing') and worksheet.drawing:
|
| 1764 |
+
for drawing in worksheet.drawing:
|
| 1765 |
+
if hasattr(drawing, '_images'):
|
| 1766 |
+
for img in drawing._images:
|
| 1767 |
+
try:
|
| 1768 |
+
# Similar extraction logic for drawing images
|
| 1769 |
+
if hasattr(img, '_data'):
|
| 1770 |
+
image_data = img._data()
|
| 1771 |
+
image_format = 'png'
|
| 1772 |
+
|
| 1773 |
+
if len(sheets_to_process) > 1:
|
| 1774 |
+
filename = f"{sheet_name}_drawing_{image_count + 1:03d}.{image_format}"
|
| 1775 |
+
else:
|
| 1776 |
+
filename = f"drawing_{image_count + 1:03d}.{image_format}"
|
| 1777 |
+
|
| 1778 |
+
output_path = os.path.join(output_dir, filename)
|
| 1779 |
+
with open(output_path, 'wb') as f:
|
| 1780 |
+
f.write(image_data)
|
| 1781 |
+
|
| 1782 |
+
extracted_files.append(output_path)
|
| 1783 |
+
image_count += 1
|
| 1784 |
+
|
| 1785 |
+
except Exception:
|
| 1786 |
+
continue
|
| 1787 |
+
|
| 1788 |
+
except Exception as e:
|
| 1789 |
+
print(f"Error processing sheet {sheet_name}: {e}")
|
| 1790 |
+
continue
|
| 1791 |
+
|
| 1792 |
+
workbook.close()
|
| 1793 |
+
|
| 1794 |
+
# If openpyxl method didn't find images, fall back to zip extraction
|
| 1795 |
+
if image_count == 0:
|
| 1796 |
+
return extract_images_from_xlsx_zip_method(xlsx_path, output_dir, target_sheet)
|
| 1797 |
+
|
| 1798 |
+
return image_count, extracted_files, None, available_sheets
|
| 1799 |
+
|
| 1800 |
+
except Exception as e:
|
| 1801 |
+
return extract_images_from_xlsx_zip_method(xlsx_path, output_dir, target_sheet)
|
| 1802 |
+
|
| 1803 |
+
def extract_images_from_xlsx_zip_method(xlsx_path, output_dir, target_sheet=None):
|
| 1804 |
+
"""
|
| 1805 |
+
Fallback method: Extract all images from xlsx using zip method
|
| 1806 |
+
"""
|
| 1807 |
+
try:
|
| 1808 |
+
extracted_files = []
|
| 1809 |
+
image_count = 0
|
| 1810 |
+
|
| 1811 |
+
with zipfile.ZipFile(xlsx_path, 'r') as zip_ref:
|
| 1812 |
+
# Get available sheets
|
| 1813 |
+
available_sheets = []
|
| 1814 |
+
try:
|
| 1815 |
+
with zip_ref.open('xl/workbook.xml') as f:
|
| 1816 |
+
content = f.read().decode('utf-8')
|
| 1817 |
+
sheet_matches = re.findall(r'<sheet name="([^"]+)"', content)
|
| 1818 |
+
available_sheets = [match for match in sheet_matches]
|
| 1819 |
+
except:
|
| 1820 |
+
available_sheets = ["Sheet1"]
|
| 1821 |
+
|
| 1822 |
+
# Find all media files
|
| 1823 |
+
media_files = [f for f in zip_ref.namelist() if f.startswith('xl/media/')]
|
| 1824 |
+
|
| 1825 |
+
if not media_files:
|
| 1826 |
+
return 0, [], "No images found in Excel file", available_sheets
|
| 1827 |
+
|
| 1828 |
+
# Extract all images (since precise sheet mapping is complex)
|
| 1829 |
+
for media_file in media_files:
|
| 1830 |
+
try:
|
| 1831 |
+
image_data = zip_ref.read(media_file)
|
| 1832 |
+
original_filename = os.path.basename(media_file)
|
| 1833 |
+
|
| 1834 |
+
# Create output filename
|
| 1835 |
+
if target_sheet and target_sheet != "All worksheets":
|
| 1836 |
+
output_filename = f"{target_sheet}_{original_filename}"
|
| 1837 |
+
else:
|
| 1838 |
+
output_filename = original_filename
|
| 1839 |
+
|
| 1840 |
+
output_path = os.path.join(output_dir, output_filename)
|
| 1841 |
+
|
| 1842 |
+
with open(output_path, 'wb') as f:
|
| 1843 |
+
f.write(image_data)
|
| 1844 |
+
|
| 1845 |
+
extracted_files.append(output_path)
|
| 1846 |
+
image_count += 1
|
| 1847 |
+
|
| 1848 |
+
except Exception as e:
|
| 1849 |
+
print(f"Error extracting {media_file}: {e}")
|
| 1850 |
+
continue
|
| 1851 |
+
|
| 1852 |
+
warning_msg = None
|
| 1853 |
+
if target_sheet and target_sheet != "All worksheets":
|
| 1854 |
+
warning_msg = f"Note: Extracted all images from file. Sheet-specific extraction not fully supported with this method."
|
| 1855 |
+
|
| 1856 |
+
return image_count, extracted_files, warning_msg, available_sheets
|
| 1857 |
+
|
| 1858 |
+
except Exception as e:
|
| 1859 |
+
return 0, [], f"Error processing Excel file: {str(e)}", []
|
| 1860 |
+
|
| 1861 |
def excel_extractor_tool():
|
| 1862 |
st.header("Excel Image Extractor")
|
| 1863 |
+
st.markdown("Upload Excel files (.xlsx) to extract embedded images from specific sheets.")
|
| 1864 |
|
| 1865 |
# File upload for Excel files
|
| 1866 |
uploaded_files = st.file_uploader(
|
|
|
|
| 1868 |
type=['xlsx'],
|
| 1869 |
accept_multiple_files=True,
|
| 1870 |
help="Upload one or more .xlsx files to extract embedded images.",
|
| 1871 |
+
key="excel_upload_fixed"
|
| 1872 |
)
|
| 1873 |
|
| 1874 |
if uploaded_files:
|
| 1875 |
+
# For each file, let user select sheets
|
| 1876 |
+
sheet_selections = {}
|
| 1877 |
+
|
| 1878 |
+
for uploaded_file in uploaded_files:
|
| 1879 |
+
# Temporarily save file to read sheet names
|
| 1880 |
+
temp_dir = tempfile.mkdtemp()
|
| 1881 |
+
temp_path = os.path.join(temp_dir, uploaded_file.name)
|
| 1882 |
+
|
| 1883 |
+
with open(temp_path, 'wb') as f:
|
| 1884 |
+
f.write(uploaded_file.getbuffer())
|
| 1885 |
+
|
| 1886 |
+
try:
|
| 1887 |
+
# Get available sheets using the simple function
|
| 1888 |
+
available_sheets = get_excel_worksheets_simple(temp_path)
|
| 1889 |
+
|
| 1890 |
+
if available_sheets:
|
| 1891 |
+
st.subheader(f"Select sheets from: {uploaded_file.name}")
|
| 1892 |
+
|
| 1893 |
+
# Add "All sheets" option
|
| 1894 |
+
all_options = ["All worksheets"] + available_sheets
|
| 1895 |
+
|
| 1896 |
+
selected = st.multiselect(
|
| 1897 |
+
f"Choose sheets to extract images from:",
|
| 1898 |
+
all_options,
|
| 1899 |
+
default=["All worksheets"],
|
| 1900 |
+
help="Select specific sheets or 'All worksheets' to extract from all sheets",
|
| 1901 |
+
key=f"sheets_fixed_{uploaded_file.name}"
|
| 1902 |
+
)
|
| 1903 |
+
|
| 1904 |
+
if "All worksheets" in selected:
|
| 1905 |
+
sheet_selections[uploaded_file.name] = available_sheets
|
| 1906 |
+
else:
|
| 1907 |
+
sheet_selections[uploaded_file.name] = [s for s in selected if s != "All worksheets"]
|
| 1908 |
+
else:
|
| 1909 |
+
st.warning(f"Could not read sheets from {uploaded_file.name}")
|
| 1910 |
+
sheet_selections[uploaded_file.name] = []
|
| 1911 |
+
|
| 1912 |
+
except Exception as e:
|
| 1913 |
+
st.error(f"Error reading {uploaded_file.name}: {str(e)}")
|
| 1914 |
+
sheet_selections[uploaded_file.name] = []
|
| 1915 |
+
|
| 1916 |
+
# Clean up
|
| 1917 |
+
try:
|
| 1918 |
+
os.remove(temp_path)
|
| 1919 |
+
os.rmdir(temp_dir)
|
| 1920 |
+
except:
|
| 1921 |
+
pass
|
| 1922 |
+
|
| 1923 |
+
if st.button("Extract Images", type="primary", key="extract_btn_fixed"):
|
| 1924 |
temp_dir = tempfile.mkdtemp()
|
| 1925 |
all_extracted_files = []
|
| 1926 |
total_images = 0
|
| 1927 |
+
extraction_results = []
|
| 1928 |
|
| 1929 |
progress_bar = st.progress(0)
|
| 1930 |
status_text = st.empty()
|
| 1931 |
|
| 1932 |
for i, uploaded_file in enumerate(uploaded_files):
|
| 1933 |
+
file_name = uploaded_file.name
|
| 1934 |
+
selected_sheets = sheet_selections.get(file_name, [])
|
| 1935 |
+
|
| 1936 |
+
if not selected_sheets:
|
| 1937 |
+
st.warning(f"No sheets selected for {file_name}, skipping...")
|
| 1938 |
+
continue
|
| 1939 |
+
|
| 1940 |
+
status_text.text(f"Processing {file_name}...")
|
| 1941 |
progress_bar.progress((i + 1) / len(uploaded_files))
|
| 1942 |
|
| 1943 |
# Save uploaded file temporarily
|
| 1944 |
+
temp_xlsx_path = os.path.join(temp_dir, file_name)
|
| 1945 |
with open(temp_xlsx_path, 'wb') as f:
|
| 1946 |
f.write(uploaded_file.getbuffer())
|
| 1947 |
|
| 1948 |
# Create output directory for this file
|
| 1949 |
+
output_dir = os.path.join(temp_dir, f"{Path(file_name).stem}_images")
|
| 1950 |
os.makedirs(output_dir, exist_ok=True)
|
| 1951 |
|
| 1952 |
+
# Extract images for each selected sheet individually
|
| 1953 |
+
file_total = 0
|
| 1954 |
+
for sheet_name in selected_sheets:
|
| 1955 |
+
sheet_output_dir = os.path.join(output_dir, sheet_name.replace('/', '_').replace('\\', '_'))
|
| 1956 |
+
os.makedirs(sheet_output_dir, exist_ok=True)
|
| 1957 |
+
|
| 1958 |
+
count, extracted_files, error, _ = extract_images_from_xlsx_by_sheet(
|
| 1959 |
+
temp_xlsx_path,
|
| 1960 |
+
sheet_output_dir,
|
| 1961 |
+
sheet_name
|
| 1962 |
+
)
|
| 1963 |
+
|
| 1964 |
+
if error:
|
| 1965 |
+
st.warning(f"Issue with {file_name} - {sheet_name}: {error}")
|
| 1966 |
+
|
| 1967 |
+
if count > 0:
|
| 1968 |
+
extraction_results.append(f"✅ {file_name} - {sheet_name}: {count} images")
|
| 1969 |
+
all_extracted_files.extend(extracted_files)
|
| 1970 |
+
file_total += count
|
| 1971 |
+
else:
|
| 1972 |
+
extraction_results.append(f"⚪ {file_name} - {sheet_name}: No images found")
|
| 1973 |
|
| 1974 |
+
total_images += file_total
|
| 1975 |
+
if file_total > 0:
|
| 1976 |
+
st.success(f"Extracted {file_total} images from {file_name}")
|
|
|
|
|
|
|
|
|
|
| 1977 |
else:
|
| 1978 |
+
st.info(f"No images found in {file_name}")
|
| 1979 |
|
| 1980 |
status_text.empty()
|
| 1981 |
progress_bar.empty()
|
| 1982 |
|
| 1983 |
+
# Show detailed extraction results
|
| 1984 |
+
with st.expander("Detailed Extraction Results"):
|
| 1985 |
+
for result in extraction_results:
|
| 1986 |
+
st.write(result)
|
| 1987 |
+
|
| 1988 |
if total_images > 0:
|
| 1989 |
st.success(f"Total: {total_images} images extracted from {len(uploaded_files)} file(s)")
|
| 1990 |
|
| 1991 |
+
# Show extracted files summary
|
| 1992 |
+
with st.expander("Extracted Files Summary"):
|
| 1993 |
+
for file_path in all_extracted_files[:20]: # Show first 20
|
| 1994 |
+
st.write(f"📄 {os.path.relpath(file_path, temp_dir)}")
|
| 1995 |
+
if len(all_extracted_files) > 20:
|
| 1996 |
+
st.info(f"Showing first 20 files. Total extracted: {len(all_extracted_files)}")
|
| 1997 |
+
|
| 1998 |
# Create zip file with all extracted images
|
| 1999 |
zip_buffer = io.BytesIO()
|
| 2000 |
with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
|
|
|
|
| 2009 |
st.download_button(
|
| 2010 |
label="Download All Extracted Images (ZIP)",
|
| 2011 |
data=zip_buffer.getvalue(),
|
| 2012 |
+
file_name="extracted_images_by_sheet.zip",
|
| 2013 |
mime="application/zip"
|
| 2014 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2015 |
|
| 2016 |
else:
|
| 2017 |
+
st.info("No images were found in the selected sheets of the uploaded Excel file(s).")
|
| 2018 |
|
| 2019 |
else:
|
| 2020 |
+
st.info("Please upload Excel file(s) to get started.")
|
| 2021 |
|
| 2022 |
+
with st.expander("Instructions"):
|
|
|
|
| 2023 |
st.markdown("""
|
| 2024 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2025 |
""")
|
| 2026 |
|
| 2027 |
def file_renamer_tool():
|
|
|
|
| 2032 |
uploaded_file = st.file_uploader(
|
| 2033 |
"Choose a ZIP file",
|
| 2034 |
type=['zip'],
|
| 2035 |
+
# help="Upload a zip file containing your brand folders with assets.",
|
| 2036 |
key="renamer_zip_upload"
|
| 2037 |
)
|
| 2038 |
|
|
|
|
| 2055 |
# Process files
|
| 2056 |
total_files = 0
|
| 2057 |
processed_files = []
|
| 2058 |
+
file_type_counts = {"images": 0, "text": 0, "videos": 0}
|
| 2059 |
|
| 2060 |
for subfolder in input_folder.iterdir():
|
| 2061 |
if subfolder.is_dir():
|
|
|
|
| 2070 |
shutil.copy2(file, target_path)
|
| 2071 |
processed_files.append((file.name, new_name, markenname))
|
| 2072 |
total_files += 1
|
| 2073 |
+
|
| 2074 |
+
# Count file types
|
| 2075 |
+
if file.suffix.lower() in ALLOWED_IMAGE_EXTENSIONS:
|
| 2076 |
+
file_type_counts["images"] += 1
|
| 2077 |
+
elif file.suffix.lower() in ALLOWED_TEXT_EXTENSIONS:
|
| 2078 |
+
file_type_counts["text"] += 1
|
| 2079 |
+
elif file.suffix.lower() in ALLOWED_VIDEO_EXTENSIONS:
|
| 2080 |
+
file_type_counts["videos"] += 1
|
| 2081 |
|
| 2082 |
if total_files > 0:
|
| 2083 |
st.success(f"Successfully renamed and copied {total_files} files")
|
| 2084 |
|
| 2085 |
+
# Show file type breakdown
|
| 2086 |
+
st.info(f"File types processed: {file_type_counts['images']} images, {file_type_counts['text']} text files, {file_type_counts['videos']} videos")
|
| 2087 |
+
|
| 2088 |
# Show preview
|
| 2089 |
with st.expander("📋 Preview renamed files"):
|
| 2090 |
preview_df = pd.DataFrame(
|
|
|
|
| 2139 |
- Provide a zip file with all renamed files
|
| 2140 |
|
| 2141 |
**Supported file types:**
|
| 2142 |
+
- **Images:** JPG, JPEG, PNG, BMP, GIF, TIFF, WEBP
|
| 2143 |
+
- **Text files:** TXT, MD, CSV
|
| 2144 |
+
- **Videos:** MP4, AVI, MOV, WMV, FLV, MKV, WEBM, M4V, 3GP, OGV
|
| 2145 |
""")
|
| 2146 |
|
|
|
|
|
|
|
| 2147 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2148 |
|
| 2149 |
def white_to_transparent_tool():
|
| 2150 |
st.header("White Background to Transparent")
|
|
|
|
| 2225 |
|
| 2226 |
# Save the processed image
|
| 2227 |
new_filename = os.path.splitext(uploaded_file.name)[0] + ".png"
|
| 2228 |
+
processed_path = os.path.join(temp_dir,
|
| 2229 |
+
new_filename)
|
| 2230 |
result_img.save(processed_path)
|
| 2231 |
processed_files.append(processed_path)
|
| 2232 |
else:
|
|
|
|
| 2263 |
for i, file_path in enumerate(processed_files[:6]): # Show max 6 images
|
| 2264 |
with cols[i % 3]:
|
| 2265 |
img = PILImage.open(file_path)
|
| 2266 |
+
st.image(img, caption=os.path.basename(file_path), use_container_width=True)
|
| 2267 |
|
| 2268 |
if len(processed_files) > 6:
|
| 2269 |
st.info(f"Showing first 6 images. Total processed: {len(processed_files)}")
|
|
|
|
| 2355 |
with col1:
|
| 2356 |
st.subheader("Smallest Width")
|
| 2357 |
st.write(f"Dimensions: {min_width} × {height_at_min_width} px")
|
| 2358 |
+
st.image(file_min_width, caption=os.path.basename(file_min_width), use_container_width =True)
|
| 2359 |
|
| 2360 |
with col2:
|
| 2361 |
st.subheader("Smallest Height")
|
| 2362 |
st.write(f"Dimensions: {width_at_min_height} × {min_height} px")
|
| 2363 |
+
st.image(file_min_height, caption=os.path.basename(file_min_height), use_container_width =True)
|
| 2364 |
else:
|
| 2365 |
st.warning("No valid image files found in the uploaded zip.")
|
| 2366 |
|
|
|
|
| 2548 |
for i, file_path in enumerate(sample_files):
|
| 2549 |
with cols[i % 3]:
|
| 2550 |
img = PILImage.open(file_path)
|
| 2551 |
+
st.image(img, caption=os.path.basename(file_path), use_container_width=True)
|
| 2552 |
|
| 2553 |
if processed_count > 6:
|
| 2554 |
st.info(f"Showing sample images. Total processed: {processed_count}")
|
|
|
|
| 2701 |
for i, file_path in enumerate(sample_files):
|
| 2702 |
with cols[i % 3]:
|
| 2703 |
img = PILImage.open(file_path)
|
| 2704 |
+
st.image(img, caption=os.path.basename(file_path), use_container_width=True)
|
| 2705 |
|
| 2706 |
if processed_count > 6:
|
| 2707 |
st.info(f"Showing sample images. Total processed: {processed_count}")
|
|
|
|
| 3088 |
uploaded_file = st.file_uploader(
|
| 3089 |
"Choose a ZIP file",
|
| 3090 |
type=['zip'],
|
| 3091 |
+
# help="Upload a zip file containing your brand folders with assets."
|
| 3092 |
)
|
| 3093 |
|
| 3094 |
# Reset processing state when new file is uploaded
|
|
|
|
| 3291 |
st.title("🔧 Brand Assets Tools")
|
| 3292 |
|
| 3293 |
tab1, tab2, tab3, tab4, tab5, tab6, tab7, tab8 = st.tabs([
|
| 3294 |
+
"Extract Images from Excel",
|
| 3295 |
+
"Name assets by brand",
|
| 3296 |
+
"Asset Overview",
|
| 3297 |
+
"Name stims by block + create output files",
|
| 3298 |
"Find Smallest Dimensions",
|
| 3299 |
+
"Resize",
|
| 3300 |
+
"Place on Canvas",
|
| 3301 |
+
"Canvas white to Transparent",
|
| 3302 |
])
|
| 3303 |
|
| 3304 |
with tab1:
|