def test_translation_with_glossary(self, client):
        doc = Document(data=b'testing')
        source_container_sas_url = self.create_source_container(data=[doc])
        target_container_sas_url = self.create_target_container()

        container_client = ContainerClient(self.storage_endpoint, self.source_container_name,
                                           self.storage_key)
        with open(GLOSSARY_FILE_NAME, "rb") as fd:
            container_client.upload_blob(name=GLOSSARY_FILE_NAME, data=fd.read())

        prefix, suffix = source_container_sas_url.split("?")
        glossary_file_sas_url = prefix + "/" + GLOSSARY_FILE_NAME + "?" + suffix

        poller = client.begin_translation(
            source_container_sas_url,
            target_container_sas_url,
            "es",
            glossaries=[TranslationGlossary(glossary_url=glossary_file_sas_url, file_format="csv")]
        )
        result = poller.result()

        container_client = ContainerClient(self.storage_endpoint, self.target_container_name,
                                           self.storage_key)

        # download translated file and assert that translation reflects glossary changes
        document = doc.name + doc.suffix
        with open(document, "wb") as my_blob:
            download_stream = container_client.download_blob(document)
            my_blob.write(download_stream.readall())

        with open(document, "rb") as fd:
            translated = fd.readline()

        assert b'essai' in translated  # glossary worked
        os.remove(document)
Пример #2
0
def upload_file(
    file_path: Path,
    container_name: str,
    blob_name: str,
    service: ContainerClient,
    settings: Settings,
    force: bool,
) -> None:
    file_extension = get_file_extension(file_path)

    if file_extension in settings.mimes:
        file_mime = settings.mimes.get(file_extension)
    else:
        file_mime = mimetypes.guess_type(file_path)[0]

    blob_name = remove_empty_folders(blob_name)
    logger.debug("Using mime `%s` for blob `%s`", file_mime, blob_name)
    logger.debug("File `%s` mapped to blob `%s`", file_path, blob_name)
    logger.info(f"Uploading `{blob_name}` ({file_mime})")

    with open(file_path, mode="rb") as file:
        service.upload_blob(
            name=blob_name,
            data=file,
            content_settings=ContentSettings(content_type=file_mime),
            overwrite=force,
        )
Пример #3
0
    def create_storage_item(self, data, mime_type=None, item_name=None) -> str:
        """Creates and uploads data into online-storage. Returns its storage ID."""
        if not mime_type:
            mime_type = guess_data_mimetype(data)

        # get signed url to use signature
        client = self._client
        url = '{}/{}/project/{}/storage/signedurl'.format(client.HOME, client.API_1, self.id)
        if item_name:
            url += '?name={}'.format(item_name)
        resp = client._auth_get(url)

        blob_id = 'storage/' + resp['id']
        url = resp['signedurl']

        url_object = urlparse(url)
        sas_token = url_object.query
        account_url = url_object.scheme + '://' + url_object.netloc
        container_name = url_object.path.split('/')[1]

        container_client = ContainerClient(account_url, container_name, credential=sas_token)
        container_client.upload_blob(
            blob_id,
            data,
            blob_type='BlockBlob',
            content_settings=ContentSettings(content_type=mime_type)
        )

        return resp['id']
