首页 > 其他分享 >【ERNIE + PaddleOCR】 创建自己的论文字典,更好的写论文吧!

【ERNIE + PaddleOCR】 创建自己的论文字典,更好的写论文吧!

时间:2024-05-26 12:01:57浏览次数:21  
标签:ERNIE PaddleOCR 论文 dict result text import 字典

一、项目背景

        在撰写论文的过程中,许多作者习惯先以中文完成初稿,随后再将其翻译为英文。然而,这种翻译过程往往伴随着一系列挑战。尤其是在词汇选择和语法结构上,很容易使用到一些在学术论文中不常用或不符合规范的表达。为了克服这一难题,我结合PaddleOCR和ERNIE技术来构建一个模板论文的字典来解决这个问题。

二、项目方案

        首先,利用PaddleOCR技术,我能够从大量的学术论文中提取出关键的词汇和短语,这些词汇和短语往往代表着学术领域内的专业表达。随后,通过ERNIE的API,将这个字典告诉大模型,来提高翻译的准确性和规范性。

        在拥有了这样一个字典后,我能够确保在翻译过程中使用到的是那些符合学术规范的词汇,而单词形态与语法结构有关,所以也规范了语法结构。这不仅大大提高了翻译的准确性,还有效降低了因词汇和语法问题而导致的论文质量下降的风险。

        总的来说,通过结合PaddleOCR和ERNIE技术来构建论文翻译字典,我成功地解决了翻译过程中的词汇和语法问题,为我的论文写作提供了有力的支持。这种方法不仅提高了我的翻译效率,还使我的论文更加符合学术规范,为我在学术领域内的进一步研究奠定了坚实的基础。

三、数据说明

        准备好自己的参考论文的pdf文件即可。

四、代码实现

4.1 环境安装

        安装所需环境,需要安装PaddleOCR,最好从源代码进行安装,目前该项目更新较快,使用新版本更不容易出现错误。源代码安装首先根据requirements.txt安装所需环境以及一些必要的包(使用中报错提示需要安装一些额外的包)

%cd ~

# 首先建议你先从github上下载PaddleOCR的源码,https://github.com/PaddlePaddle/PaddleOCR.git,我这里会先上传一份。
# 先不要使用左侧套件里的PaddleOCR,它的版本使用起来有各种小问题。
# 我这里先下载好了源代码并上传解压。
!unzip PaddleOCR-main.zip

# 安装源码所依赖环境
%cd ~/PaddleOCR-main
!pip install --user -r requirements.txt
!pip install --user paddleclas PyMuPDF==1.19.0

# 这里是因为它下载很慢,所以我就本地下载下来上传安装的,在线安装包有可能因为网络问题失败,多试几次或者下载下来离线安装
# !pip install /home/aistudio/work/opencv_python_headless-4.9.0.80-cp37-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl

# 运行setup安装
# ******  注意,如果遇见安装超时或者其他原因导致安装环境失败,多半是网络问题,请多尝试几次。 ******
!python setup.py build install

4.2 PaddleOCR版面分析和文本识别

        有两种方法可以使用版面分析和文本识别,一种是命令行运行,一种是python代码运行。

# 我的pdf文件在work文件夹里面
%cd ~/work

# 通过命令行进行版面分析和文本识别,不需要重现文档
!paddleocr --image_dir=molecular.pdf --type=structure --recovery=false --lang='en'

        这里我本来先使用的python代码实现,而没有使用命令行。结果发现目前代码有问题,无法通过官方案例解析pdf文件,代码会报错。下面我给了一个案例可以使用,此案例也合并到了官方代码中。

%cd ~/work

import os
import cv2
import numpy as np
from paddleocr import PPStructure,save_structure_res
from paddle.utils import try_import
from PIL import Image

ocr_engine = PPStructure(table=False, ocr=True, show_log=True)

save_folder = './output'
img_path = 'molecular.pdf'

fitz = try_import("fitz")
imgs = []
with fitz.open(img_path) as pdf:
    for pg in range(0, pdf.page_count):
        page = pdf[pg]
        mat = fitz.Matrix(2, 2)
        pm = page.get_pixmap(matrix=mat, alpha=False)

        # if width or height > 2000 pixels, don't enlarge the image
        if pm.width > 2000 or pm.height > 2000:
            pm = page.get_pixmap(matrix=fitz.Matrix(1, 1), alpha=False)

        img = Image.frombytes("RGB", [pm.width, pm.height], pm.samples)
        img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
        imgs.append(img)

for index, img in enumerate(imgs):
    result = ocr_engine(img)
    save_structure_res(result, save_folder, os.path.basename(img_path).split('.')[0], index)
    for line in result:
        line.pop('img')
        print(line)

        我看了源码,发现代码会报错的原因在于,它没有对pdf文件做判断,且判断逻辑有问题,目前只适用于单page的图片或者gif。于是我改了相关代码,并提交了pull requests,修复了直接使用报错的BUG。

4.3 字典生成

        根据版面分析的结果,统计字典,以下代码为生成字典文件的代码。

# 读取output里对应的文本结果

%cd ~
import os
import re
import dill
  
# 假设所有txt文件都位于这个目录下  
directory = 'work/output/molecular'  
  
