How to fix TargetFileAlreadyExists error

Tristan Mac Cana 0 Reputation points
2025-07-10T11:15:35.5366667+00:00

I consistently get the following error when I have translated several different files: azure.core.exceptions.HttpResponseError: (TargetFileAlreadyExists): Target document file already exists.

127.0.0.1 - - [10/Jul/2025 10:23:40] "POST /translate_document HTTP/1.1" 500 -

The first files will translate ok but after 2 or 3 tests it fails until I clear the source/target storage containers.

Files are unique and have UUIDs so believe something else is causing issue. Help please!

here is the full translate route:

@app.route('/translate_document', methods=['POST'])
def translate_document():
    if 'file' not in request.files:
        return jsonify({'error': 'No file uploaded'}), 400

    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': 'Empty filename'}), 400

    try:
        # Generate unique filename
        original_filename = file.filename
        unique_filename = f"{uuid4()}_{original_filename}"

        # Get container client
        container_client = blob_service_client.get_container_client(target_container_name)

        # List all blobs in the translations/ folder
        print("Current blobs in 'translations/':")
        for blob in container_client.list_blobs(name_starts_with="translations/"):
            print(" -", blob.name)

        # Check if any blob ends with the original filename
        for blob in container_client.list_blobs(name_starts_with="translations/"):
            if blob.name.endswith(original_filename):
                print(f"Found existing translation: {blob.name}")
                sas_token = generate_blob_sas(
                    account_name=account_name,
                    container_name=target_container_name,
                    blob_name=blob.name,
                    account_key=account_key,
                    permission=BlobSasPermissions(read=True),
                    expiry=datetime.utcnow() + timedelta(hours=1)
                )
                translated_file_url = f"https://{account_name}.blob.core.windows.net/{target_container_name}/{blob.name}?{sas_token}"
                return jsonify({'download_url': translated_file_url})

        #  Delete any blob that ends with the original filename (to avoid Azure conflict)
        for blob in container_client.list_blobs(name_starts_with="translations/"):
            if blob.name.endswith(original_filename):
                print(f"Deleting conflicting blob: {blob.name}")
                container_client.delete_blob(blob.name)

        # Wrap file with new filename to ensure uniqueness inside the blob
        file_content = file.read()
        file.seek(0)
        wrapped_file = FileStorage(
            stream=BytesIO(file_content),
            filename=unique_filename,
            content_type=file.content_type
        )

        # Upload to source container
        blob_client = blob_service_client.get_blob_client(container="sourcefolder", blob=unique_filename)
        blob_client.upload_blob(wrapped_file, overwrite=True)

        # Construct target container URL
        target_url = f"https://{account_name}.blob.core.windows.net/{target_container_name}/translations?{target_container_sas_token}"

        # Determine language pair
        source_lang = "en"
        target_lang = request.form['target_language']
        lang_pair = f"{source_lang}-{target_lang}"
        glossary_url = glossary_urls.get(lang_pair)

        # Build translation target
        targets = [
            TranslationTarget(
                target_url=target_url,
                language=target_lang,
                glossaries=[
                    TranslationGlossary(
                        glossary_url=glossary_url,
                        file_format="Csv"
                    )
                ] if glossary_url else None
            )
        ]

        print("Glossary is being applied:", bool(glossary_url))

        # Start document translation
        input = DocumentTranslationInput(
            source_url=source_container_url,
            targets=targets
        )
        poller = document_translator.begin_translation(inputs=[input])

        # Print debug info BEFORE waiting for result
        print("Original uploaded filename:", original_filename)
        print("Unique filename (blob name):", unique_filename)
        print("Glossary URL used:", glossary_url)
        print("Target language:", target_lang)
        print("Source container URL:", source_container_url)
        print("Target container URL:", target_url)

        # Wait for result
        result = poller.result()

        for doc in result:
            print(f"Document status: {doc.status}, translated URL: {doc.translated_document_url}, glossary URL: {getattr(doc, 'glossary_document_url', 'N/A')}")
            print("Translated blob name:", doc.translated_document_url)

        # Generate SAS token for the newly translated file
        translated_blob_name = f"translations/{unique_filename}"
        sas_token = generate_blob_sas(
            account_name=account_name,
            container_name=target_container_name,
            blob_name=translated_blob_name,
            account_key=account_key,
            permission=BlobSasPermissions(read=True),
            expiry=datetime.utcnow() + timedelta(hours=1)
        )

        translated_file_url = f"https://{account_name}.blob.core.windows.net/{target_container_name}/{translated_blob_name}?{sas_token}"
        return jsonify({'download_url': translated_file_url})

    except Exception as e:
        print("Exception occurred during document translation:")
        traceback.print_exc()
        return jsonify({'error': str(e)}), 500



    
if __name__ == '__main__': app.run(debug=True)
Azure AI Translator
Azure AI Translator
An Azure service to easily conduct machine translation with a simple REST API call.
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Tristan Mac Cana 0 Reputation points
    2025-07-17T12:17:09.9533333+00:00

    It looks like I have been taking all blobs from the source container with each translation request and that is the cause of the issue.I am now working on generating unique SAS URLs for each file moving forward, hopefully will resolve the issue

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.