Пример #4
0
    def combine_azure(self):
        from azure.storage.blob import ContainerClient, ContentSettings

        feed_uri = self.settings.get("FEED_URI")
        feed_prefix = self.settings.get("CITY_SCRAPERS_DIFF_FEED_PREFIX", "%Y/%m/%d")
        account_name, account_key = feed_uri[8::].split("@")[0].split(":")
        container = feed_uri.split("@")[1].split("/")[0]
        container_client = ContainerClient(
            "{}.blob.core.windows.net".format(account_name),
            container,
            credential=account_key,
        )

        max_days_previous = 3
        days_previous = 0
        prefix_blobs = []
        while days_previous <= max_days_previous:
            prefix_blobs = [
                blob
                for blob in container_client.list_blobs(
                    name_starts_with=(
                        datetime.now() - timedelta(days=days_previous)
                    ).strftime(feed_prefix)
                )
            ]
            if len(prefix_blobs) > 0:
                break
            days_previous += 1

        spider_blob_names = self.get_spider_paths([blob.name for blob in prefix_blobs])
        meetings = []
        for blob_name in spider_blob_names:
            feed_blob = container_client.get_blob_client(blob_name)
            feed_text = feed_blob.download_blob().content_as_text()
            meetings.extend(
                [json.loads(line) for line in feed_text.split("\n") if line]
            )
        meetings = sorted(meetings, key=itemgetter(self.start_key))
        yesterday_iso = (datetime.now() - timedelta(days=1)).isoformat()[:19]
        upcoming = [
            meeting
            for meeting in meetings
            if meeting[self.start_key][:19] > yesterday_iso
        ]

        container_client.upload_blob(
            "latest.json",
            "\n".join([json.dumps(meeting) for meeting in meetings]),
            content_settings=ContentSettings(cache_control="no-cache"),
            overwrite=True,
        )

        container_client.upload_blob(
            "upcoming.json",
            "\n".join([json.dumps(meeting) for meeting in upcoming]),
            content_settings=ContentSettings(cache_control="no-cache"),
            overwrite=True,
        )
Пример #5
0
    def create_form_client_and_container_sas_url(self, **kwargs):
        form_recognizer_account = self.client_kwargs.pop("form_recognizer_account", None)
        if form_recognizer_account is None:
            form_recognizer_account = kwargs.pop("form_recognizer_account")

        form_recognizer_account_key = self.client_kwargs.pop("form_recognizer_account_key", None)
        if form_recognizer_account_key is None:
            form_recognizer_account_key = kwargs.pop("form_recognizer_account_key")

        storage_account = self.client_kwargs.pop("storage_account", None)
        if storage_account is None:
            storage_account = kwargs.pop("storage_account")

        storage_account_key = self.client_kwargs.pop("storage_account_key", None)
        if storage_account_key is None:
            storage_account_key = kwargs.pop("storage_account_key")

        if self.is_live:
            container_name = self.resource_random_name.replace("_", "-")  # container names can't have underscore
            container_client = ContainerClient(storage_account.primary_endpoints.blob, container_name,
                                               storage_account_key)
            container_client.create_container()

            training_path = os.path.abspath(os.path.join(os.path.abspath(__file__), "..", "./sample_forms/training/"))
            for path, folder, files in os.walk(training_path):
                for document in files:
                    with open(os.path.join(path, document), "rb") as data:
                        if document == "Form_6.jpg":
                            document = "subfolder/Form_6.jpg"  # create virtual subfolder in container
                        container_client.upload_blob(name=document, data=data)

            sas_token = generate_container_sas(
                storage_account.name,
                container_name,
                storage_account_key,
                permission=ContainerSasPermissions.from_string("rl"),
                expiry=datetime.utcnow() + timedelta(hours=1)
            )

            container_sas_url = storage_account.primary_endpoints.blob + container_name + "?" + sas_token

        else:
            container_sas_url = "containersasurl"

        return self.client_cls(
            form_recognizer_account,
            AzureKeyCredential(form_recognizer_account_key),
            **self.client_kwargs
        ), container_sas_url
Пример #6
0
 def create_source_container(self, data, blob_prefix=""):
     container_name = "src" + str(uuid.uuid4())
     container_client = ContainerClient(self.storage_endpoint,
                                        container_name, self.storage_key)
     container_client.create_container()
     if isinstance(data, list):
         for blob in data:
             container_client.upload_blob(name=blob_prefix +
                                          str(uuid.uuid4()) + ".txt",
                                          data=blob)
     else:
         container_client.upload_blob(name=blob_prefix + str(uuid.uuid4()) +
                                      ".txt",
                                      data=data)
     return self.generate_sas_url(container_name, "rl")
Пример #7
0
    def update_status_svg(self, spider, svg):
        from azure.storage.blob import ContainerClient, ContentSettings

        container_client = ContainerClient(
            "{}.blob.core.windows.net".format(
                self.crawler.settings.get("AZURE_ACCOUNT_NAME")),
            self.crawler.settings.get("CITY_SCRAPERS_STATUS_CONTAINER"),
            credential=self.crawler.settings.get("AZURE_ACCOUNT_KEY"),
        )
        container_client.upload_blob(
            "{}.svg".format(spider.name),
            svg,
            content_settings=ContentSettings(content_type="image/svg+xml",
                                             cache_control="no-cache"),
            overwrite=True,
        )
