Azure Document Intelligence (formrecouncer) — «InvalidContent» при передаче PDF-файлаPython

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Azure Document Intelligence (formrecouncer) — «InvalidContent» при передаче PDF-файла

Сообщение Anonymous »

Я загружаю PDF-файл в свое приложениеstreamlit следующим образом:
import streamlit as st

uploaded_file = st.file_uploader("Upload pdf file", type="pdf")
result = analyze_general_document(uploaded_file)

Я хочу проанализировать этот PDF-файл с помощью пакета Python Azure Document Intelligence следующим образом:
from io import BytesIO
from azure.core.credentials import AzureKeyCredential
from azure.ai.formrecognizer import DocumentAnalysisClient

def set_client(secrets: dict):
endpoint = secrets["AI_DOCS_BASE"]
key = secrets["AI_DOCS_KEY"]
document_analysis_client = DocumentAnalysisClient(endpoint=endpoint, credential=AzureKeyCredential(key))
return document_analysis_client

def analyze_general_document(uploaded_file, secrets: dict):
print(f"File type: {uploaded_file.type}")
print(f"File size: {uploaded_file.size} bytes")
client = set_client(secrets)
# poller = client.begin_analyze_document_from_url("prebuilt-document", formUrl)
poller = client.begin_analyze_document("prebuilt-document", document=uploaded_file)

Я могу успешно распечатать тип и размер файла, как вы можете видеть в выводе терминала:
File type: application/pdf
File size: 6928426 bytes

Открытие файла с помощью PyMuPDF также работает нормально.
Однако метод Begin_analyze_document выдает следующее исключение:
Traceback (most recent call last):
File "C:\Users\myuser\AppData\Local\miniconda3\envs\projectai\Lib\site-packages\streamlit\runtime\scriptrunner\exec_code.py", line 88, in exec_func_with_error_handling
result = func()
^^^^^^
File "C:\Users\myuser\AppData\Local\miniconda3\envs\projectai\Lib\site-packages\streamlit\runtime\scriptrunner\script_runner.py", line 579, in code_to_exec
exec(code, module.__dict__)
File "C:\Users\myuser\Documents\visual-studio-code\project\project-ai-docs\webapp\app.py", line 79, in
main()
File "C:\Users\myuser\Documents\visual-studio-code\project\project-ai-docs\webapp\app.py", line 61, in main
zip_content = process_pdf(uploaded_file, secrets)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\myuser\Documents\visual-studio-code\project\project-ai-docs\webapp\app_backend.py", line 40, in process_pdf
analyze_general_document(uploaded_file, secrets)
File "C:\Users\myuser\Documents\visual-studio-code\project\project-ai-docs\webapp\az_document_intelligence.py", line 18, in analyze_general_document
poller = client.begin_analyze_document("prebuilt-document", document=uploaded_file)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\myuser\AppData\Local\miniconda3\envs\projectai\Lib\site-packages\azure\core\tracing\decorator.py", line 105, in wrapper_use_tracer
return func(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\myuser\AppData\Local\miniconda3\envs\projectai\Lib\site-packages\azure\ai\formrecognizer\_document_analysis_client.py", line 129, in begin_analyze_document
return _client_op_path.begin_analyze_document( # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\myuser\AppData\Local\miniconda3\envs\projectai\Lib\site-packages\azure\core\tracing\decorator.py", line 105, in wrapper_use_tracer
return func(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\myuser\AppData\Local\miniconda3\envs\projectai\Lib\site-packages\azure\ai\formrecognizer\_generated\v2023_07_31\operations\_document_models_operations.py", line 518, in begin_analyze_document
raw_result = self._analyze_document_initial( # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\myuser\AppData\Local\miniconda3\envs\projectai\Lib\site-packages\azure\ai\formrecognizer\_generated\v2023_07_31\operations\_document_models_operations.py", line 443, in _analyze_document_initial
raise HttpResponseError(response=response)
azure.core.exceptions.HttpResponseError: (InvalidRequest) Invalid request.
Code: InvalidRequest
Message: Invalid request.
Inner error: {
"code": "InvalidContent",
"message": "The file is corrupted or format is unsupported. Refer to documentation for the list of supported formats."
}

Почему PDF-файл считается недействительным?
Я также пытался обернуть его в объект BytesIO вот так, но это тоже не сработало:
def analyze_general_document(uploaded_file, secrets: dict):
print(f"File type: {uploaded_file.type}")
print(f"File size: {uploaded_file.size} bytes")
# Read the file as bytes
file_bytes = uploaded_file.read()
client = set_client(secrets)
# poller = client.begin_analyze_document_from_url("prebuilt-document", formUrl)
poller = client.begin_analyze_document("prebuilt-document", document=BytesIO(file_bytes))


Подробнее здесь: https://stackoverflow.com/questions/792 ... assing-pdf
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»