ZoneTwelve's picture
Update patient doctor rawdata
732eb0d
#!/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()