Пример #8
0
    def upload_opta_config(self) -> None:
        providers = self.layer.gen_providers(0)
        credentials = self.get_credentials()

        storage_account_name = providers["terraform"]["backend"]["azurerm"][
            "storage_account_name"]
        container_name = providers["terraform"]["backend"]["azurerm"][
            "container_name"]

        storage_client = ContainerClient(
            account_url=f"https://{storage_account_name}.blob.core.windows.net",
            container_name=container_name,
            credential=credentials,
        )
        config_path = f"opta_config/{self.layer.name}"
        storage_client.upload_blob(
            name=config_path,
            data=json.dumps(self.layer.structured_config()),
            overwrite=True,
        )
Пример #9
0
class AzureBlobFeedStorage(BlockingFeedStorage):
    def __init__(self, uri):
        from azure.storage.blob import ContainerClient

        container = uri.split("@")[1].split("/")[0]
        filename = "/".join(uri.split("@")[1].split("/")[1::])
        account_name, account_key = uri[8::].split("@")[0].split(":")

        self.account_name = account_name
        self.account_key = account_key
        self.container = container
        self.filename = filename
        self.container_client = ContainerClient(
            "{}.blob.core.windows.net".format(self.account_name),
            self.container,
            credential=self.account_key,
        )

    def _store_in_thread(self, file):
        file.seek(0)
        self.container_client.upload_blob(self.filename, file, overwrite=True)