# 获取目录下的所有txt文件  
txt_files = [f for f in os.listdir(directory) if f.endswith('.txt')]  
txt_files.sort(key=lambda x: int(re.search(r'res_(\d+)\.txt', x).group(1)))
print(txt_files)
result = {}
result_text = []
# 遍历每个txt文件  
for filename in txt_files:  
    file_path = os.path.join(directory, filename)
    line_list = []
    with open(file_path, 'r', encoding='utf-8') as file:  
        # 逐行读取文件内容
        for line in file:  
            # 尝试将字符串转换为字典  
            try:  
                data_dict = eval(line)  
                # 在这里处理你的字典数据
                line_list.append(data_dict)
                if data_dict['type'] == 'text' and isinstance(data_dict['res'], list):
                    for res in data_dict['res']:
                        result_text.append(res['text'])
            except Exception as e:  
                # 如果转换失败,打印错误信息  
                print(f"Error evaluating line in {filename}: {e}")
    result[filename] = line_list

# 保存数据文件
dill.dump(result, open('result.pkl', 'wb'))
dill.dump(result_text, open('result_text.pkl', 'wb'))

        接下来是分词,本来想用PaddleNLP进行分词,但是我没有从官方文档里找到英文分词场景的介绍,都介绍的中文分词,所以还是使用的spacy,之后在研究怎么用吧。

        如果觉得没关系,也可以用paddleNLP本身的分词,之后会尝试一下。

%cd ~
!pip install spacy

# 建议提前下载模型包,在线下载太慢了
# !pip install work/en_core_web_trf-3.7.3-py3-none-any.whl

        最后生成works列表并排序过滤。

%cd ~
import dill
import re
import spacy  

# 加载spaCy的英文模型  
nlp = spacy.load('en_core_web_trf')  
  
def process_sentences(sentences):  
    # 合并短句并处理  
    processed_text = ' '.join(sentences)  
    doc = nlp(processed_text)  
    # 提取单词  
    words = [token.text for token in doc if not token.is_stop and token.is_alpha]  
    return words  
  
result_text = dill.load(open('result_text.pkl', 'rb'))
print(result_text)
# 提取并处理单词  
words = process_sentences(result_text)  
  
# 打印提取的单词  
print(words)
dill.dump(words, open('words.pkl', 'wb'))

        将字典数据降序排序,并进行过滤(出现次数大于5的保留)

# 生成字典
from collections import defaultdict, OrderedDict
import dill

words = dill.load(open('words.pkl', 'rb'))
count_dict = defaultdict(int)
for word in words:
    count_dict[word] += 1
# 倒序排序
sorted_dict = OrderedDict(sorted(count_dict.items(), key=lambda x: x[1], reverse=True))

# 过滤数据
filtered_words = [k+':'+str(v) for k, v in sorted_dict.items() if v > 5]
dict_str = ';'.join(filtered_words)

print(filtered_words)

4.4 ERNIE翻译

        之后使用ERNIE Bot进行语句的翻译,并给他准备好的词典。

# 安装ERNIE Bot
!pip install --upgrade erniebot

设计prompt在后续使用

# 设计prompt

prompt = (
    "你现在帮我翻译中文语句为英文,用于论文写作,不要减少或增加内容,文风要严谨。"
    "此外我会提供一个常用词典,请尽量使用词典里的单词进行翻译。"
    "词典的格式为:word1:110,word2:105,word3:100......"
    "冒号前是单词本身,冒号后是单词出现的频率。"
    # "现在我提供字典:"
)
prompt += dict_str
prompt += "现在我提供英文语句,你来翻译。英文语句为:"
print(prompt)

五、效果展示

        使用ernie-3.5来进行翻译,得到翻译的结果,可以看到不用字典和用字典有明显差别,不仅优化了单词还间接优化了语法。

import erniebot

models = erniebot.Model.list()
print(models)

# Set authentication params
erniebot.api_type = "aistudio"
erniebot.access_token = "你的token"

content = (
    "对于分子,它的 2D 和 3D 形式描述了相同的原子集合,但使用结构的不同特征。"
    "因此,关键挑战是在捕获不同公式中的结构知识并训练参数从两个信息中学习时具有表现力和兼容性。"
)

# Create a chat completion
response = erniebot.ChatCompletion.create(
    model="ernie-3.5",
    messages=[{"role": "user", "content": prompt+content}]
)

print(response.get_result())

# 不用字典
# For molecules, their 2D and 3D forms represent the same set of atoms but use different structural features. Therefore, the key challenge lies in capturing the structural knowledge from different formulas and training the parameters to learn from the two sources of information in an expressive and compatible manner.

# 使用字典
# For molecules, their 2D and 3D forms describe the same set of atoms, but use different characteristics of the structure. Therefore, the key challenge is to capture structural knowledge in different formulas and train parameters to be expressive and compatible when learning from both sources of information.

不用字典

        For molecules, their 2D and 3D forms represent the same set of atoms but use different structural features. Therefore, the key challenge lies in capturing the structural knowledge from different formulas and training the parameters to learn from the two sources of information in an expressive and compatible manner.

使用字典

        For molecules, their 2D and 3D forms describe the same set of atoms, but use different characteristics of the structure. Therefore, the key challenge is to capture structural knowledge in different formulas and train parameters to be expressive and compatible when learning from both sources of information.

        可以看到使用的单词和语法都有了变化,更符合论文的规范了。

六、总结提高

        在写代码过程中还发现了PaddleOCR存在的问题,虽然不知道能不能做出贡献,但还是挺开心的。分词目前还没有使用PaddleNLP,之后可以在研究研究。

标签:ERNIE,PaddleOCR,论文,dict,result,text,import,字典
From: https://blog.csdn.net/class4715/article/details/139207622

相关文章