Это содержимое относится к следующему:🟩v4.0 (GA) | Предыдущие версии:🟦v3.1 (GA)
Это содержимое относится к следующему:🟩v3.1 (GA) | Последняя версия:🟪v4.0 (GA)
Примечание.
Дополнительные возможности доступны во всех моделях, кроме модели визитки.
Возможности
Аналитика документов поддерживает более сложные и модульные возможности анализа. Используйте возможности надстройки, чтобы расширить результаты, включив в них дополнительные возможности, извлечённые из ваших документов. Некоторые дополнительные функции предоставляются за дополнительную плату. Эти необязательные функции можно включить и отключить в зависимости от сценария извлечения документов. Чтобы включить функцию, добавьте связанное имя функции в features свойство строки запроса. Вы можете включить в запросе несколько дополнительных функций, указав список функций, разделённых запятыми. Следующие дополнительные возможности доступны начиная с версии 2023-07-31 (GA) и в более поздних выпусках.
Примечание.
Не все модели или типы файлов Microsoft Office поддерживают возможности надстройки. Дополнительные сведения см. в статьеоб извлечении данных модели.
Доступность версий
| Возможность надстройки |
Дополнение/Бесплатно |
2024-11-30 (GA) |
2023-07-31 (GA) |
2022-08-31 (GA) |
v2.1 (GA) |
| Извлечение штрихкодов |
Бесплатно |
✔️ |
✔️ |
Недоступно |
Недоступно |
| Распознавание языка |
Бесплатно |
✔️ |
✔️ |
Недоступно |
Недоступно |
| Пары "ключ — значение" |
Бесплатно |
✔️ |
Недоступно |
Недоступно |
Недоступно |
| Pdf-файл, доступный для поиска |
Бесплатно |
✔️ |
Недоступно |
Недоступно |
Недоступно |
| Извлечение свойств шрифта |
Дополнение |
✔️ |
✔️ |
Недоступно |
Недоступно |
| Извлечение формул |
Дополнение |
✔️ |
✔️ |
Недоступно |
Недоступно |
| Извлечение в высоком разрешении |
Дополнение |
✔️ |
✔️ |
Недоступно |
Недоступно |
| Поля запроса |
Дополнение |
✔️ |
Недоступно |
Недоступно |
Недоступно |
✱ Надстройка — поля запроса тарифицируются иначе, чем другие функции надстройки. Подробные сведения см. в разделе Цены.
** Дополнение — PDF-файл с возможностью поиска доступен только для модели Read в виде дополнительной функции.
✱ Файлы Microsoft Office в настоящее время не поддерживаются.
Задача распознавания небольшого текста из документов большого размера, таких как инженерные рисунки, является проблемой. Часто текст смешан с другими графическими элементами и имеет различные шрифты, размеры и ориентации. Кроме того, текст можно разбить на отдельные части или соединить с другими символами. Document Intelligence теперь поддерживает извлечение содержимого из документов этих типов с помощью функции ocr.highResolution. Вы получаете улучшенное качество извлечения содержимого из документов A1/A2/A3, включив эту возможность надстройки.
{your-resource-endpoint}.cognitiveservices.azure.com/documentintelligence/documentModels/prebuilt-layout:analyze?api-version=2024-11-30&features=ocrHighResolution
# Analyze a document at a URL:
formUrl = "https://github.com/Azure-Samples/document-intelligence-code-samples/blob/main/Data/add-on/add-on-highres.png?raw=true"
poller = document_intelligence_client.begin_analyze_document(
"prebuilt-layout",
AnalyzeDocumentRequest(url_source=formUrl),
features=[DocumentAnalysisFeature.OCR_HIGH_RESOLUTION], # Specify which add-on capabilities to enable.
)
result: AnalyzeResult = poller.result()
# [START analyze_with_highres]
if result.styles and any([style.is_handwritten for style in result.styles]):
print("Document contains handwritten content")
else:
print("Document does not contain handwritten content")
for page in result.pages:
print(f"----Analyzing layout from page #{page.page_number}----")
print(f"Page has width: {page.width} and height: {page.height}, measured with unit: {page.unit}")
if page.lines:
for line_idx, line in enumerate(page.lines):
words = get_words(page, line)
print(
f"...Line # {line_idx} has word count {len(words)} and text '{line.content}' "
f"within bounding polygon '{line.polygon}'"
)
for word in words:
print(f"......Word '{word.content}' has a confidence of {word.confidence}")
if page.selection_marks:
for selection_mark in page.selection_marks:
print(
f"Selection mark is '{selection_mark.state}' within bounding polygon "
f"'{selection_mark.polygon}' and has a confidence of {selection_mark.confidence}"
)
if result.tables:
for table_idx, table in enumerate(result.tables):
print(f"Table # {table_idx} has {table.row_count} rows and " f"{table.column_count} columns")
if table.bounding_regions:
for region in table.bounding_regions:
print(f"Table # {table_idx} location on page: {region.page_number} is {region.polygon}")
for cell in table.cells:
print(f"...Cell[{cell.row_index}][{cell.column_index}] has text '{cell.content}'")
if cell.bounding_regions:
for region in cell.bounding_regions:
print(f"...content on page {region.page_number} is within bounding polygon '{region.polygon}'")
"styles": [true],
"pages": [
{
"page_number": 1,
"width": 1000,
"height": 800,
"unit": "px",
"lines": [
{
"line_idx": 1,
"content": "This",
"polygon": [10, 20, 30, 40],
"words": [
{
"content": "This",
"confidence": 0.98
}
]
}
],
"selection_marks": [
{
"state": "selected",
"polygon": [50, 60, 70, 80],
"confidence": 0.91
}
]
}
],
"tables": [
{
"table_idx": 1,
"row_count": 3,
"column_count": 4,
"bounding_regions": [
{
"page_number": 1,
"polygon": [100, 200, 300, 400]
}
],
"cells": [
{
"row_index": 1,
"column_index": 1,
"content": "Content 1",
"bounding_regions": [
{
"page_number": 1,
"polygon": [110, 210, 310, 410]
}
]
}
]
}
]
{your-resource-endpoint}.cognitiveservices.azure.com/formrecognizer/documentModels/prebuilt-layout:analyze?api-version=2023-07-31&features=ocrHighResolution
# Analyze a document at a URL:
url = "(https://github.com/Azure-Samples/document-intelligence-code-samples/blob/main/Data/add-on/add-on-highres.png?raw=true"
poller = document_analysis_client.begin_analyze_document_from_url(
"prebuilt-layout", document_url=url, features=[AnalysisFeature.OCR_HIGH_RESOLUTION] # Specify which add-on capabilities to enable.
)
result = poller.result()
# [START analyze_with_highres]
if any([style.is_handwritten for style in result.styles]):
print("Document contains handwritten content")
else:
print("Document does not contain handwritten content")
for page in result.pages:
print(f"----Analyzing layout from page #{page.page_number}----")
print(
f"Page has width: {page.width} and height: {page.height}, measured with unit: {page.unit}"
)
for line_idx, line in enumerate(page.lines):
words = line.get_words()
print(
f"...Line # {line_idx} has word count {len(words)} and text '{line.content}' "
f"within bounding polygon '{format_polygon(line.polygon)}'"
)
for word in words:
print(
f"......Word '{word.content}' has a confidence of {word.confidence}"
)
for selection_mark in page.selection_marks:
print(
f"Selection mark is '{selection_mark.state}' within bounding polygon "
f"'{format_polygon(selection_mark.polygon)}' and has a confidence of {selection_mark.confidence}"
)
for table_idx, table in enumerate(result.tables):
print(
f"Table # {table_idx} has {table.row_count} rows and "
f"{table.column_count} columns"
)
for region in table.bounding_regions:
print(
f"Table # {table_idx} location on page: {region.page_number} is {format_polygon(region.polygon)}"
)
for cell in table.cells:
print(
f"...Cell[{cell.row_index}][{cell.column_index}] has text '{cell.content}'"
)
for region in cell.bounding_regions:
print(
f"...content on page {region.page_number} is within bounding polygon '{format_polygon(region.polygon)}'"
)
"styles": [true],
"pages": [
{
"page_number": 1,
"width": 1000,
"height": 800,
"unit": "px",
"lines": [
{
"line_idx": 1,
"content": "This",
"polygon": [10, 20, 30, 40],
"words": [
{
"content": "This",
"confidence": 0.98
}
]
}
],
"selection_marks": [
{
"state": "selected",
"polygon": [50, 60, 70, 80],
"confidence": 0.91
}
]
}
],
"tables": [
{
"table_idx": 1,
"row_count": 3,
"column_count": 4,
"bounding_regions": [
{
"page_number": 1,
"polygon": [100, 200, 300, 400]
}
],
"cells": [
{
"row_index": 1,
"column_index": 1,
"content": "Content 1",
"bounding_regions": [
{
"page_number": 1,
"polygon": [110, 210, 310, 410]
}
]
}
]
}
]
Функция ocr.formula извлекает все обнаруженные формулы, такие как математические уравнения, в коллекции formulas как объект верхнего уровня в content. Внутри contentобнаруженные формулы представлены как :formula:. Каждая запись в этой коллекции представляет собой формулу с указанием типа формулы как inline или display, её представления в LaTeX как value, а также её координат polygon. Изначально формулы отображаются в конце каждой страницы.
Примечание.
Оценка confidence жестко закодирована.
{your-resource-endpoint}.cognitiveservices.azure.com/documentintelligence/documentModels/prebuilt-layout:analyze?api-version=2024-11-30&features=formulas
# Analyze a document at a URL:
formUrl = "https://github.com/Azure-Samples/document-intelligence-code-samples/blob/main/Data/add-on/layout-formulas.png?raw=true"
poller = document_intelligence_client.begin_analyze_document(
"prebuilt-layout",
AnalyzeDocumentRequest(url_source=formUrl),
features=[DocumentAnalysisFeature.FORMULAS], # Specify which add-on capabilities to enable
)
result: AnalyzeResult = poller.result()
# [START analyze_formulas]
for page in result.pages:
print(f"----Formulas detected from page #{page.page_number}----")
if page.formulas:
inline_formulas = [f for f in page.formulas if f.kind == "inline"]
display_formulas = [f for f in page.formulas if f.kind == "display"]
# To learn the detailed concept of "polygon" in the following content, visit: https://aka.ms/bounding-region
print(f"Detected {len(inline_formulas)} inline formulas.")
for formula_idx, formula in enumerate(inline_formulas):
print(f"- Inline #{formula_idx}: {formula.value}")
print(f" Confidence: {formula.confidence}")
print(f" Bounding regions: {formula.polygon}")
print(f"\nDetected {len(display_formulas)} display formulas.")
for formula_idx, formula in enumerate(display_formulas):
print(f"- Display #{formula_idx}: {formula.value}")
print(f" Confidence: {formula.confidence}")
print(f" Bounding regions: {formula.polygon}")
"content": ":formula:",
"pages": [
{
"pageNumber": 1,
"formulas": [
{
"kind": "inline",
"value": "\\frac { \\partial a } { \\partial b }",
"polygon": [...],
"span": {...},
"confidence": 0.99
},
{
"kind": "display",
"value": "y = a \\times b + a \\times c",
"polygon": [...],
"span": {...},
"confidence": 0.99
}
]
}
]
{your-resource-endpoint}.cognitiveservices.azure.com/formrecognizer/documentModels/prebuilt-layout:analyze?api-version=2023-07-31&features=formulas
# Analyze a document at a URL:
url = "https://github.com/Azure-Samples/document-intelligence-code-samples/blob/main/Data/add-on/layout-formulas.png?raw=true"
poller = document_analysis_client.begin_analyze_document_from_url(
"prebuilt-layout", document_url=url, features=[AnalysisFeature.FORMULAS] # Specify which add-on capabilities to enable
)
result = poller.result()
# [START analyze_formulas]
for page in result.pages:
print(f"----Formulas detected from page #{page.page_number}----")
inline_formulas = [f for f in page.formulas if f.kind == "inline"]
display_formulas = [f for f in page.formulas if f.kind == "display"]
print(f"Detected {len(inline_formulas)} inline formulas.")
for formula_idx, formula in enumerate(inline_formulas):
print(f"- Inline #{formula_idx}: {formula.value}")
print(f" Confidence: {formula.confidence}")
print(f" Bounding regions: {format_polygon(formula.polygon)}")
print(f"\nDetected {len(display_formulas)} display formulas.")
for formula_idx, formula in enumerate(display_formulas):
print(f"- Display #{formula_idx}: {formula.value}")
print(f" Confidence: {formula.confidence}")
print(f" Bounding regions: {format_polygon(formula.polygon)}")
"content": ":formula:",
"pages": [
{
"pageNumber": 1,
"formulas": [
{
"kind": "inline",
"value": "\\frac { \\partial a } { \\partial b }",
"polygon": [...],
"span": {...},
"confidence": 0.99
},
{
"kind": "display",
"value": "y = a \\times b + a \\times c",
"polygon": [...],
"span": {...},
"confidence": 0.99
}
]
}
]
Возможность ocr.font извлекает все свойства шрифта из текста, извлечённого в коллекции styles, как объект верхнего уровня в content. Каждый объект стиля задает одно свойство шрифта, фрагмент текста, к которому оно применяется, и соответствующую ему оценку уверенности. Существующее свойство style расширено дополнительными свойствами шрифта, такими как similarFontFamily для шрифта текста, fontStyle для таких начертаний, как курсив и обычное, fontWeight для полужирного или обычного начертания, color для цвета текста и backgroundColor для цвета ограничивающей рамки текста.
{your-resource-endpoint}.cognitiveservices.azure.com/documentintelligence/documentModels/prebuilt-layout:analyze?api-version=2024-11-30&features=styleFont
# Analyze a document at a URL:
formUrl = "https://github.com/Azure-Samples/document-intelligence-code-samples/blob/main/Data/receipt/receipt-with-tips.png?raw=true"
poller = document_intelligence_client.begin_analyze_document(
"prebuilt-layout",
AnalyzeDocumentRequest(url_source=formUrl),
features=[DocumentAnalysisFeature.STYLE_FONT] # Specify which add-on capabilities to enable.
)
result: AnalyzeResult = poller.result()
# [START analyze_fonts]
# DocumentStyle has the following font related attributes:
similar_font_families = defaultdict(list) # e.g., 'Arial, sans-serif
font_styles = defaultdict(list) # e.g, 'italic'
font_weights = defaultdict(list) # e.g., 'bold'
font_colors = defaultdict(list) # in '#rrggbb' hexadecimal format
font_background_colors = defaultdict(list) # in '#rrggbb' hexadecimal format
if result.styles and any([style.is_handwritten for style in result.styles]):
print("Document contains handwritten content")
else:
print("Document does not contain handwritten content")
return
print("\n----Fonts styles detected in the document----")
# Iterate over the styles and group them by their font attributes.
for style in result.styles:
if style.similar_font_family:
similar_font_families[style.similar_font_family].append(style)
if style.font_style:
font_styles[style.font_style].append(style)
if style.font_weight:
font_weights[style.font_weight].append(style)
if style.color:
font_colors[style.color].append(style)
if style.background_color:
font_background_colors[style.background_color].append(style)
print(f"Detected {len(similar_font_families)} font families:")
for font_family, styles in similar_font_families.items():
print(f"- Font family: '{font_family}'")
print(f" Text: '{get_styled_text(styles, result.content)}'")
print(f"\nDetected {len(font_styles)} font styles:")
for font_style, styles in font_styles.items():
print(f"- Font style: '{font_style}'")
print(f" Text: '{get_styled_text(styles, result.content)}'")
print(f"\nDetected {len(font_weights)} font weights:")
for font_weight, styles in font_weights.items():
print(f"- Font weight: '{font_weight}'")
print(f" Text: '{get_styled_text(styles, result.content)}'")
print(f"\nDetected {len(font_colors)} font colors:")
for font_color, styles in font_colors.items():
print(f"- Font color: '{font_color}'")
print(f" Text: '{get_styled_text(styles, result.content)}'")
print(f"\nDetected {len(font_background_colors)} font background colors:")
for font_background_color, styles in font_background_colors.items():
print(f"- Font background color: '{font_background_color}'")
print(f" Text: '{get_styled_text(styles, result.content)}'")
"content": "Foo bar",
"styles": [
{
"similarFontFamily": "Arial, sans-serif",
"spans": [ { "offset": 0, "length": 3 } ],
"confidence": 0.98
},
{
"similarFontFamily": "Times New Roman, serif",
"spans": [ { "offset": 4, "length": 3 } ],
"confidence": 0.98
},
{
"fontStyle": "italic",
"spans": [ { "offset": 1, "length": 2 } ],
"confidence": 0.98
},
{
"fontWeight": "bold",
"spans": [ { "offset": 2, "length": 3 } ],
"confidence": 0.98
},
{
"color": "#FF0000",
"spans": [ { "offset": 4, "length": 2 } ],
"confidence": 0.98
},
{
"backgroundColor": "#00FF00",
"spans": [ { "offset": 5, "length": 2 } ],
"confidence": 0.98
}
]
{your-resource-endpoint}.cognitiveservices.azure.com/formrecognizer/documentModels/prebuilt-layout:analyze?api-version=2023-07-31&features=styleFont
# Analyze a document at a URL:
url = "https://github.com/Azure-Samples/document-intelligence-code-samples/blob/main/Data/receipt/receipt-with-tips.png?raw=true"
poller = document_analysis_client.begin_analyze_document_from_url(
"prebuilt-layout", document_url=url, features=[AnalysisFeature.STYLE_FONT] # Specify which add-on capabilities to enable.
)
result = poller.result()
# [START analyze_fonts]
# DocumentStyle has the following font related attributes:
similar_font_families = defaultdict(list) # e.g., 'Arial, sans-serif
font_styles = defaultdict(list) # e.g, 'italic'
font_weights = defaultdict(list) # e.g., 'bold'
font_colors = defaultdict(list) # in '#rrggbb' hexadecimal format
font_background_colors = defaultdict(list) # in '#rrggbb' hexadecimal format
if any([style.is_handwritten for style in result.styles]):
print("Document contains handwritten content")
else:
print("Document does not contain handwritten content")
print("\n----Fonts styles detected in the document----")
# Iterate over the styles and group them by their font attributes.
for style in result.styles:
if style.similar_font_family:
similar_font_families[style.similar_font_family].append(style)
if style.font_style:
font_styles[style.font_style].append(style)
if style.font_weight:
font_weights[style.font_weight].append(style)
if style.color:
font_colors[style.color].append(style)
if style.background_color:
font_background_colors[style.background_color].append(style)
print(f"Detected {len(similar_font_families)} font families:")
for font_family, styles in similar_font_families.items():
print(f"- Font family: '{font_family}'")
print(f" Text: '{get_styled_text(styles, result.content)}'")
print(f"\nDetected {len(font_styles)} font styles:")
for font_style, styles in font_styles.items():
print(f"- Font style: '{font_style}'")
print(f" Text: '{get_styled_text(styles, result.content)}'")
print(f"\nDetected {len(font_weights)} font weights:")
for font_weight, styles in font_weights.items():
print(f"- Font weight: '{font_weight}'")
print(f" Text: '{get_styled_text(styles, result.content)}'")
print(f"\nDetected {len(font_colors)} font colors:")
for font_color, styles in font_colors.items():
print(f"- Font color: '{font_color}'")
print(f" Text: '{get_styled_text(styles, result.content)}'")
print(f"\nDetected {len(font_background_colors)} font background colors:")
for font_background_color, styles in font_background_colors.items():
print(f"- Font background color: '{font_background_color}'")
print(f" Text: '{get_styled_text(styles, result.content)}'")
"content": "Foo bar",
"styles": [
{
"similarFontFamily": "Arial, sans-serif",
"spans": [ { "offset": 0, "length": 3 } ],
"confidence": 0.98
},
{
"similarFontFamily": "Times New Roman, serif",
"spans": [ { "offset": 4, "length": 3 } ],
"confidence": 0.98
},
{
"fontStyle": "italic",
"spans": [ { "offset": 1, "length": 2 } ],
"confidence": 0.98
},
{
"fontWeight": "bold",
"spans": [ { "offset": 2, "length": 3 } ],
"confidence": 0.98
},
{
"color": "#FF0000",
"spans": [ { "offset": 4, "length": 2 } ],
"confidence": 0.98
},
{
"backgroundColor": "#00FF00",
"spans": [ { "offset": 5, "length": 2 } ],
"confidence": 0.98
}
]
Возможность ocr.barcode извлекает все обнаруженные штрихкоды из коллекции barcodes в виде объекта верхнего уровня в content. Внутри content обнаруженные штрихкоды отображаются как :barcode:. Каждая запись в этой коллекции представляет собой штрихкод и включает тип штрихкода в виде kind, закодированное в штрихкоде содержимое в виде value, а также его координаты polygon. Изначально штрихкоды отображаются в конце каждой страницы.
confidence жёстко задан равным 1.
Поддерживаемые типы штрихкодов
|
Тип штрихкода |
Пример |
QR Code |
|
Code 39 |
|
Code 93 |
|
Code 128 |
|
UPC (UPC-A & UPC-E) |
|
PDF417 |
|
EAN-8 |
|
EAN-13 |
|
Codabar |
|
Databar |
|
Databar Расширенный |
|
ITF |
|
Data Matrix |
|
{your-resource-endpoint}.cognitiveservices.azure.com/documentintelligence/documentModels/prebuilt-layout:analyze?api-version=2024-11-30&features=barcodes
# Analyze a document at a URL:
formUrl = "https://github.com/Azure-Samples/document-intelligence-code-samples/blob/main/Data/add-on/add-on-barcodes.jpg?raw=true"
poller = document_intelligence_client.begin_analyze_document(
"prebuilt-read",
AnalyzeDocumentRequest(url_source=formUrl),
features=[DocumentAnalysisFeature.BARCODES] # Specify which add-on capabilities to enable.
)
result: AnalyzeResult = poller.result()
# [START analyze_barcodes]
# Iterate over extracted barcodes on each page.
for page in result.pages:
print(f"----Barcodes detected from page #{page.page_number}----")
if page.barcodes:
print(f"Detected {len(page.barcodes)} barcodes:")
for barcode_idx, barcode in enumerate(page.barcodes):
print(f"- Barcode #{barcode_idx}: {barcode.value}")
print(f" Kind: {barcode.kind}")
print(f" Confidence: {barcode.confidence}")
print(f" Bounding regions: {barcode.polygon}")
----Barcodes detected from page #1----
Detected 2 barcodes:
- Barcode #0: 123456
Kind: QRCode
Confidence: 0.95
Bounding regions: [10.5, 20.5, 30.5, 40.5]
- Barcode #1: 789012
Kind: QRCode
Confidence: 0.98
Bounding regions: [50.5, 60.5, 70.5, 80.5]
{your-resource-endpoint}.cognitiveservices.azure.com/formrecognizer/documentModels/prebuilt-layout:analyze?api-version=2023-07-31&features=barcodes
# Analyze a document at a URL:
url = "https://github.com/Azure-Samples/document-intelligence-code-samples/blob/main/Data/add-on/add-on-barcodes.jpg?raw=true"
poller = document_analysis_client.begin_analyze_document_from_url(
"prebuilt-layout", document_url=url, features=[AnalysisFeature.BARCODES] # Specify which add-on capabilities to enable.
)
result = poller.result()
# [START analyze_barcodes]
# Iterate over extracted barcodes on each page.
for page in result.pages:
print(f"----Barcodes detected from page #{page.page_number}----")
print(f"Detected {len(page.barcodes)} barcodes:")
for barcode_idx, barcode in enumerate(page.barcodes):
print(f"- Barcode #{barcode_idx}: {barcode.value}")
print(f" Kind: {barcode.kind}")
print(f" Confidence: {barcode.confidence}")
print(f" Bounding regions: {format_polygon(barcode.polygon)}")
----Barcodes detected from page #1----
Detected 2 barcodes:
- Barcode #0: 123456
Kind: QRCode
Confidence: 0.95
Bounding regions: [10.5, 20.5, 30.5, 40.5]
- Barcode #1: 789012
Kind: QRCode
Confidence: 0.98
Bounding regions: [50.5, 60.5, 70.5, 80.5]
Распознавание языка
Добавление функции languages к запросу analyzeResult позволяет определить обнаруженный основной язык для каждой строки текста вместе с confidence в коллекции languages в разделе analyzeResult.
{your-resource-endpoint}.cognitiveservices.azure.com/documentintelligence/documentModels/prebuilt-layout:analyze?api-version=2024-11-30&features=languages
# Analyze a document at a URL:
formUrl = "https://github.com/Azure-Samples/document-intelligence-code-samples/blob/main/Data/add-on/add-on-fonts_and_languages.png?raw=true"
poller = document_intelligence_client.begin_analyze_document(
"prebuilt-layout",
AnalyzeDocumentRequest(url_source=formUrl),
features=[DocumentAnalysisFeature.LANGUAGES] # Specify which add-on capabilities to enable.
)
result: AnalyzeResult = poller.result()
# [START analyze_languages]
print("----Languages detected in the document----")
if result.languages:
print(f"Detected {len(result.languages)} languages:")
for lang_idx, lang in enumerate(result.languages):
print(f"- Language #{lang_idx}: locale '{lang.locale}'")
print(f" Confidence: {lang.confidence}")
print(
f" Text: '{','.join([result.content[span.offset : span.offset + span.length] for span in lang.spans])}'"
)
"languages": [
{
"spans": [
{
"offset": 0,
"length": 131
}
],
"locale": "en",
"confidence": 0.7
},
]
{your-resource-endpoint}.cognitiveservices.azure.com/formrecognizer/documentModels/prebuilt-layout:analyze?api-version=2023-07-31&features=languages
# Analyze a document at a URL:
url = "https://github.com/Azure-Samples/document-intelligence-code-samples/blob/main/Data/add-on/add-on-fonts_and_languages.png?raw=true"
poller = document_analysis_client.begin_analyze_document_from_url(
"prebuilt-layout", document_url=url, features=[AnalysisFeature.LANGUAGES] # Specify which add-on capabilities to enable.
)
result = poller.result()
# [START analyze_languages]
print("----Languages detected in the document----")
print(f"Detected {len(result.languages)} languages:")
for lang_idx, lang in enumerate(result.languages):
print(f"- Language #{lang_idx}: locale '{lang.locale}'")
print(f" Confidence: {lang.confidence}")
print(f" Text: '{','.join([result.content[span.offset : span.offset + span.length] for span in lang.spans])}'")
"languages": [
{
"spans": [
{
"offset": 0,
"length": 131
}
],
"locale": "en",
"confidence": 0.7
},
]
Pdf-файл, доступный для поиска
Возможность PDF с возможностью поиска позволяет преобразовать аналоговый PDF-файл( например, сканированный PDF-файл в PDF-файл с внедренным текстом). Встроенный текст позволяет выполнять глубокий поиск по тексту в содержимом, извлечённом из PDF, путём наложения обнаруженных текстовых элементов поверх файлов изображений.
Внимание
- В настоящее время только модель Read
prebuilt-read поддерживает функцию поиска по PDF. При использовании этой функции укажите modelId как prebuilt-read.
- PDF с возможностью поиска входит в модель
2024-11-30(GA)prebuilt-read без платы за использование при стандартной работе с PDF.
Использование PDF с возможностью поиска
Чтобы использовать PDF с возможностью поиска, выполните запрос POST с помощью операции Analyze и укажите формат вывода как pdf:
POST /documentModels/prebuilt-read:analyze?output=pdf
{...}
202
Analyze После завершения операции выполните GET запрос на получение Analyze результатов операции.
После успешного завершения PDF-файл можно получить и скачать как application/pdf. Эта операция позволяет напрямую загружать внедренную текстовую форму PDF вместо JSON в кодировке Base64.
// Monitor the operation until completion.
GET /documentModels/prebuilt-read/analyzeResults/{resultId}
200
{...}
// Upon successful completion, retrieve the PDF as application/pdf.
GET /documentModels/prebuilt-read/analyzeResults/{resultId}/pdf
200 OK
Content-Type: application/pdf
Пары "Ключ-значение"
В более ранних версиях API prebuilt-document модель извлекала пары "ключ — значение" из форм и документов. При добавлении функции к предварительно созданному макету модель макета keyValuePairs теперь выдает те же результаты.
Пары "ключ-значение" — это отдельные фрагменты внутри документа, которые определяют метку или ключ и связанный с ними ответ или значение. В структурированной форме эти пары могут быть меткой и значением, которое пользователь указал для данного поля. В неструктурированном документе они могут быть датой подписания договора на основании текста в абзаце. Модель искусственного интеллекта предназначена для извлечения идентифицируемых ключей и значений на основе широкого спектра типов документов, форматов и структур.
Ключи также могут существовать в изоляции, когда модель обнаруживает, что ключ существует, но с ним не связано ни одно значение, или при обработке необязательных полей. Например, в некоторых случаях поле для второго имени в форме можно оставить пустым. Пары ключ-значение являются фрагментами текста, содержащимися в документе. Для документов, в которых одно и то же понятие описывается по-разному, например customer/user, соответствующим ключом будет либо customer, либо user (в зависимости от контекста).
REST API
{your-resource-endpoint}.cognitiveservices.azure.com/documentintelligence/documentModels/prebuilt-layout:analyze?api-version=2024-11-30&features=keyValuePairs
Поля запроса
Поля запросов — это возможность расширения схемы, извлеченной из любой предварительно созданной модели, или определения определенного имени ключа при переменной имени ключа. Чтобы использовать поля запроса, задайте функции queryFields и укажите список имен полей с разделием запятыми в свойстве queryFields .
Аналитика документов теперь поддерживает извлечение полей запросов. При извлечении полей по запросу вы можете добавлять поля в процесс извлечения с помощью запроса без дополнительного обучения.
Используйте поля запроса, если необходимо расширить схему предварительно созданной или пользовательской модели или извлечь несколько полей с выходными данными макета.
Поля запроса доступны только как дополнительная функция уровня «Премиум». Для получения наилучших результатов определите поля, которые требуется извлечь, используя стиль camelCase или PascalCase для имен полей, состоящих из нескольких слов.
Поля запросов поддерживают не более 20 полей на запрос. Если документ содержит значение для поля, возвращается поле и значение.
Этот выпуск имеет новую реализацию возможностей полей запроса, которая имеет более низкую цену, чем более ранняя реализация, и должна быть проверена.
Примечание.
Извлечение полей по запросу в Document Intelligence Studio в настоящее время доступно для моделей Layout и Prebuilt через API 2024-11-30 (GA), за исключением американских налоговых моделей W2, 1098 и 1099.
Для извлечения полей запроса укажите поля, которые необходимо извлечь, и аналитика документов анализирует документ соответствующим образом. Приведем пример:
Если вы обрабатываете контракт в Студии аналитики документов, используйте версию 2024-11-30 (GA):
Вы можете передать список меток полей, например Party1, Party2, TermsOfUse, PaymentTermsи PaymentDateTermEndDate как часть analyze document запроса.
Аналитика документов может анализировать и извлекать данные поля и возвращать значения в структурированных выходных данных JSON.
В дополнение к полям запроса ответ включает текст, таблицы, метки выделения и другие соответствующие данные.
{your-resource-endpoint}.cognitiveservices.azure.com/documentintelligence/documentModels/prebuilt-layout:analyze?api-version=2024-11-30&features=queryFields&queryFields=TERMS
# Analyze a document at a URL:
formUrl = "https://github.com/Azure-Samples/document-intelligence-code-samples/blob/main/Data/invoice/simple-invoice.png?raw=true"
poller = document_intelligence_client.begin_analyze_document(
"prebuilt-layout",
AnalyzeDocumentRequest(url_source=formUrl),
features=[DocumentAnalysisFeature.QUERY_FIELDS], # Specify which add-on capabilities to enable.
query_fields=["Address", "InvoiceNumber"], # Set the features and provide a comma-separated list of field names.
)
result: AnalyzeResult = poller.result()
print("Here are extra fields in result:\n")
if result.documents:
for doc in result.documents:
if doc.fields and doc.fields["Address"]:
print(f"Address: {doc.fields['Address'].value_string}")
if doc.fields and doc.fields["InvoiceNumber"]:
print(f"Invoice number: {doc.fields['InvoiceNumber'].value_string}")
Address: 1 Redmond way Suite 6000 Redmond, WA Sunnayvale, 99243
Invoice number: 34278587
Следующие шаги