下面的代码用于填充地图。AnalyzeResult 类只是键和值映射以及页面列表的持有者。
List<Block> blocks = result.getBlocks();
for (Block block : blocks) {
String blockId = block.getId();
analyzeResult.blockMap.put(blockId, block);
String blockType = block.getBlockType();
switch(blockType){
case AppConstant.BLOCK_PAGE :
page = new ArrayList<TextLine>();
analyzeResult.pages.add(page);
break;
case AppConstant.BLOCK_KEY_VALUE_SET :
if (block.getEntityTypes().contains(AppConstant.BLOCK_KEY)) {
analyzeResult.keyMap.put(blockId, block);
}
else {
analyzeResult.valueMap.put(blockId, block);
}
break;
}
}
paginationToken = result.getNextToken();
if (paginationToken == null) {
finished = true;
}
}
以下函数可用于获取关系并查找键值对
public List getKVRelationShip(AnalyzeResult analyzeResult) {
List listOfFormFields = new ArrayList<FormInfo>();
final Set<Map.Entry<String, Block>> entries = analyzeResult.keyMap.entrySet();
for (Map.Entry<String, Block> entry : entries) {
Block keyBlock = entry.getValue();
Block valueBlock = this.findValueBlock(keyBlock, analyzeResult.valueMap);
if(valueBlock != null){
String key = getText(keyBlock, analyzeResult.blockMap);
String val = getText(valueBlock, analyzeResult.blockMap);
key = key != null ? key.trim() : "";
val = val != null ? val.trim() : "";
FormInfo formInfo = new FormInfo(key, val, keyBlock.getPage(),
keyBlock.getGeometry().getBoundingBox().getTop(), keyBlock.getConfidence());
listOfFormFields.add(formInfo);
}
}
Collections.sort(listOfFormFields);
return listOfFormFields;
}
public String getText(Block results, Map blockMap) {
String text = "";
if (results.getRelationships() != null && results.getRelationships().size() != 0) {
for (Relationship relationship : results.getRelationships()) {
if (relationship.getType().equals(AppConstant.BLOCK_CHILD)) {
for (String childId : relationship.getIds()) {
Block word = (Block) blockMap.get(childId);
if (word.getBlockType().equals(AppConstant.BLOCK_WORD)) {
text = text + word.getText() + " ";
}
if (word.getBlockType().equals(AppConstant.BLOCK_SELECTION_ELEMENT)) {
if (word.getSelectionStatus().equals(AppConstant.BLOCK_SELECTED)) {
text = text + "X";
}
}
}
}
}
}
return text;
}
private Block findValueBlock(Block block, Map valueMap) {
Block valueBlock = null;
for (Relationship relationship : block.getRelationships()) {
if (relationship.getType().equals(AppConstant.BLOCK_VALUE)) {
for (String valueId : relationship.getIds()) {
valueBlock = (Block) valueMap.get(valueId);
}
}
}
return valueBlock;
}