File size: 5,065 Bytes
			
			| fc18dbd 4460661 fc18dbd 4460661 | 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 118 119 120 121 122 123 124 | import os
import subprocess
import datetime
from pathlib import Path
import shutil
# --- CONFIGURATION ---
items = ['spaces', 'models', 'datasets', 'daily_papers']
REPO_URL = "https://huggingface.co/datasets/cfahlgren1/hub-stats"
for item in items:
    FILE_PATH = item+".parquet"
    DEST_DIR = item
    CLONE_DIR = "temp_repo"
    # ----------------------
    # First, make sure git lfs is installed on your system
    try:
        subprocess.run(["git", "lfs", "install"], check=True)
        print("Git LFS installed successfully")
    except Exception as e:
        print(f"Warning: Git LFS installation might have failed: {e}")
        print("Continuing anyway...")
    # Clone repo if not already cloned
    if not os.path.exists(CLONE_DIR):
        print(f"Cloning repository with Git LFS: {REPO_URL}")
        subprocess.run(["git", "lfs", "clone", REPO_URL, CLONE_DIR], check=True)
    else:
        print(f"Repository already exists at {CLONE_DIR}")
        # Force checkout to main branch first before pulling
        subprocess.run(["git", "-C", CLONE_DIR, "checkout", "main"], check=True)
        subprocess.run(["git", "-C", CLONE_DIR, "pull"], check=True)
    # Get all commits that affected the file
    print(f"Finding commits for file: {FILE_PATH}")
    git_log_cmd = ["git", "-C", CLONE_DIR, "log", "--pretty=format:%H|%ct", "--follow", FILE_PATH]
    result = subprocess.run(git_log_cmd, capture_output=True, text=True, check=True)
    commits_info = result.stdout.strip().split('\n')
    if not commits_info or commits_info[0] == '':
        print("No commits found for the file.")
        exit()
    # Parse commit info
    commits = []
    for commit_line in commits_info:
        if '|' in commit_line:
            hexsha, timestamp = commit_line.split('|')
            commits.append((hexsha, int(timestamp)))
    # Sort commits by timestamp (oldest first)
    commits.sort(key=lambda x: x[1])
    # Get the date of the first commit
    start_date = datetime.datetime.fromtimestamp(commits[0][1]).date()
    end_date = datetime.date.today()
    Path(DEST_DIR).mkdir(parents=True, exist_ok=True)
    current_date = start_date
    week = datetime.timedelta(weeks=1)
    print(f"Processing weekly snapshots from {start_date} to {end_date}")
    while current_date < end_date:
        next_date = current_date + week
        next_date_timestamp = int(datetime.datetime.combine(next_date, datetime.time.min).timestamp())
        # Find latest commit before next_date
        weekly_commit = None
        for hexsha, timestamp in reversed(commits):
            if timestamp < next_date_timestamp:
                weekly_commit = hexsha
                commit_date = datetime.datetime.fromtimestamp(timestamp).date()
                break
        if weekly_commit:
            try:
                print(f"Processing week of {current_date} using commit {weekly_commit[:8]}")
                
                # Create the destination folder
                weekly_folder = Path(DEST_DIR) / str(current_date)
                weekly_folder.mkdir(parents=True, exist_ok=True)
                output_path = weekly_folder / os.path.basename(FILE_PATH)
                
                # Checkout this specific commit
                subprocess.run(["git", "-C", CLONE_DIR, "checkout", weekly_commit], check=True)
                
                # Force Git LFS to fetch the actual file content
                subprocess.run(["git", "-C", CLONE_DIR, "lfs", "pull"], check=True)
                
                # Copy the actual file
                source_file = os.path.join(CLONE_DIR, FILE_PATH)
                
                if os.path.exists(source_file):
                    shutil.copy2(source_file, output_path)
                    file_size = os.path.getsize(output_path) / (1024 * 1024)  # Size in MB
                    print(f"Saved: {output_path} ({file_size:.2f} MB)")
                    
                    # Verify if it's actually a parquet file and not just a pointer
                    with open(output_path, 'rb') as f:
                        header = f.read(4)
                    if header != b'PAR1':
                        print(f"WARNING: File doesn't start with Parquet magic bytes. Size: {file_size:.2f} MB")
                        if file_size < 1:  # Less than 1MB is suspicious for a Parquet file
                            print("This is likely still an LFS pointer and not the actual file")
                else:
                    print(f"ERROR: Source file not found at {source_file}")
                    
            except Exception as e:
                print(f"Error processing commit {weekly_commit}: {e}")
        else:
            print(f"No commit found for week of {current_date}")
        current_date = next_date
    # Return to main branch before exiting
    try:
        subprocess.run(["git", "-C", CLONE_DIR, "checkout", "main"], check=True)
        print("Returned to main branch")
    except Exception as e:
        print(f"Warning: Couldn't return to main branch: {e}") | 