Пример #10
0
class AzureCloudInterface(CloudInterface):
    # Azure block blob limitations
    # https://docs.microsoft.com/en-us/rest/api/storageservices/understanding-block-blobs--append-blobs--and-page-blobs
    MAX_CHUNKS_PER_FILE = 50000
    # Minimum block size allowed in Azure Blob Storage is 64KB
    MIN_CHUNK_SIZE = 64 << 10

    # Azure Blob Storage permit a maximum of 4.75TB per file
    # This is a hard limit, while our upload procedure can go over the specified
    # MAX_ARCHIVE_SIZE - so we set a maximum of 1TB per file
    MAX_ARCHIVE_SIZE = 1 << 40

    # The size of each chunk in a single object upload when the size of the
    # object exceeds max_single_put_size. We default to 2MB in order to
    # allow the default max_concurrency of 8 to be achieved when uploading
    # uncompressed WAL segments of the default 16MB size.
    DEFAULT_MAX_BLOCK_SIZE = 2 << 20

    # The maximum amount of concurrent chunks allowed in a single object upload
    # where the size exceeds max_single_put_size. We default to 8 based on
    # experiments with in-region and inter-region transfers within Azure.
    DEFAULT_MAX_CONCURRENCY = 8

    # The largest file size which will be uploaded in a single PUT request. This
    # should be lower than the size of the compressed WAL segment in order to
    # force the Azure client to use concurrent chunk upload for archiving WAL files.
    DEFAULT_MAX_SINGLE_PUT_SIZE = 4 << 20

    # The maximum size of the requests connection pool used by the Azure client
    # to upload objects.
    REQUESTS_POOL_MAXSIZE = 32

    def __init__(
        self,
        url,
        jobs=2,
        encryption_scope=None,
        credential=None,
        tags=None,
        max_block_size=DEFAULT_MAX_BLOCK_SIZE,
        max_concurrency=DEFAULT_MAX_CONCURRENCY,
        max_single_put_size=DEFAULT_MAX_SINGLE_PUT_SIZE,
    ):
        """
        Create a new Azure Blob Storage interface given the supplied account url

        :param str url: Full URL of the cloud destination/source
        :param int jobs: How many sub-processes to use for asynchronous
          uploading, defaults to 2.
        """
        super(AzureCloudInterface, self).__init__(
            url=url,
            jobs=jobs,
            tags=tags,
        )
        self.encryption_scope = encryption_scope
        self.credential = credential
        self.max_block_size = max_block_size
        self.max_concurrency = max_concurrency
        self.max_single_put_size = max_single_put_size

        parsed_url = urlparse(url)
        if parsed_url.netloc.endswith(AZURE_BLOB_STORAGE_DOMAIN):
            # We have an Azure Storage URI so we use the following form:
            # <http|https>://<account-name>.<service-name>.core.windows.net/<resource-path>
            # where <resource-path> is <container>/<blob>.
            # Note that although Azure supports an implicit root container, we require
            # that the container is always included.
            self.account_url = parsed_url.netloc
            try:
                self.bucket_name = parsed_url.path.split("/")[1]
            except IndexError:
                raise ValueError("azure blob storage URL %s is malformed" %
                                 url)
            path = parsed_url.path.split("/")[2:]
        else:
            # We are dealing with emulated storage so we use the following form:
            # http://<local-machine-address>:<port>/<account-name>/<resource-path>
            logging.info("Using emulated storage URL: %s " % url)
            if "AZURE_STORAGE_CONNECTION_STRING" not in os.environ:
                raise ValueError(
                    "A connection string must be provided when using emulated storage"
                )
            try:
                self.bucket_name = parsed_url.path.split("/")[2]
            except IndexError:
                raise ValueError("emulated storage URL %s is malformed" % url)
            path = parsed_url.path.split("/")[3:]

        self.path = "/".join(path)

        self.bucket_exists = None
        self._reinit_session()

    def _reinit_session(self):
        """
        Create a new session
        """
        if self.credential:
            # Any supplied credential takes precedence over the environment
            credential = self.credential
        elif "AZURE_STORAGE_CONNECTION_STRING" in os.environ:
            logging.info("Authenticating to Azure with connection string")
            self.container_client = ContainerClient.from_connection_string(
                conn_str=os.getenv("AZURE_STORAGE_CONNECTION_STRING"),
                container_name=self.bucket_name,
            )
            return
        else:
            if "AZURE_STORAGE_SAS_TOKEN" in os.environ:
                logging.info("Authenticating to Azure with SAS token")
                credential = os.getenv("AZURE_STORAGE_SAS_TOKEN")
            elif "AZURE_STORAGE_KEY" in os.environ:
                logging.info("Authenticating to Azure with shared key")
                credential = os.getenv("AZURE_STORAGE_KEY")
            else:
                logging.info(
                    "Authenticating to Azure with default credentials")
                # azure-identity is not part of azure-storage-blob so only import
                # it if needed
                try:
                    from azure.identity import DefaultAzureCredential
                except ImportError:
                    raise SystemExit(
                        "Missing required python module: azure-identity")
                credential = DefaultAzureCredential()
        session = requests.Session()
        adapter = requests.adapters.HTTPAdapter(
            pool_maxsize=self.REQUESTS_POOL_MAXSIZE)
        session.mount("https://", adapter)
        self.container_client = ContainerClient(
            account_url=self.account_url,
            container_name=self.bucket_name,
            credential=credential,
            max_single_put_size=self.max_single_put_size,
            max_block_size=self.max_block_size,
            session=session,
        )

    @property
    def _extra_upload_args(self):
        optional_args = {}
        if self.encryption_scope:
            optional_args["encryption_scope"] = self.encryption_scope
        return optional_args

    def test_connectivity(self):
        """
        Test Azure connectivity by trying to access a container
        """
        try:
            # We are not even interested in the existence of the bucket,
            # we just want to see if Azure blob service is reachable.
            self.bucket_exists = self._check_bucket_existence()
            return True
        except (HttpResponseError, ServiceRequestError) as exc:
            logging.error("Can't connect to cloud provider: %s", exc)
            return False

    def _check_bucket_existence(self):
        """
        Chck Azure Blob Storage for the target container

        Although there is an `exists` function it cannot be called by container-level
        shared access tokens. We therefore check for existence by calling list_blobs
        on the container.

        :return: True if the container exists, False otherwise
        :rtype: bool
        """
        try:
            self.container_client.list_blobs().next()
        except ResourceNotFoundError:
            return False
        except StopIteration:
            # The bucket is empty but it does exist
            pass
        return True

    def _create_bucket(self):
        """
        Create the container in cloud storage
        """
        # By default public access is disabled for newly created containers.
        # Unlike S3 there is no concept of regions for containers (this is at
        # the storage account level in Azure)
        self.container_client.create_container()

    def _walk_blob_tree(self, obj, ignore=None):
        """
        Walk a blob tree in a directory manner and return a list of directories
        and files.

        :param ItemPaged[BlobProperties] obj: Iterable response of BlobProperties
          obtained from ContainerClient.walk_blobs
        :param str|None ignore: An entry to be excluded from the returned list,
          typically the top level prefix
        :return: List of objects and directories in the tree
        :rtype: List[str]
        """
        if obj.name != ignore:
            yield obj.name
        if isinstance(obj, BlobPrefix):
            # We are a prefix and not a leaf so iterate children
            for child in obj:
                for v in self._walk_blob_tree(child):
                    yield v

    def list_bucket(self, prefix="", delimiter=DEFAULT_DELIMITER):
        """
        List bucket content in a directory manner

        :param str prefix:
        :param str delimiter:
        :return: List of objects and dirs right under the prefix
        :rtype: List[str]
        """
        res = self.container_client.walk_blobs(name_starts_with=prefix,
                                               delimiter=delimiter)
        return self._walk_blob_tree(res, ignore=prefix)

    def download_file(self, key, dest_path, decompress=None):
        """
        Download a file from Azure Blob Storage

        :param str key: The key to download
        :param str dest_path: Where to put the destination file
        :param str|None decompress: Compression scheme to use for decompression
        """
        obj = self.container_client.download_blob(key)
        with open(dest_path, "wb") as dest_file:
            if decompress is None:
                obj.download_to_stream(dest_file)
                return
            blob = StreamingBlobIO(obj)
            decompress_to_file(blob, dest_file, decompress)

    def remote_open(self, key, decompressor=None):
        """
        Open a remote Azure Blob Storage object and return a readable stream

        :param str key: The key identifying the object to open
        :param barman.clients.cloud_compression.ChunkedCompressor decompressor:
          A ChunkedCompressor object which will be used to decompress chunks of bytes
          as they are read from the stream
        :return: A file-like object from which the stream can be read or None if
          the key does not exist
        """
        try:
            obj = self.container_client.download_blob(key)
            resp = StreamingBlobIO(obj)
            if decompressor:
                return DecompressingStreamingIO(resp, decompressor)
            else:
                return resp
        except ResourceNotFoundError:
            return None

    def upload_fileobj(
        self,
        fileobj,
        key,
        override_tags=None,
    ):
        """
        Synchronously upload the content of a file-like object to a cloud key

        :param fileobj IOBase: File-like object to upload
        :param str key: The key to identify the uploaded object
        :param List[tuple] override_tags: List of tags as k,v tuples to be added to the
          uploaded object
        """
        # Find length of the file so we can pass it to the Azure client
        fileobj.seek(0, SEEK_END)
        length = fileobj.tell()
        fileobj.seek(0)

        extra_args = self._extra_upload_args.copy()
        tags = override_tags or self.tags
        if tags is not None:
            extra_args["tags"] = dict(tags)
        self.container_client.upload_blob(name=key,
                                          data=fileobj,
                                          overwrite=True,
                                          length=length,
                                          max_concurrency=self.max_concurrency,
                                          **extra_args)

    def create_multipart_upload(self, key):
        """No-op method because Azure has no concept of multipart uploads

        Instead of multipart upload, blob blocks are staged and then committed.
        However this does not require anything to be created up front.
        This method therefore does nothing.
        """
        pass

    def _upload_part(self, upload_metadata, key, body, part_number):
        """
        Upload a single block of this block blob.

        Uses the supplied part number to generate the block ID and returns it
        as the "PartNumber" in the part metadata.

        :param dict upload_metadata: Provider-specific metadata about the upload
          (not used in Azure)
        :param str key: The key to use in the cloud service
        :param object body: A stream-like object to upload
        :param int part_number: Part number, starting from 1
        :return: The part metadata
        :rtype: dict[str, None|str]
        """
        # Block IDs must be the same length for all bocks in the blob
        # and no greater than 64 characters. Given there is a limit of
        # 50000 blocks per blob we zero-pad the part_number to five
        # places.
        block_id = str(part_number).zfill(5)
        blob_client = self.container_client.get_blob_client(key)
        blob_client.stage_block(block_id, body, **self._extra_upload_args)
        return {"PartNumber": block_id}

    def _complete_multipart_upload(self, upload_metadata, key, parts):
        """
        Finish a "multipart upload" by committing all blocks in the blob.

        :param dict upload_metadata: Provider-specific metadata about the upload
          (not used in Azure)
        :param str key: The key to use in the cloud service
        :param parts: The list of block IDs for the blocks which compose this blob
        """
        blob_client = self.container_client.get_blob_client(key)
        block_list = [part["PartNumber"] for part in parts]
        extra_args = self._extra_upload_args.copy()
        if self.tags is not None:
            extra_args["tags"] = dict(self.tags)
        blob_client.commit_block_list(block_list, **extra_args)

    def _abort_multipart_upload(self, upload_metadata, key):
        """
        Abort the upload of a block blob

        The objective of this method is to clean up any dangling resources - in
        this case those resources are uncommitted blocks.

        :param dict upload_metadata: Provider-specific metadata about the upload
          (not used in Azure)
        :param str key: The key to use in the cloud service
        """
        # Ideally we would clean up uncommitted blocks at this point
        # however there is no way of doing that.
        # Uncommitted blocks will be discarded after 7 days or when
        # the blob is committed (if they're not included in the commit).
        # We therefore create an empty blob (thereby discarding all uploaded
        # blocks for that blob) and then delete it.
        blob_client = self.container_client.get_blob_client(key)
        blob_client.commit_block_list([], **self._extra_upload_args)
        blob_client.delete_blob()

    def delete_objects(self, paths):
        """
        Delete the objects at the specified paths

        :param List[str] paths:
        """
        try:
            # If paths is empty because the files have already been deleted then
            # delete_blobs will return successfully so we just call it with whatever
            # we were given
            responses = self.container_client.delete_blobs(*paths)
        except PartialBatchErrorException as exc:
            # Although the docs imply any errors will be returned in the response
            # object, in practice a PartialBatchErrorException is raised which contains
            # the response objects in its `parts` attribute.
            # We therefore set responses to reference the response in the exception and
            # treat it the same way we would a regular response.
            logging.warning(
                "PartialBatchErrorException received from Azure: %s" %
                exc.message)
            responses = exc.parts

        # resp is an iterator of HttpResponse objects so we check the status codes
        # which should all be 202 if successful
        errors = False
        for resp in responses:
            if resp.status_code == 404:
                logging.warning(
                    "Deletion of object %s failed because it could not be found"
                    % resp.request.url)
            elif resp.status_code != 202:
                errors = True
                logging.error(
                    'Deletion of object %s failed with error code: "%s"' %
                    (resp.request.url, resp.status_code))

        if errors:
            raise CloudProviderError(
                "Error from cloud provider while deleting objects - "
                "please check the Barman logs")
