Spaces:
Sleeping

File size: 3,886 Bytes
3b37a1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from typing import Any, Dict, List, Tuple
import os
import time
import zipfile
from PIL import Image

def get_image_metadata(image_path: str) -> Dict[str, Any]:
    """Get metadata for an image including aspect ratio, resolution, and size."""
    try:
        img = Image.open(image_path)
        width, height = img.size
        # Calculate simplified aspect ratio
        gcd = lambda a, b: a if b == 0 else gcd(b, a % b)
        div = gcd(width, height)
        simplified_ratio = f"{width//div}:{height//div}"
        
        file_size = os.path.getsize(image_path)
        # Convert to appropriate unit
        size_str = f"{file_size} bytes"
        if file_size > 1024:
            size_str = f"{file_size/1024:.2f} KB"
        if file_size > 1024*1024:
            size_str = f"{file_size/(1024*1024):.2f} MB"
            
        return {
            "resolution": f"{width}x{height}",
            "aspect_ratio": simplified_ratio,
            "size": size_str,
            "width": width,
            "height": height
        }
    except Exception as e:
        return {
            "resolution": "Unknown",
            "aspect_ratio": "Unknown",
            "size": "Unknown",
            "width": 0,
            "height": 0,
            "error": str(e)
        }

def format_metadata(metadata: Dict[str, Any]) -> str:
    """Format metadata as a string for display."""
    if not metadata:
        return "No metadata available"
    
    result = []
    if "resolution" in metadata:
        result.append(f"Resolution: {metadata['resolution']}")
    if "aspect_ratio" in metadata:
        result.append(f"Aspect Ratio: {metadata['aspect_ratio']}")
    if "size" in metadata:
        result.append(f"Size: {metadata['size']}")
    
    return " | ".join(result)

def generate_caption(image_path: str, trigger_token: str, description: str) -> str:
    """Generate caption for an image with trigger token and description."""
    if trigger_token:
        return f"A picture of {trigger_token}, {description}"
    else:
        return f"{description}"

def save_caption(image_path: str, caption: str) -> str:
    """Save caption to a text file with the same name as the image."""
    txt_path = os.path.splitext(image_path)[0] + ".txt"
    with open(txt_path, "w") as f:
        f.write(caption)
    return txt_path

def create_zip_file(image_data: List[Dict[str, Any]], dataset_name: str = "") -> str:
    """Create a zip file containing all processed images and their captions."""
    if not image_data:
        return ""
    
    # Create a zip file with a unique name based on timestamp and optional dataset name
    timestamp = int(time.time())
    zip_name = f"{dataset_name}_{timestamp}" if dataset_name else f"processed_images_{timestamp}"
    temp_zip_path = f"{zip_name}.zip"
    
    with zipfile.ZipFile(temp_zip_path, 'w') as zipf:
        for idx, item in enumerate(image_data, 1):
            if "path" in item and os.path.exists(item["path"]):
                # Add the image file with incremental naming
                image_path = item["path"]
                image_ext = os.path.splitext(image_path)[1]
                zipf.write(image_path, f"{idx}{image_ext}")
                
                # Create and add the caption file with the same incremental name
                if "caption" in item:
                    caption_content = item["caption"]
                    txt_filename = f"{idx}.txt"
                    
                    # Create a temporary text file
                    temp_txt_path = f"temp_{txt_filename}"
                    with open(temp_txt_path, "w") as f:
                        f.write(caption_content)
                    
                    # Add to zip and then delete the temp file
                    zipf.write(temp_txt_path, txt_filename)
                    os.remove(temp_txt_path)
    
    return temp_zip_path