File size: 3,559 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
#!/usr/bin/env python3
"""
Script to extract files from blobs created for Hugging Face datasets.
Usage:
    python blob_extract.py /path/to/blob/directory --file path/to/extract.txt --output /path/to/save
"""

import json
import argparse
from pathlib import Path
import shutil
import os

class BlobExtractor:
    def __init__(self, blob_dir: str):
        """Initialize extractor 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 available for extraction:")
        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 extract_file(self, file_path: str, output_path: str = None) -> None:
        """
        Extract a specific file from the blob.
        
        Args:
            file_path: Path of the file within the blob
            output_path: Where to save the extracted file. If None, uses original filename
        """
        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']
        
        # Determine output path
        if output_path is None:
            output_path = file_path

        # Create output directory if needed
        output_path = Path(output_path)
        output_path.parent.mkdir(parents=True, exist_ok=True)
            
        print(f"\nExtracting: {file_path}")
        print(f"From blob: {info['blob']}")
        print(f"Size: {info['size']} bytes")
        print(f"To: {output_path}")
        
        try:
            with open(blob_path, 'rb') as src, open(output_path, 'wb') as dst:
                # Seek to file's position in blob
                src.seek(info['offset'])
                # Copy exact number of bytes
                shutil.copyfileobj(src, dst, length=info['size'])
            
            print(f"Successfully extracted to: {output_path}")
            
        except Exception as e:
            print(f"Error extracting file: {e}")

def main():
    parser = argparse.ArgumentParser(description="Extract files from blobs")
    parser.add_argument("blob_dir", help="Directory containing blobs and metadata.json")
    parser.add_argument("--file", "-f", help="Specific file to extract")
    parser.add_argument("--output", "-o", help="Output path for extracted file")
    parser.add_argument("--list", "-l", action="store_true", help="List all files in blobs")
    
    args = parser.parse_args()
    
    try:
        extractor = BlobExtractor(args.blob_dir)
        
        if args.list:
            extractor.list_files()
        elif args.file:
            extractor.extract_file(args.file, args.output)
        else:
            extractor.list_files()  # Default to listing files if no specific action
            
    except Exception as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    main()