Пример #11
0
def main(args):
    blob_account_url = f"https://{args.storageaccountname}.blob.core.windows.net"

    input_blob = BlobClient.from_blob_url(args.url)
    _, filename = os.path.split(input_blob.blob_name)
    root, ext = os.path.splitext(filename)
    print(f"root: {root}")

    assert ext.lower() == ".mp4"

    gps_output_container = ContainerClient(account_url=blob_account_url,
                                           container_name="gpsdata",
                                           credential=credential)
    assert gps_output_container.exists()

    video_upload_container = ContainerClient(
        account_url=blob_account_url,
        container_name="inputvideos",
        credential=credential,
    )
    assert video_upload_container.exists()

    # Download blob into "input.mp4"
    print("Downloading video file")
    with open(local_video_filename, "wb") as fh:
        input_blob.download_blob().readinto(fh)

    # GET CREATION DATE FROM FILE
    print("Probing File")
    probe = ffmpeg.probe(filename="input.mp4")
    creation_time = probe["format"]["tags"]["creation_time"]
    creation_datetime = datetime.datetime.strptime(creation_time,
                                                   "%Y-%m-%dT%H:%M:%S.%fZ")
    print(f"Creation time: {creation_datetime}")

    # STORE JSON TO YYYY/DD/MM/GOPROFILENAME.JSON
    target_folder = os.path.join(
        str(creation_datetime.year),
        str(creation_datetime.month),
        str(creation_datetime.day),
    )
    gps_json_output_filename = os.path.join(target_folder, f"{root}.json")
    video_upload_filename = os.path.join(target_folder, f"{root}.MP4")
    print(f"JSON FILENAME: {gps_json_output_filename}")

    # Extract GPS data into gps_json_output_filename
    print("Extracting GPS data")
    result = subprocess.check_output("node process.js", shell=True)
    print(result)

    # Upload json file to gps data container
    try:
        with open("out.json", "rb") as fh:
            extracted_gps = json.load(fh)
            print("extraction successful")

        gps_output_blob = gps_output_container.upload_blob(
            name=gps_json_output_filename,
            data=json.dumps(extracted_gps),
            overwrite=True,
        )
        print(f"file '{gps_json_output_filename}' uploaded.")
        print(gps_output_blob.get_blob_properties())
    except ResourceExistsError:
        print("File already exists")

    # upload to inputvideos folder
    with open(local_video_filename, "rb") as data:
        length = os.path.getsize(local_video_filename)
        gps_output_blob = video_upload_container.upload_blob(
            name=video_upload_filename,
            data=data,
            length=length,
            overwrite=True,
        )
