File size: 3,845 Bytes
732eb0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Simple script to preview contents of blob files created for Hugging Face datasets.
Usage:
    python blob_preview.py /path/to/blob/directory [--file specific/file.txt] [--list]
"""

import json
import argparse
from pathlib import Path
from typing import Dict, Tuple

class BlobPreview:
    def __init__(self, blob_dir: str):
        """Initialize preview with directory containing blobs and metadata."""
        self.blob_dir = Path(blob_dir)
        self.metadata_path = self.blob_dir / 'metadata.json'
        self.metadata = self._load_metadata()

    def _load_metadata(self) -> Dict:
        """Load and return the metadata JSON file."""
        if not self.metadata_path.exists():
            raise FileNotFoundError(f"Metadata file not found at {self.metadata_path}")
        
        with open(self.metadata_path, 'r') as f:
            return json.load(f)

    def list_files(self):
        """Print all files stored in the blobs."""
        print("\nFiles in blobs:")
        print("-" * 50)
        for file_path in sorted(self.metadata.keys()):
            info = self.metadata[file_path]
            print(f"{file_path:<50} (size: {info['size']} bytes, blob: {info['blob']})")

    def preview_file(self, file_path: str, max_size: int = 1024) -> None:
        """Preview content of a specific file."""
        if file_path not in self.metadata:
            print(f"Error: File '{file_path}' not found in blobs")
            return

        info = self.metadata[file_path]
        blob_path = self.blob_dir / info['blob']
        
        print(f"\nFile: {file_path}")
        print(f"Location: {info['blob']}")
        print(f"Size: {info['size']} bytes")
        print(f"Offset: {info['offset']} bytes")
        print("-" * 50)

        try:
            with open(blob_path, 'rb') as f:
                # Seek to file's position in blob
                f.seek(info['offset'])
                # Read the content (up to max_size)
                content = f.read(min(info['size'], max_size))

            # Try to decode as text
            try:
                text = content.decode('utf-8')
                print("Content preview (decoded as UTF-8):")
                print(text)
                if len(content) < info['size']:
                    print("\n... (truncated)")
            except UnicodeDecodeError:
                print("Content preview (hexdump):")
                for i in range(0, len(content), 16):
                    chunk = content[i:i+16]
                    hex_values = ' '.join(f'{b:02x}' for b in chunk)
                    ascii_values = ''.join(chr(b) if 32 <= b <= 126 else '.' for b in chunk)
                    print(f"{i:08x}  {hex_values:<48}  {ascii_values}")
                if len(content) < info['size']:
                    print("\n... (truncated)")

        except Exception as e:
            print(f"Error reading file: {e}")

def main():
    parser = argparse.ArgumentParser(description="Preview contents of blob files")
    parser.add_argument("blob_dir", help="Directory containing blobs and metadata.json")
    parser.add_argument("--file", "-f", help="Specific file to preview")
    parser.add_argument("--list", "-l", action="store_true", help="List all files in blobs")
    parser.add_argument("--size", "-s", type=int, default=1024,
                       help="Maximum preview size in bytes (default: 1024)")
    
    args = parser.parse_args()
    
    try:
        preview = BlobPreview(args.blob_dir)
        
        if args.list:
            preview.list_files()
        elif args.file:
            preview.preview_file(args.file, args.size)
        else:
            preview.list_files()  # Default to listing files if no specific action
            
    except Exception as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    main()