CoolFace
Apppublic

SE-09/HapticsProject

sourceHugging Faceunknownupdated 2y agoView on Hugging Face
2likes
AzureBlobStorageVideo.py112 linesDownload Raw Back to root
1import azure.storage.blob  # Import required library2from azure.storage.blob import BlobServiceClient, generate_blob_sas, BlobSasPermissions3from datetime import datetime, timedelta4 5# Parameters for linking Azure to the application6storage_account_key = "zhrGpPBX6PVD+krncC4nVF4yoweEku/z2ErVxjLiuu/CjAVKqM5O4xlGWEyuWGxptL3mA1pv/6P4+AStjSjLEQ=="7storage_account_name = "useruploadhuggingface"8connection_string = f"DefaultEndpointsProtocol=https;AccountName={storage_account_name};AccountKey={storage_account_key};EndpointSuffix=core.windows.net"9container_name = "useruploadhuggingfacevideo"10#file_path = r"C:\Users\isuru\Documents\IIT University\Modules\Year 2 - Semester 2\SDGP\HapticAudio SE09 Local Repo\gradio-env\HapticsProject\video\WIND ANIMATION.mp4"11#file_name = "wind_video.mp4"12target_container_id = 'useruploadhuggingfacevideo'13 14 15 16def delete_container(container_id: str) -> None:17  """18  Deletes all blobs within a specified Azure Blob Storage container.19 20  Args:21      container_id (str): The ID of the container to delete.22  """23  try:24    # Establish connection using your storage connection string (replace with yours)25    storage_connection_string = 'DefaultEndpointsProtocol=https;AccountName=useruploadhuggingface;AccountKey=zhrGpPBX6PVD+krncC4nVF4yoweEku/z2ErVxjLiuu/CjAVKqM5O4xlGWEyuWGxptL3mA1pv/6P4+AStjSjLEQ==;EndpointSuffix=core.windows.net'26    blob_service_client = azure.storage.blob.BlobServiceClient.from_connection_string(storage_connection_string)27 28    # Get container client29    container_client = blob_service_client.get_container_client(container_id)30 31    # Delete all blobs in the container (iterator for large datasets)32    blobs = container_client.list_blobs()33    for blob in blobs:34        container_client.delete_blob(blob.name)35    print(f'Container "{container_id}" emptied successfully.')36 37  except Exception as e:38    print(f'Error deleting blobs: {e}')39 40 41 42 43def uploadUserVideoToBlobStorage(file_path, file_name):44    """Uploads an MP4 video file to the specified Azure Blob Storage container and returns the URL.45 46    Args:47        file_path (str): The path to the MP4 video file.48        file_name (str): The desired name of the blob in Azure Blob Storage.49 50    Returns:51        str: The URL for the uploaded video file in Azure Blob Storage.52 53    Raises:54        FileNotFoundError: If the specified file is not found.55    """56 57    try:58        # Create BlobServiceClient using the connection string59        blob_service_client = BlobServiceClient.from_connection_string(conn_str=connection_string)60 61        # Get a reference to the blob container62        container_client = blob_service_client.get_container_client(container_name)63 64        # Create the blob client with the specified file name65        blob_client = container_client.get_blob_client(file_name)66 67        # Open the video file in binary mode for upload68        with open(file_path, "rb") as data:69            # Upload the video data to the blob70            upload_blob_result = blob_client.upload_blob(data, overwrite=True)71 72            # Get the URL for the uploaded blob73            blob_url = blob_client.url74 75            print(f"Video '{file_name}' uploaded successfully. URL: {blob_url}")76            return blob_url77 78    except FileNotFoundError as e:79        print(f"Error: File not found at {file_path}.")80        raise  # Re-raise the exception for further handling81 82 83def generateSASToken(account_name,container_name, blob_name, account_key):84    sas_token = generate_blob_sas(account_name=account_name,85                              container_name=container_name,86                              blob_name=blob_name,87                              account_key=account_key,88                              permission=BlobSasPermissions(read=True),89                              expiry=datetime.utcnow() + timedelta(hours=1))90 91    print(f"SAS Token generated:{sas_token}")92 93    return sas_token94 95 96def generateSASURL(account_name, container_name, blob_name, sas_token):97 98    sas_url = 'https://' + account_name + '.blob.core.windows.net/' + container_name + '/' + blob_name + '?' + sas_token99    print(f"SAS URL Generated: {sas_url}")100 101    return sas_url102 103if __name__ == "__main__":104    # Example usage105    uploaded_video_url = uploadUserVideoToBlobStorage(file_path, file_name)106    # use the uploaded_video_url for further processing or sharing107    # Retrieve container_client from within the upload function108    blob_service_client = BlobServiceClient.from_connection_string(conn_str=connection_string)109    container_client = blob_service_client.get_container_client(container_name)110    target_container_id = 'useruploadhuggingfacevideo'111    deleteUserVideoFromBlobStorage(target_container_id)112