Пример #12
0
def sample_batch_translation_with_storage():
    import os
    from azure.core.credentials import AzureKeyCredential
    from azure.ai.documenttranslation import (DocumentTranslationClient,
                                              DocumentTranslationInput,
                                              TranslationTarget)
    from azure.storage.blob import ContainerClient, generate_container_sas, ContainerSasPermissions

    endpoint = os.environ["AZURE_DOCUMENT_TRANSLATION_ENDPOINT"]
    key = os.environ["AZURE_DOCUMENT_TRANSLATION_KEY"]
    source_storage_endpoint = os.environ["AZURE_STORAGE_SOURCE_ENDPOINT"]
    source_storage_account_name = os.environ[
        "AZURE_STORAGE_SOURCE_ACCOUNT_NAME"]
    source_storage_container_name = os.environ[
        "AZURE_STORAGE_SOURCE_CONTAINER_NAME"]
    source_storage_key = os.environ["AZURE_STORAGE_SOURCE_KEY"]
    target_storage_endpoint = os.environ["AZURE_STORAGE_TARGET_ENDPOINT"]
    target_storage_account_name = os.environ[
        "AZURE_STORAGE_TARGET_ACCOUNT_NAME"]
    target_storage_container_name = os.environ[
        "AZURE_STORAGE_TARGET_CONTAINER_NAME"]
    target_storage_key = os.environ["AZURE_STORAGE_TARGET_KEY"]

    translation_client = DocumentTranslationClient(endpoint,
                                                   AzureKeyCredential(key))

    container_client = ContainerClient(
        source_storage_endpoint,
        container_name=source_storage_container_name,
        credential=source_storage_key)

    with open("document.txt", "rb") as doc:
        container_client.upload_blob("document.txt", doc)

    source_container_sas = generate_container_sas(
        account_name=source_storage_account_name,
        container_name=source_storage_container_name,
        account_key=source_storage_key,
        permission=ContainerSasPermissions.from_string("rl"))

    target_container_sas = generate_container_sas(
        account_name=target_storage_account_name,
        container_name=target_storage_container_name,
        account_key=target_storage_key,
        permission=ContainerSasPermissions.from_string("rlwd"))

    source_container_url = source_storage_endpoint + "/" + source_storage_container_name + "?" + source_container_sas
    target_container_url = target_storage_endpoint + "/" + target_storage_container_name + "?" + target_container_sas

    translation_inputs = [
        DocumentTranslationInput(source_url=source_container_url,
                                 targets=[
                                     TranslationTarget(
                                         target_url=target_container_url,
                                         language_code="es")
                                 ],
                                 prefix="document")
    ]

    job_detail = translation_client.create_translation_job(translation_inputs)
    job_result = translation_client.wait_until_done(job_detail.id)

    if job_result.status == "Succeeded":
        print("We translated our documents!")
        if job_result.documents_failed_count > 0:
            check_documents(translation_client, job_result.id)

    elif job_result.status in ["Failed", "ValidationFailed"]:
        if job_result.error:
            print("Translation job failed: {}: {}".format(
                job_result.error.code, job_result.error.message))
        check_documents(translation_client, job_result.id)
        exit(1)

    container_client = ContainerClient(
        target_storage_endpoint,
        container_name=target_storage_container_name,
        credential=target_storage_key)

    target_container_client = container_client.from_container_url(
        target_container_url)

    with open("translated.txt", "wb") as my_blob:
        download_stream = target_container_client.download_blob("document.txt")
        my_blob.write(download_stream.readall())
