Spaces:
Sleeping
Sleeping
Gnanashri Kota Venkatesh commited on
Refactor brand extraction and improve error handling
Browse filesImproved brand extraction logic and added error handling for image processing. Enhanced comments for clarity and fixed issues with file handling.
helper.py
CHANGED
|
@@ -115,9 +115,22 @@ def process_files(input_folder, marken_index, output_root):
|
|
| 115 |
|
| 116 |
files_to_process = []
|
| 117 |
for file in sorted(subfolder.iterdir()):
|
| 118 |
-
|
|
|
|
| 119 |
continue
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
marke = extract_brand(file.stem)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
brand_counters[marke] += 1
|
| 122 |
files_to_process.append((file, marke))
|
| 123 |
|
|
@@ -127,6 +140,11 @@ def process_files(input_folder, marken_index, output_root):
|
|
| 127 |
brand_counters[marke] += 1 # Increment counter for this brand
|
| 128 |
count_str = f"{brand_counters[marke]:02d}" # Format as 01, 02, 03, etc.
|
| 129 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
markennummer = marken_index[marke]
|
| 131 |
cleaned = get_cleaned_filename_without_brand(file.name, marke)
|
| 132 |
|
|
@@ -134,11 +152,15 @@ def process_files(input_folder, marken_index, output_root):
|
|
| 134 |
ziel = output_root / neuer_name
|
| 135 |
|
| 136 |
if file.suffix.lower() in ALLOWED_IMAGE_EXTENSIONS:
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
img.
|
| 140 |
-
|
| 141 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
else:
|
| 143 |
shutil.copy2(file, ziel)
|
| 144 |
|
|
@@ -564,9 +586,32 @@ def extract_images_from_xlsx(xlsx_file, output_dir):
|
|
| 564 |
return 0, [], str(e)
|
| 565 |
|
| 566 |
def extract_brand(file_stem):
|
| 567 |
-
"""Extract brand name from filename using pattern matching"""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 568 |
parts = re.split(r'[ _\-]', file_stem)
|
| 569 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 570 |
|
| 571 |
def erkenne_marken_aus_ordnern(input_folder):
|
| 572 |
"""Recognize brands from subfolders (original method)"""
|
|
@@ -785,7 +830,7 @@ def add_brand_pages(elements, marken_spalten, renamed_files_by_folder_and_marke)
|
|
| 785 |
elements.append(table)
|
| 786 |
|
| 787 |
def analyze_files_by_filename(input_folder):
|
| 788 |
-
"""Analyze files by extracting brand names from filenames"""
|
| 789 |
dateien = []
|
| 790 |
marken_set = set()
|
| 791 |
renamed_files_by_folder_and_marke = defaultdict(lambda: defaultdict(list))
|
|
@@ -795,9 +840,20 @@ def analyze_files_by_filename(input_folder):
|
|
| 795 |
continue
|
| 796 |
|
| 797 |
for file in sorted(subfolder.iterdir()):
|
| 798 |
-
if file.
|
| 799 |
continue
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 800 |
marke = extract_brand(file.stem)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 801 |
marken_set.add(marke)
|
| 802 |
dateien.append({
|
| 803 |
"original_file": file,
|
|
@@ -862,17 +918,17 @@ def extract_zip_to_temp(uploaded_file):
|
|
| 862 |
zip_ref.extractall(temp_dir)
|
| 863 |
return temp_dir
|
| 864 |
|
| 865 |
-
def extract_brand(file_stem):
|
| 866 |
-
"""Extract brand name from filename using pattern matching"""
|
| 867 |
-
parts = re.split(r'[ _\-]', file_stem)
|
| 868 |
-
return re.sub(r'[^a-z0-9]', '', parts[0].lower()) if parts else "unknown"
|
| 869 |
-
|
| 870 |
def clean_letters_only(text):
|
| 871 |
return re.sub(r'[^A-Za-z]', '', text)
|
| 872 |
|
| 873 |
def get_cleaned_filename_without_brand(filename, brand):
|
| 874 |
-
|
| 875 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 876 |
|
| 877 |
def generate_filename_based_pdf_report(input_folder, erste_marke=None, processed_files_mapping=None):
|
| 878 |
"""Generate PDF report based on filename brand analysis with final processed labels"""
|
|
|
|
| 115 |
|
| 116 |
files_to_process = []
|
| 117 |
for file in sorted(subfolder.iterdir()):
|
| 118 |
+
# Skip if not a file
|
| 119 |
+
if not file.is_file():
|
| 120 |
continue
|
| 121 |
+
|
| 122 |
+
# Skip files without allowed extensions
|
| 123 |
+
if file.suffix.lower() not in ALL_ALLOWED_EXTENSIONS and file.suffix != '':
|
| 124 |
+
continue
|
| 125 |
+
|
| 126 |
+
# Accept files with no extension as well
|
| 127 |
marke = extract_brand(file.stem)
|
| 128 |
+
|
| 129 |
+
# CRITICAL FIX: Skip files where brand extraction failed or brand not in index
|
| 130 |
+
if not marke or marke == "unknown" or marke not in marken_index:
|
| 131 |
+
print(f"Warning: Skipping file {file.name} - brand '{marke}' not found in marken_index")
|
| 132 |
+
continue
|
| 133 |
+
|
| 134 |
brand_counters[marke] += 1
|
| 135 |
files_to_process.append((file, marke))
|
| 136 |
|
|
|
|
| 140 |
brand_counters[marke] += 1 # Increment counter for this brand
|
| 141 |
count_str = f"{brand_counters[marke]:02d}" # Format as 01, 02, 03, etc.
|
| 142 |
|
| 143 |
+
# CRITICAL FIX: Double-check brand exists in index before proceeding
|
| 144 |
+
if marke not in marken_index:
|
| 145 |
+
print(f"Warning: Skipping file {file.name} - brand '{marke}' not in marken_index")
|
| 146 |
+
continue
|
| 147 |
+
|
| 148 |
markennummer = marken_index[marke]
|
| 149 |
cleaned = get_cleaned_filename_without_brand(file.name, marke)
|
| 150 |
|
|
|
|
| 152 |
ziel = output_root / neuer_name
|
| 153 |
|
| 154 |
if file.suffix.lower() in ALLOWED_IMAGE_EXTENSIONS:
|
| 155 |
+
try:
|
| 156 |
+
with PILImage.open(file) as img:
|
| 157 |
+
if img.mode in ('RGBA', 'LA') or (img.mode == 'P' and 'transparency' in img.info):
|
| 158 |
+
img.save(ziel, format='PNG')
|
| 159 |
+
else:
|
| 160 |
+
img.convert("RGBA").save(ziel, format='PNG')
|
| 161 |
+
except Exception as e:
|
| 162 |
+
print(f"Error processing image {file.name}: {e}")
|
| 163 |
+
shutil.copy2(file, ziel)
|
| 164 |
else:
|
| 165 |
shutil.copy2(file, ziel)
|
| 166 |
|
|
|
|
| 586 |
return 0, [], str(e)
|
| 587 |
|
| 588 |
def extract_brand(file_stem):
|
| 589 |
+
"""Extract brand name from filename using pattern matching - IMPROVED VERSION"""
|
| 590 |
+
# Remove any leading/trailing whitespace
|
| 591 |
+
file_stem = file_stem.strip()
|
| 592 |
+
|
| 593 |
+
# Split by common delimiters
|
| 594 |
parts = re.split(r'[ _\-]', file_stem)
|
| 595 |
+
|
| 596 |
+
if not parts:
|
| 597 |
+
return "unknown"
|
| 598 |
+
|
| 599 |
+
# Take the first part and clean it
|
| 600 |
+
first_part = parts[0].lower()
|
| 601 |
+
# Remove all non-alphanumeric characters
|
| 602 |
+
cleaned = re.sub(r'[^a-z0-9]', '', first_part)
|
| 603 |
+
|
| 604 |
+
# If the result is empty or too short, return unknown
|
| 605 |
+
if not cleaned or len(cleaned) < 2:
|
| 606 |
+
return "unknown"
|
| 607 |
+
|
| 608 |
+
# If it starts with numbers (like "01b01"), it might be already processed - extract the brand part
|
| 609 |
+
# Pattern: digits + 'b' + digits + brand
|
| 610 |
+
match = re.match(r'^\d{2}b\d{2}([a-z]+)', cleaned)
|
| 611 |
+
if match:
|
| 612 |
+
return match.group(1)
|
| 613 |
+
|
| 614 |
+
return cleaned
|
| 615 |
|
| 616 |
def erkenne_marken_aus_ordnern(input_folder):
|
| 617 |
"""Recognize brands from subfolders (original method)"""
|
|
|
|
| 830 |
elements.append(table)
|
| 831 |
|
| 832 |
def analyze_files_by_filename(input_folder):
|
| 833 |
+
"""Analyze files by extracting brand names from filenames - IMPROVED VERSION"""
|
| 834 |
dateien = []
|
| 835 |
marken_set = set()
|
| 836 |
renamed_files_by_folder_and_marke = defaultdict(lambda: defaultdict(list))
|
|
|
|
| 840 |
continue
|
| 841 |
|
| 842 |
for file in sorted(subfolder.iterdir()):
|
| 843 |
+
if not file.is_file():
|
| 844 |
continue
|
| 845 |
+
|
| 846 |
+
# Accept files with allowed extensions or no extension
|
| 847 |
+
if file.suffix.lower() not in ALL_ALLOWED_EXTENSIONS and file.suffix != '':
|
| 848 |
+
continue
|
| 849 |
+
|
| 850 |
marke = extract_brand(file.stem)
|
| 851 |
+
|
| 852 |
+
# Skip unknown brands
|
| 853 |
+
if marke == "unknown":
|
| 854 |
+
print(f"Warning: Could not extract brand from filename: {file.name}")
|
| 855 |
+
continue
|
| 856 |
+
|
| 857 |
marken_set.add(marke)
|
| 858 |
dateien.append({
|
| 859 |
"original_file": file,
|
|
|
|
| 918 |
zip_ref.extractall(temp_dir)
|
| 919 |
return temp_dir
|
| 920 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 921 |
def clean_letters_only(text):
|
| 922 |
return re.sub(r'[^A-Za-z]', '', text)
|
| 923 |
|
| 924 |
def get_cleaned_filename_without_brand(filename, brand):
|
| 925 |
+
"""Get cleaned filename without brand name"""
|
| 926 |
+
# Remove the extension first if present
|
| 927 |
+
stem = Path(filename).stem
|
| 928 |
+
full_letters = clean_letters_only(stem.lower())
|
| 929 |
+
# Remove the brand from the beginning
|
| 930 |
+
cleaned = full_letters.replace(brand, '', 1)
|
| 931 |
+
return cleaned
|
| 932 |
|
| 933 |
def generate_filename_based_pdf_report(input_folder, erste_marke=None, processed_files_mapping=None):
|
| 934 |
"""Generate PDF report based on filename brand analysis with final processed labels"""
|