Spaces:
Running
Running
| #!/usr/bin/env python3 | |
| """ | |
| π§Ή PYTHON CACHE CLEANER | |
| Removes all __pycache__ folders and .pyc files from the backend directory | |
| """ | |
| import os | |
| import shutil | |
| import sys | |
| from pathlib import Path | |
| from typing import List, Tuple | |
| def find_pycache_dirs(root_dir: str) -> List[str]: | |
| """Find all __pycache__ directories recursively""" | |
| pycache_dirs = [] | |
| for root, dirs, files in os.walk(root_dir): | |
| if '__pycache__' in dirs: | |
| pycache_path = os.path.join(root, '__pycache__') | |
| pycache_dirs.append(pycache_path) | |
| return pycache_dirs | |
| def find_pyc_files(root_dir: str) -> List[str]: | |
| """Find all .pyc files recursively""" | |
| pyc_files = [] | |
| for root, dirs, files in os.walk(root_dir): | |
| for file in files: | |
| if file.endswith('.pyc'): | |
| pyc_path = os.path.join(root, file) | |
| pyc_files.append(pyc_path) | |
| return pyc_files | |
| def delete_pycache_dirs(pycache_dirs: List[str]) -> Tuple[int, List[str]]: | |
| """Delete __pycache__ directories and return count and any errors""" | |
| deleted_count = 0 | |
| errors = [] | |
| for pycache_dir in pycache_dirs: | |
| try: | |
| shutil.rmtree(pycache_dir) | |
| print(f"β Deleted: {pycache_dir}") | |
| deleted_count += 1 | |
| except Exception as e: | |
| error_msg = f"β Failed to delete {pycache_dir}: {str(e)}" | |
| print(error_msg) | |
| errors.append(error_msg) | |
| return deleted_count, errors | |
| def delete_pyc_files(pyc_files: List[str]) -> Tuple[int, List[str]]: | |
| """Delete .pyc files and return count and any errors""" | |
| deleted_count = 0 | |
| errors = [] | |
| for pyc_file in pyc_files: | |
| try: | |
| os.remove(pyc_file) | |
| print(f"β Deleted: {pyc_file}") | |
| deleted_count += 1 | |
| except Exception as e: | |
| error_msg = f"β Failed to delete {pyc_file}: {str(e)}" | |
| print(error_msg) | |
| errors.append(error_msg) | |
| return deleted_count, errors | |
| def get_directory_size(root_dir: str) -> int: | |
| """Calculate total size of __pycache__ directories in bytes""" | |
| total_size = 0 | |
| for root, dirs, files in os.walk(root_dir): | |
| if '__pycache__' in dirs: | |
| pycache_path = os.path.join(root, '__pycache__') | |
| try: | |
| for dirpath, dirnames, filenames in os.walk(pycache_path): | |
| for filename in filenames: | |
| filepath = os.path.join(dirpath, filename) | |
| try: | |
| total_size += os.path.getsize(filepath) | |
| except (OSError, FileNotFoundError): | |
| pass | |
| except (OSError, FileNotFoundError): | |
| pass | |
| return total_size | |
| def format_size(size_bytes: int) -> str: | |
| """Format size in human readable format""" | |
| if size_bytes == 0: | |
| return "0 B" | |
| size_names = ["B", "KB", "MB", "GB"] | |
| i = 0 | |
| size = float(size_bytes) | |
| while size >= 1024.0 and i < len(size_names) - 1: | |
| size /= 1024.0 | |
| i += 1 | |
| return f"{size:.1f} {size_names[i]}" | |
| def main(): | |
| """Main function to clean Python cache files""" | |
| print("π§Ή PYTHON CACHE CLEANER") | |
| print("=" * 50) | |
| # Get the backend directory (current script's directory) | |
| backend_dir = os.path.dirname(os.path.abspath(__file__)) | |
| print(f"π Scanning directory: {backend_dir}") | |
| # Calculate cache size before deletion | |
| print("\nπ Analyzing cache files...") | |
| cache_size = get_directory_size(backend_dir) | |
| print(f"πΎ Total cache size: {format_size(cache_size)}") | |
| # Find all cache files and directories | |
| pycache_dirs = find_pycache_dirs(backend_dir) | |
| pyc_files = find_pyc_files(backend_dir) | |
| print(f"\nπ Found:") | |
| print(f" π __pycache__ directories: {len(pycache_dirs)}") | |
| print(f" π .pyc files: {len(pyc_files)}") | |
| if len(pycache_dirs) == 0 and len(pyc_files) == 0: | |
| print("\n⨠No cache files found! Directory is already clean.") | |
| return | |
| # Show what will be deleted | |
| print(f"\nπ Cache directories to delete:") | |
| for pycache_dir in pycache_dirs: | |
| rel_path = os.path.relpath(pycache_dir, backend_dir) | |
| print(f" ποΈ {rel_path}") | |
| if pyc_files: | |
| print(f"\nπ .pyc files to delete:") | |
| for pyc_file in pyc_files[:10]: # Show first 10 | |
| rel_path = os.path.relpath(pyc_file, backend_dir) | |
| print(f" π {rel_path}") | |
| if len(pyc_files) > 10: | |
| print(f" ... and {len(pyc_files) - 10} more") | |
| # Ask for confirmation | |
| print(f"\nβ οΈ This will permanently delete {len(pycache_dirs)} directories and {len(pyc_files)} files") | |
| print(f"πΎ Total space to be freed: {format_size(cache_size)}") | |
| try: | |
| confirm = input("\nπ€ Proceed with deletion? (y/N): ").strip().lower() | |
| if confirm not in ['y', 'yes']: | |
| print("β Operation cancelled by user") | |
| return | |
| except KeyboardInterrupt: | |
| print("\nβ Operation cancelled by user") | |
| return | |
| print(f"\nπ§Ή Starting cleanup...") | |
| # Delete __pycache__ directories | |
| dirs_deleted, dir_errors = delete_pycache_dirs(pycache_dirs) | |
| # Delete .pyc files | |
| files_deleted, file_errors = delete_pyc_files(pyc_files) | |
| # Summary | |
| print(f"\nπ CLEANUP SUMMARY") | |
| print("=" * 30) | |
| print(f"β Directories deleted: {dirs_deleted}/{len(pycache_dirs)}") | |
| print(f"β Files deleted: {files_deleted}/{len(pyc_files)}") | |
| print(f"πΎ Space freed: {format_size(cache_size)}") | |
| if dir_errors or file_errors: | |
| print(f"\nβ οΈ ERRORS ENCOUNTERED:") | |
| for error in dir_errors + file_errors: | |
| print(f" {error}") | |
| print(f"\nβ {len(dir_errors + file_errors)} errors occurred during cleanup") | |
| else: | |
| print(f"\nπ Cleanup completed successfully!") | |
| # Final verification | |
| remaining_pycache = find_pycache_dirs(backend_dir) | |
| remaining_pyc = find_pyc_files(backend_dir) | |
| if remaining_pycache or remaining_pyc: | |
| print(f"\nβ οΈ Warning: {len(remaining_pycache)} __pycache__ dirs and {len(remaining_pyc)} .pyc files still remain") | |
| else: | |
| print(f"\n⨠All Python cache files have been successfully removed!") | |
| if __name__ == "__main__": | |
| try: | |
| main() | |
| except KeyboardInterrupt: | |
| print("\n\nβ Cleanup interrupted by user") | |
| sys.exit(1) | |
| except Exception as e: | |
| print(f"\n\nπ₯ Unexpected error: {str(e)}") | |
| sys.exit(1) |