Пример #13
0
def _upload_image_chunked(paths,
                          session,
                          create_url,
                          complete_url,
                          log,
                          workload_info,
                          mime,
                          use_azure_client=False,
                          imageset_id=None):  # noqa: E501
    results = []

    # get all signed urls at once
    try:
        if imageset_id:
            id_set = {
                "ids": [
                    f'imagesets/{imageset_id}/{str(uuid.uuid4())}'
                    for path in paths
                ]
            }
        else:
            id_set = {"ids": [str(uuid.uuid4()) for path in paths]}
        signed_urls = http.post_json(session, create_url, id_set)
    except Exception as ex:
        log.error("Could not get signed urls for image uploads: {}".format(ex))
        return

    index = 0

    for fpath in paths:
        try:
            file_name = os.path.basename(fpath)
            file_ext = os.path.splitext(fpath)[-1]
            if mime is not None:
                file_mime = mime
            else:
                file_mime = MIMES.get(file_ext, MIMES['.jpg'])
        except Exception as ex:
            log.error("issue with file info: {}".format(ex))

        with open(fpath, 'rb') as f:
            blob_id = id_set["ids"][index]
            info = {
                "image": {
                    "blob_id": blob_id,
                    "name": file_name,
                    "size": os.path.getsize(fpath),
                    "mimetype": file_mime
                }
            }
            index = index + 1
            try:
                # Post file to storage location
                url = signed_urls[blob_id]

                if use_azure_client:
                    url_object = urlparse(url)
                    # get SAS token from url
                    sas_token = url_object.query
                    account_url = url_object.scheme + '://' + url_object.netloc
                    container_name = url_object.path.split('/')[1]

                    # upload blob using client
                    blob_client = ContainerClient(account_url,
                                                  container_name,
                                                  credential=sas_token)
                    blob_client.upload_blob(blob_id,
                                            f,
                                            content_settings=ContentSettings(
                                                content_type=file_mime))

                    results.append(info["image"])
                else:
                    # TODO fetch project storage location to decide this
                    is_gcp_storage = url.startswith("/")
                    if is_gcp_storage:
                        url = 'https://storage.googleapis.com{}'.format(url)
                    http.put_file(session, url, f, file_mime)
                    # pop the info into a temp array, upload only once later
                    results.append(info["image"])

            except Exception as ex:
                log.error("File upload failed: {}".format(ex))

    # send the chunk of images as a bulk operation rather than per image
    try:
        url = complete_url + "?start={}".format(workload_info["start"])
        log.debug("POSTING TO: {}".format(url))
        http.post_json(session, url, {'images': results})
    except Exception as ex:
        log.error("Failed to complete workload: {}".format(ex))
Пример #14
0
            result, image = cv2.imencode('.JPEG', image_np)
            io_buf = io.BytesIO(image)
            file_name = secrets.token_hex(32) + ".jpg"
            try:
                if args.blob == "s3":
                    s3.upload_fileobj(io_buf,
                                      os.getenv('S3_BUCKET_NAME'),
                                      file_name,
                                      ExtraArgs={
                                          'ACL': 'public-read',
                                          'ContentType': 'image/jpeg'
                                      })
                elif args.blob == "azure":
                    az_container.upload_blob(file_name,
                                             io_buf,
                                             content_settings=ContentSettings(
                                                 content_type='image/jpeg'))
            except:
                continue

            occurrences = collections.Counter(items)
            occurrences['file_name'] = '"' + file_name + '"'
            mqttc.publish(names[j], payload=json.dumps(occurrences))

except KeyboardInterrupt:
    for i in range(num_feeds):
        if type[i] == "video":
            cap[i].release()
    mqttc.loop_stop()
    mqttc.disconnect()