Spaces:
Runtime error
Runtime error
msIntui commited on
Commit Β·
897d2f8
1
Parent(s): 984fc5d
Add Hugging Face Spaces upload functionality
Browse files- Add direct upload to HF Spaces
- Improve download progress tracking
- Add better error handling
- Implement smaller chunk sizes for downloads
1 unmodified line23456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051524 unmodified lines5758596061626364656667686970717273747576777879808182831 unmodified linefrom azure.storage.blob import BlobServiceClientfrom dotenv import load_dotenvfrom tqdm import tqdm# Load environment variablesload_dotenv()def download_with_progress(blob_client, local_path):"""Download blob with progress bar"""# Get blob properties for total sizeproperties = blob_client.get_blob_properties()total_size = properties.size# Create progress barprogress = tqdm(total=total_size,unit='iB',unit_scale=True,desc=f"Downloading {os.path.basename(local_path)}")# Download in chunkswith open(local_path, "wb") as file:download_stream = blob_client.download_blob()for chunk in download_stream.chunks():file.write(chunk)progress.update(len(chunk))progress.close()def download_from_azure():"""Download models from Azure Blob Storage"""try:# Try primary connection first, fallback to secondaryconnect_str = os.getenv('AZURE_STORAGE_PRIMARY_CONNECTION')if not connect_str:connect_str = os.getenv('AZURE_STORAGE_SECONDARY_CONNECTION')container_name = os.getenv('AZURE_STORAGE_CONTAINER_NAME', 'pnid-models')print("Connecting to Azure Blob Storage...")# Create the BlobServiceClientblob_service_client = BlobServiceClient.from_connection_string(connect_str)container_client = blob_service_client.get_container_client(container_name)# Create models directoryos.makedirs('models', exist_ok=True)# Define model files to downloadmodel_files = {'Intui_SDM_41.pt': os.getenv('MODEL_SDM_41_PATH'),'Intui_SDM_30.pt': os.getenv('MODEL_SDM_30_PATH'),4 unmodified lines'intui_LDM_01.pt': os.getenv('MODEL_LDM_PATH')}# Download each modelfor blob_name, local_path in model_files.items():if not local_path:continueprint(f"\nChecking {blob_name}...")os.makedirs(os.path.dirname(local_path), exist_ok=True)if not os.path.exists(local_path) or os.path.getsize(local_path) == 0:blob_client = container_client.get_blob_client(blob_name)print(f"Starting download of {blob_name}...")download_with_progress(blob_client, local_path)print(f"Successfully downloaded {blob_name}")else:print(f"Skipping {blob_name}, already exists")print("\nAll models downloaded successfully!")except Exception as e:print(f"\nError downloading models from Azure: {str(e)}")raiseif __name__ == "__main__":download_from_azure()1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980814 unmodified lines86878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261 unmodified linefrom azure.storage.blob import BlobServiceClientfrom dotenv import load_dotenvfrom tqdm import tqdmimport requestsfrom huggingface_hub import HfApi, upload_file# Load environment variablesload_dotenv()def upload_to_hf_spaces(local_path, repo_id, token):"""Upload file to Hugging Face Spaces"""try:api = HfApi()print(f"\nUploading {os.path.basename(local_path)} to {repo_id}...")response = api.upload_file(path_or_fileobj=local_path,path_in_repo=os.path.basename(local_path),repo_id=repo_id,token=token)print(f"Successfully uploaded to {response}")return Trueexcept Exception as e:print(f"Error uploading to Hugging Face: {str(e)}")return Falsedef download_with_progress(blob_client, local_path):"""Download blob with improved progress tracking"""try:properties = blob_client.get_blob_properties()total_size = properties.size# Configure progress barprogress = tqdm(total=total_size,unit='B',unit_scale=True,desc=f"Downloading {os.path.basename(local_path)}",ncols=80)# Download in smaller chunks (5MB)chunk_size = 5 * 1024 * 1024 # 5MB chunkswith open(local_path, "wb") as file:download_stream = blob_client.download_blob()for chunk in download_stream.chunks(chunk_size=chunk_size):if chunk:file.write(chunk)progress.update(len(chunk))progress.close()return Trueexcept Exception as e:print(f"\nError during download: {str(e)}")# Clean up partial downloadif os.path.exists(local_path):os.remove(local_path)return Falsedef download_from_azure(upload_to_hf=False):"""Download models from Azure Blob Storage with optional HF upload"""try:# Get connection stringsconnect_str = os.getenv('AZURE_STORAGE_PRIMARY_CONNECTION')if not connect_str:connect_str = os.getenv('AZURE_STORAGE_SECONDARY_CONNECTION')container_name = os.getenv('AZURE_STORAGE_CONTAINER_NAME', 'pnid-models')hf_token = os.getenv('HF_TOKEN')hf_repo = os.getenv('HF_REPO_ID')print("Connecting to Azure Blob Storage...")blob_service_client = BlobServiceClient.from_connection_string(connect_str)container_client = blob_service_client.get_container_client(container_name)os.makedirs('models', exist_ok=True)model_files = {'Intui_SDM_41.pt': os.getenv('MODEL_SDM_41_PATH'),'Intui_SDM_30.pt': os.getenv('MODEL_SDM_30_PATH'),4 unmodified lines'intui_LDM_01.pt': os.getenv('MODEL_LDM_PATH')}for blob_name, local_path in model_files.items():if not local_path:continueprint(f"\nProcessing {blob_name}...")os.makedirs(os.path.dirname(local_path), exist_ok=True)# Check if file needs to be downloadedneeds_download = (not os.path.exists(local_path) oros.path.getsize(local_path) == 0)if needs_download:blob_client = container_client.get_blob_client(blob_name)success = download_with_progress(blob_client, local_path)if not success:print(f"Failed to download {blob_name}")continueprint(f"Successfully downloaded {blob_name}")else:print(f"Skipping {blob_name}, already exists")# Upload to HF Spaces if requestedif upload_to_hf and hf_token and hf_repo:upload_to_hf_spaces(local_path, hf_repo, hf_token)print("\nAll operations completed!")except Exception as e:print(f"\nError in main process: {str(e)}")raiseif __name__ == "__main__":# Set to True if you want to upload to HF Spacesdownload_from_azure(upload_to_hf=False)
download_models.py+81-38