1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#!/usr/bin/env python
import os
import sys
from collections import defaultdict
from PIL import Image
import colorsys
import subprocess
import tempfile

def get_primary_color(image_path):
    with Image.open(image_path) as img:
        img = img.resize((100, 100))  # Resize for faster processing
        img = img.convert('RGB')
        pixels = list(img.getdata())
        # Get the most common color
        color_count = defaultdict(int)
        for pixel in pixels:
            color_count[pixel] += 1
        primary_color = max(color_count, key=color_count.get)
        # Convert RGB to HSV for better sorting
        h, s, v = colorsys.rgb_to_hsv(*[x/255.0 for x in primary_color])
        return (h, s, v)

def remove_yaml_header(content):
    lines = content.split('\n')
    if lines[0].strip() == '---':
        end_index = next((i for i, line in enumerate(lines[1:], 1) if line.strip() == '---'), None)
        if end_index is not None:
            return '\n'.join(lines[end_index+1:])
    return content

def markdown_to_html(markdown_content):
    with tempfile.NamedTemporaryFile(mode='w+', suffix='.md', delete=False) as temp_md:
        temp_md.write(markdown_content)
        temp_md_path = temp_md.name

    with tempfile.NamedTemporaryFile(mode='w+', suffix='.html', delete=False) as temp_html:
        temp_html_path = temp_html.name

    try:
        subprocess.run(['pandoc', '-f', 'markdown', '-t', 'html', temp_md_path, '-o', temp_html_path], check=True)
        with open(temp_html_path, 'r') as html_file:
            html_content = html_file.read()
    finally:
        os.unlink(temp_md_path)
        os.unlink(temp_html_path)

    return html_content

def generate_collage(directory, output_file):
    image_files = []
    # Walk through the directory
    for root, _, files in os.walk(directory):
        for file in files:
            if file.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.webp')):
                image_path = os.path.join(root, file)
                try:
                    primary_color = get_primary_color(image_path)
                    image_files.append((primary_color, image_path))
                except Exception as e:
                    print(f"Error processing {image_path}: {e}")

    # Sort images by primary color (hue, then saturation, then value)
    image_files.sort(key=lambda x: x[0])

    # Check for index.md and render its content
    markdown_content = ""
    index_md_path = os.path.join(directory, "index.md")
    if os.path.exists(index_md_path):
        with open(index_md_path, 'r') as md_file:
            md_content = md_file.read()
            md_content_without_yaml = remove_yaml_header(md_content)
            markdown_content = markdown_to_html(md_content_without_yaml)

    # Generate HTML
    html_content = f"""
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title> {directory} Image Collage (Color-sorted)</title>
        <link href="../css/basscss.min.css" rel="stylesheet">
        <link href="../css/water.css" rel="stylesheet">
    </head>
    <body class="p2">
    {markdown_content}
    <h1 class="mb3">{directory} - Image Collage (Sorted by Color)</h1>
    <div class="flex flex-wrap">
    """

    for i, (_, image_path) in enumerate(image_files):
        if i > 0 and i % 8 == 0:
            html_content += '</div>\n<div class="flex flex-wrap">\n'
        relative_path = os.path.relpath(image_path, directory)
        html_content += f'<div class="p1"><a href="{relative_path}"><img src="{relative_path}" alt="Image {i+1}" width="100" height="100" class="block"></a></div>\n'

    html_content += """
    </div>
    </body>
    </html>
    """

    # Write HTML to file
    with open(output_file, 'w') as f:
        f.write(html_content)

    print(f"Collage generated and saved as {output_file}")

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: python script.py <directory>")
        sys.exit(1)

    input_directory = sys.argv[1]
    output_file = os.path.join(input_directory, "index.html")
    generate_collage(input_directory, output_file)