【nougat推理】pdf转markdown文件代码demo示例web_demo示例

2024-04-25 17:44

本文主要是介绍【nougat推理】pdf转markdown文件代码demo示例web_demo示例,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录

  • 模型介绍
  • 安装依赖
  • 直接使用
  • 搭建web并生成.md文件
  • 测试结果

模型介绍

Nougat是一个名为Donut的模型,它经过训练,可以将PDF文档转录成Markdown格式文档。该模型由Swin Transformer作为视觉编码器,以及mBART模型作为文本解码器组成。

该模型被训练成在只给出PDF图像像素作为输入的情况下,自回归地预测Markdown格式。
https://huggingface.co/facebook/nougat-base
在这里插入图片描述

安装依赖

pip install nltk python-Levenshtein
pip install spaces
pip install git+https://github.com/facebookresearch/nougat

直接使用

from huggingface_hub import hf_hub_download
import re
from PIL import Image
from pdf2image import convert_from_path
from transformers import NougatProcessor, VisionEncoderDecoderModel
from datasets import load_dataset
import torch
import osprocessor = NougatProcessor.from_pretrained("/your/model/path/nougat-base")
model = VisionEncoderDecoderModel.from_pretrained("/your/model/path/nougat-base")device = "cuda"
model.to(device)# prepare PDF image for the model
pdf_file = 'your/pdf_data/path/xxx.pdf'
pages = convert_from_path(pdf_file, 300)  # 300 是输出图片的 DPI(每英寸点数)
# 创建保存图片的目录
output_dir = os.path.join(os.path.dirname(pdf_file), 'images')
os.makedirs(output_dir, exist_ok=True)for i, page in enumerate(pages):image_path = os.path.join(output_dir, f'page_{i + 1}.jpg')page.save(image_path, 'JPEG')image = Image.open(image_path)print("*"*30,f"第{i}页","*"*30)pixel_values = processor(image, return_tensors="pt").pixel_values# generate transcription (here we only generate 30 tokens)outputs = model.generate(pixel_values.to(device),min_length=1,max_new_tokens=3000,bad_words_ids=[[processor.tokenizer.unk_token_id]],)sequences = processor.batch_decode(outputs, skip_special_tokens=True)for sequence in sequences:sequence = processor.post_process_generation(sequence, fix_markdown=False)# note: we're using repr here such for the sake of printing the \n characters, feel free to just print the sequenceprint(repr(sequence)

搭建web并生成.md文件

