【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

相关文章

Django开发时如何避免频繁发送短信验证码(python图文代码)

《Django开发时如何避免频繁发送短信验证码(python图文代码)》Django开发时,为防止频繁发送验证码,后端需用Redis限制请求频率,结合管道技术提升效率,通过生产者消费者模式解耦业务逻辑... 目录避免频繁发送 验证码1. www.chinasem.cn避免频繁发送 验证码逻辑分析2. 避免频繁

精选20个好玩又实用的的Python实战项目(有图文代码)

《精选20个好玩又实用的的Python实战项目(有图文代码)》文章介绍了20个实用Python项目,涵盖游戏开发、工具应用、图像处理、机器学习等,使用Tkinter、PIL、OpenCV、Kivy等库... 目录① 猜字游戏② 闹钟③ 骰子模拟器④ 二维码⑤ 语言检测⑥ 加密和解密⑦ URL缩短⑧ 音乐播放

Python使用Tenacity一行代码实现自动重试详解

《Python使用Tenacity一行代码实现自动重试详解》tenacity是一个专为Python设计的通用重试库,它的核心理念就是用简单、清晰的方式,为任何可能失败的操作添加重试能力,下面我们就来看... 目录一切始于一个简单的 API 调用Tenacity 入门:一行代码实现优雅重试精细控制:让重试按我

MySQL常用字符串函数示例和场景介绍

《MySQL常用字符串函数示例和场景介绍》MySQL提供了丰富的字符串函数帮助我们高效地对字符串进行处理、转换和分析,本文我将全面且深入地介绍MySQL常用的字符串函数,并结合具体示例和场景,帮你熟练... 目录一、字符串函数概述1.1 字符串函数的作用1.2 字符串函数分类二、字符串长度与统计函数2.1

java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)

《java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)》:本文主要介绍java中pdf模版填充表单踩坑的相关资料,OpenPDF、iText、PDFBox是三... 目录准备Pdf模版方法1:itextpdf7填充表单(1)加入依赖(2)代码(3)遇到的问题方法2:pd

Python操作PDF文档的主流库使用指南

《Python操作PDF文档的主流库使用指南》PDF因其跨平台、格式固定的特性成为文档交换的标准,然而,由于其复杂的内部结构,程序化操作PDF一直是个挑战,本文主要为大家整理了Python操作PD... 目录一、 基础操作1.PyPDF2 (及其继任者 pypdf)2.PyMuPDF / fitz3.Fre

SQL Server 中的 WITH (NOLOCK) 示例详解

《SQLServer中的WITH(NOLOCK)示例详解》SQLServer中的WITH(NOLOCK)是一种表提示,等同于READUNCOMMITTED隔离级别,允许查询在不获取共享锁的情... 目录SQL Server 中的 WITH (NOLOCK) 详解一、WITH (NOLOCK) 的本质二、工作

MySQL CTE (Common Table Expressions)示例全解析

《MySQLCTE(CommonTableExpressions)示例全解析》MySQL8.0引入CTE,支持递归查询,可创建临时命名结果集,提升复杂查询的可读性与维护性,适用于层次结构数据处... 目录基本语法CTE 主要特点非递归 CTE简单 CTE 示例多 CTE 示例递归 CTE基本递归 CTE 结

Spring AI使用tool Calling和MCP的示例详解

《SpringAI使用toolCalling和MCP的示例详解》SpringAI1.0.0.M6引入ToolCalling与MCP协议,提升AI与工具交互的扩展性与标准化,支持信息检索、行动执行等... 目录深入探索 Spring AI聊天接口示例Function CallingMCPSTDIOSSE结束语

go动态限制并发数量的实现示例

《go动态限制并发数量的实现示例》本文主要介绍了Go并发控制方法,通过带缓冲通道和第三方库实现并发数量限制,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面... 目录带有缓冲大小的通道使用第三方库其他控制并发的方法因为go从语言层面支持并发,所以面试百分百会问到