from huggingface_hub import hf_hub_download
import re
from PIL import Image
import requests
from nougat.dataset.rasterize import rasterize_paper
from transformers import NougatProcessor, VisionEncoderDecoderModel
import torch
import gradio as gr
import uuid
import os
import spacesprocessor = NougatProcessor.from_pretrained("/your/model/path/nougat-base")
model = VisionEncoderDecoderModel.from_pretrained("/your/model/path/nougat-base")device = "cuda" if torch.cuda.is_available() else "cpu"
model.to(device) def get_pdf(pdf_link):unique_filename = f"{os.getcwd()}/downloaded_paper_{uuid.uuid4().hex}.pdf"response = requests.get(pdf_link)if response.status_code == 200:with open(unique_filename, 'wb') as pdf_file:pdf_file.write(response.content)print("PDF downloaded successfully.")else:print("Failed to download the PDF.")return unique_filename@spaces.GPU
def predict(image):#为模型准备PDF图像image = Image.open(image)pixel_values = processor(image, return_tensors="pt").pixel_valuesoutputs = model.generate(pixel_values.to(device),min_length=1,max_new_tokens=3000,bad_words_ids=[[processor.tokenizer.unk_token_id]],)page_sequence = processor.batch_decode(outputs, skip_special_tokens=True)[0]page_sequence = processor.post_process_generation(page_sequence, fix_markdown=False)return page_sequencedef inference(pdf_file, pdf_link):if pdf_file is None:if pdf_link == '':print("未上传任何文件,也未提供任何链接")return "未提供任何数据。上传一个pdf文件或提供一个pdf链接,然后重试!"else:file_name = get_pdf(pdf_link)else:file_name = pdf_file.namepdf_name = pdf_file.name.split('/')[-1].split('.')[0]images = rasterize_paper(file_name, return_pil=True)sequence = ""# 推理每一页并合并for image in images:sequence += predict(image)content = sequence.replace(r'\(', '$').replace(r'\)', '$').replace(r'\[', '$$').replace(r'\]', '$$')with open(f"{os.getcwd()}/output.md","w+") as f:f.write(content)f.close()return content, f"{os.getcwd()}/output.md"css = """#mkd {height: 500px; overflow: auto; border: 1px solid #ccc; }
"""with gr.Blocks(css=css) as demo:gr.HTML("<h1><center>Nougat模型推理PDF转Markdown 🍫<center><h1>")with gr.Row():mkd = gr.Markdown('<h4><center>上传PDF</center></h4>')mkd = gr.Markdown('<h4><center>提供PDF链接</center></h4>')with gr.Row(equal_height=True):pdf_file = gr.File(label='PDF 📑', file_count='single')pdf_link = gr.Textbox(placeholder='在此处输入arxiv链接', label='Link to Paper🔗')with gr.Row():btn = gr.Button('运行 🍫')with gr.Row():clr = gr.Button('清除输入和输出 🧼')output_headline = gr.Markdown("## Markdown展示👇")with gr.Row():parsed_output = gr.Markdown(elem_id='mkd', value='输出文本 📝')output_file = gr.File(file_types = ["txt"], label="输出文件 📑")btn.click(inference, [pdf_file, pdf_link], [parsed_output, output_file])clr.click(lambda : (gr.update(value=None), gr.update(value=None),gr.update(value=None), gr.update(value=None)), [], [pdf_file, pdf_link, parsed_output, output_file])gr.Examples([["/your/pdf_data/path/xxx.pdf", ""], [None, "https://arxiv.org/pdf/2308.08316.pdf"]],inputs = [pdf_file, pdf_link],outputs = [parsed_output, output_file],fn=inference,cache_examples=True,label='点击下面的任何示例,快速获取 Nougat OCR 🍫结果:')demo.queue()
demo.launch(debug=True,share=True, server_name="192.168.10.60", server_port=7899)

测试结果

正常的arxiv上的论文识别效果很好,但是这个只限于英文
对于特殊pdf的识别效果很差,nougat自己的rasterize_paper函数没有pdf2image好
另外文档的排版也会干扰识别结果

这篇关于【nougat推理】pdf转markdown文件代码demo示例web_demo示例的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/935360

相关文章

PostgreSQL中rank()窗口函数实用指南与示例

《PostgreSQL中rank()窗口函数实用指南与示例》在数据分析和数据库管理中,经常需要对数据进行排名操作,PostgreSQL提供了强大的窗口函数rank(),可以方便地对结果集中的行进行排名... 目录一、rank()函数简介二、基础示例:部门内员工薪资排名示例数据排名查询三、高级应用示例1. 每

使用Python删除Excel中的行列和单元格示例详解

《使用Python删除Excel中的行列和单元格示例详解》在处理Excel数据时,删除不需要的行、列或单元格是一项常见且必要的操作,本文将使用Python脚本实现对Excel表格的高效自动化处理,感兴... 目录开发环境准备使用 python 删除 Excphpel 表格中的行删除特定行删除空白行删除含指定

SpringBoot线程池配置使用示例详解

《SpringBoot线程池配置使用示例详解》SpringBoot集成@Async注解,支持线程池参数配置(核心数、队列容量、拒绝策略等)及生命周期管理,结合监控与任务装饰器,提升异步处理效率与系统... 目录一、核心特性二、添加依赖三、参数详解四、配置线程池五、应用实践代码说明拒绝策略(Rejected

SQL中如何添加数据(常见方法及示例)

《SQL中如何添加数据(常见方法及示例)》SQL全称为StructuredQueryLanguage,是一种用于管理关系数据库的标准编程语言,下面给大家介绍SQL中如何添加数据,感兴趣的朋友一起看看吧... 目录在mysql中,有多种方法可以添加数据。以下是一些常见的方法及其示例。1. 使用INSERT I

SpringBoot中SM2公钥加密、私钥解密的实现示例详解

《SpringBoot中SM2公钥加密、私钥解密的实现示例详解》本文介绍了如何在SpringBoot项目中实现SM2公钥加密和私钥解密的功能,通过使用Hutool库和BouncyCastle依赖,简化... 目录一、前言1、加密信息(示例)2、加密结果(示例)二、实现代码1、yml文件配置2、创建SM2工具

MySQL 定时新增分区的实现示例

《MySQL定时新增分区的实现示例》本文主要介绍了通过存储过程和定时任务实现MySQL分区的自动创建,解决大数据量下手动维护的繁琐问题,具有一定的参考价值,感兴趣的可以了解一下... mysql创建好分区之后,有时候会需要自动创建分区。比如,一些表数据量非常大,有些数据是热点数据,按照日期分区MululbU

Python函数作用域示例详解

《Python函数作用域示例详解》本文介绍了Python中的LEGB作用域规则,详细解析了变量查找的四个层级,通过具体代码示例,展示了各层级的变量访问规则和特性,对python函数作用域相关知识感兴趣... 目录一、LEGB 规则二、作用域实例2.1 局部作用域(Local)2.2 闭包作用域(Enclos

C++20管道运算符的实现示例

《C++20管道运算符的实现示例》本文简要介绍C++20管道运算符的使用与实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录标准库的管道运算符使用自己实现类似的管道运算符我们不打算介绍太多,因为它实际属于c++20最为重要的

Java中调用数据库存储过程的示例代码

《Java中调用数据库存储过程的示例代码》本文介绍Java通过JDBC调用数据库存储过程的方法,涵盖参数类型、执行步骤及数据库差异,需注意异常处理与资源管理,以优化性能并实现复杂业务逻辑,感兴趣的朋友... 目录一、存储过程概述二、Java调用存储过程的基本javascript步骤三、Java调用存储过程示

Visual Studio 2022 编译C++20代码的图文步骤

《VisualStudio2022编译C++20代码的图文步骤》在VisualStudio中启用C++20import功能,需设置语言标准为ISOC++20,开启扫描源查找模块依赖及实验性标... 默认创建Visual Studio桌面控制台项目代码包含C++20的import方法。右键项目的属性: