Jump to content
PayMap

利用人工智能技术实现文档自动翻译和保存 Implementing Document Translation and Storage Using Artificial Intelligence

Rate this topic

Create short link


Recommended Posts

  • Administrators

背景与相关技术 Background and Related Technologies

 

    • 简要介绍 OpenAI 和 Llama-Parse。 Briefly introduce OpenAI and Llama-Parse.
    • 解释如何利用 Google Colab 和 Google Drive 实现文件的读取和保存。 Explain how to use Google Colab and Google Drive to read and save files.
  • 项目设置与环境配置 Project Setup and Environment Configuration

    • 详细描述如何在 Google Colab 上设置项目。 Detail how to set up a project on Google Colab.
    • 安装所需的 Python 库。 Install the necessary Python libraries.
    • 挂载 Google Drive 并配置 API 密钥。 Mount Google Drive and configure API keys.
  • PDF 文件加载与解析 PDF File Loading and Parsing

    • 使用 Llama-Parse 加载和解析 PDF 文件。 Use Llama-Parse to load and parse PDF files.
    • 将解析结果转换为 Markdown 文本。 Convert the parsed results into Markdown text.
  • 文本翻译 Text Translation

    • 使用 OpenAI 的 ChatGPT 模型进行文本翻译。 Use OpenAI's ChatGPT model for text translation.
    • 详细说明如何编写翻译函数。 Explain in detail how to write the translation function.
  • 保存翻译结果 Saving Translation Results

    • 将翻译后的文本保存为PDF 文件。 Save the translated text as a PDF file.
    • 介绍使用 python-docxfpdf 库来实现这一功能。 Introduce how to use the python-docx and fpdf libraries to achieve this functionality.
  • 项目优化与用户体验提升 Project Optimization and User Experience Improvement

    • 使用 Google Colab 表单简化用户输入。 Simplify user input using Google Colab forms.
    • 提供代码优化建议和注意事项。 Provide code optimization suggestions and considerations.
  • 结论 Conclusion

    • 总结项目实现的过程和效果。 Summarize the implementation process and effects of the project.
    • 展望未来可能的改进和扩展方向。 Look forward to possible improvements and expansion directions in the future.

 

 视频中所使用的代码示例(亲测好用!):https://colab.research.google.com/github/ywchiu/largitdata/blob/master/code/Course_242.ipynb

 

在 Google Colab 上设置一个新项目并进行文件翻译的步骤如下:

第一步:创建一个新的 Colab 笔记本

  1. 打开 Google Colab.
  2. 点击左上角的 File 菜单,选择 New notebook

 

为了在 Google Colab 上提供一个更友好的界面,可以使用表单来让用户输入必要的参数。以下是经过优化的代码示例,包括所有必要的手工调整部分以及表单输入。

第一步:安装必要的库

!pip install llama-index llama-index-core llama-index-embeddings-openai llama-parse openai python-docx fpdf google-auth google-auth-oauthlib google-auth-httplib2 google-api-python-client

第二步:存取 Google Drive

import os
from google.colab import drive

# 设置路径
THESIS_LOC = '/content/drive/MyDrive/PDFtranslate/'  # @param {type:"string"}
drive.mount('/content/drive')
os.chdir(THESIS_LOC)
os.listdir()
 

第三步:设置 Llama-Parse 和 OpenAI API 密钥

import nest_asyncio
nest_asyncio.apply()

LLAMA_PARSER_KEY = 'your-llama-parse-key'  # @param {type:"string"}
OPENAI_KEY = 'your-openai-key'  # @param {type:"string"}
os.environ["LLAMA_CLOUD_API_KEY"] = LLAMA_PARSER_KEY
os.environ["OPENAI_API_KEY"] = OPENAI_KEY
 

第四步:设置 Llama-Parse 用的 LLM 模型

from llama_index.llms.openai import OpenAI
from llama_index.core import Settings

LLM_MODEL = "gpt-3.5-turbo-0125"  # @param {type:"string"}
llm = OpenAI(model=LLM_MODEL)
Settings.llm = llm
 

第五步:加载 PDF

from llama_parse import LlamaParse
from IPython.display import display, Markdown, Latex

PDF_FILE = "Case-23_cr_00118_Transcript-31-05-2024.pdf"  # @param {type:"string"}
parser = LlamaParse(result_type="markdown")

md_documents = parser.load_data(
    file_path=PDF_FILE
)

print(md_documents[0].text)
 

第六步:使用 GPT 解析 Markdown 文件

from llama_index.core.node_parser import MarkdownElementNodeParser

node_parser = MarkdownElementNodeParser(
    llm=OpenAI(model=LLM_MODEL), num_workers=8
)
nodes = node_parser.get_nodes_from_documents(md_documents)
base_nodes, objects = node_parser.get_nodes_and_objects(nodes)
display(Markdown('\n\n'.join([t.text for t in nodes])))
 

第七步:使用 ChatGPT 翻译

import openai

openai.api_key = os.getenv('OPENAI_API_KEY')

TRANSLATE_MODEL = "gpt-3.5-turbo-0125"
SYSTEM_PROMPT = '请你成为文章翻译的小帮手,请协助翻译以下法庭文件,以简体中文输出'

def translate_text(text):
    completion = openai.ChatCompletion.create(
        model=TRANSLATE_MODEL,
        messages=[
            {"role": "system", "content": SYSTEM_PROMPT},
            {"role": "user", "content": text},
        ]
    )
    return completion.choices[0].message['content']

translated_text = []
for node in nodes:
    translated_text.append({
        'original': node.text,
        'translated': translate_text(node.text)
    })

# 显示翻译结果
display(Markdown('\n\n'.join([f"**Original:**\n{t['original']}\n\n**Translated:**\n{t['translated']}" for t in translated_text])))
 

第八步:保存翻译结果为中英文对照的 Word 和 PDF 文件

import os
from docx import Document
from fpdf import FPDF

DONE_LOC = os.path.join(THESIS_LOC, 'done')

if not os.path.exists(DONE_LOC):
    os.makedirs(DONE_LOC)

# 保存为中英文对照的 Word 文件
doc = Document()
for t in translated_text:
    doc.add_paragraph("Original:\n" + t['original'])
    doc.add_paragraph("\nTranslated:\n" + t['translated'])
    doc.add_paragraph("\n" + "-"*40 + "\n")
doc_path = os.path.join(THESIS_LOC, PDF_FILE.replace('.pdf', '_translated.docx'))
doc.save(doc_path)

# 保存为中英文对照的 PDF 文件
class PDF(FPDF):
    def header(self):
        self.set_font('Arial', 'B', 12)
        self.cell(0, 10, 'Translated Document', 0, 1, 'C')

    def footer(self):
        self.set_y(-15)
        self.set_font('Arial', 'I', 8)
        self.cell(0, 10, f'Page {self.page_no()}', 0, 0, 'C')

pdf = PDF()
pdf.add_page()
pdf.set_auto_page_break(auto=True, margin=15)
pdf.set_font('Arial', '', 12)

for t in translated_text:
    pdf.multi_cell(0, 10, "Original:\n" + t['original'])
    pdf.multi_cell(0, 10, "\nTranslated:\n" + t['translated'])
    pdf.multi_cell(0, 10, "\n" + "-"*40 + "\n")

pdf_path = os.path.join(THESIS_LOC, PDF_FILE.replace('.pdf', '_translated.pdf'))
pdf.output(pdf_path)

# 移动原始 PDF 文件到 done 目录
os.rename(os.path.join(THESIS_LOC, PDF_FILE), os.path.join(DONE_LOC, PDF_FILE))

# 列出存储目录的文件
os.listdir(THESIS_LOC)
 
 
注:请确保替换所有占位符(如 API 密钥和文件路径)为实际值。
 
 

结论

根据实际测试,原作者在视频中展示的方法效果较好。尝试改进为中英文对照翻译效果较差(上述代码可能会报错,因为有太多调试的内容,并不是最终调试完毕的版本)。

示例

以下为法庭531号文件自动翻译的参考文件。需要注意的是,调用 OpenAI API 进行翻译是需要付费的。

参考信息

使用 OpenAI 模型(LLM_MODEL: gpt-3.5-turbo-0125)自动翻译 PDF 并保存为 PDF 文件的示例:

  • 文件页数: 236页
  • 费用: 约1.6美元
  • 实际运行耗时: 约20分钟
  • 完成任务: 自动翻译和保存为新文件

通过优化和调试后的程序,可以高效地完成文件的自动翻译任务。

 
Link to comment
Share on other sites

  • Administrators

 

2024年6月4号 郭先生庭审英文文字笔录:
https://nfsc.press/wp-content/uploads/2024/06/Case-23_cr_00118_Transcript-04-06-2024.pdf

 

 

 

 

注:仅需自备API :LLAMA_PARSER_KEY (免费)、OPENAI_KEY(需预付费充值)

image.png

翻译中文后生成的 *.md 文件 :

Case-23_cr_00118_Transcript-04-06-2024.pdf.md

 

 

使用本地工具

  1. Typora

    • 下载并安装 Typora
    • 打开 Typora 并加载你的 .md 文件。
    • 选择 “File” 菜单,然后选择 “Export” -> “PDF”。

image.png

最终翻译后的成品PDF、Html 文件效果如下:

Case-23_cr_00118_Transcript-04-06-2024.pdfCase-23_cr_00118_Transcript-04-06-2024.html

 

为了供相关翻译团队评估AI翻译的中文效果,以下文件是由GPT-3.5模型生成的中文翻译。如果使用更高级的GPT-4模型,生成的翻译文件结果可能会更精准,翻译质量和语言流畅度也会更高。请参考以下内容进行评估:


文件名称:Case-23_cr_00118_Transcript-04-06-2024.pdf.md

文件内容:

这份文件展示了GPT-3.5模型的翻译效果,目的是供相关翻译团队评估AI翻译的准确性和流畅度。考虑到GPT-4模型在语言理解和生成方面的增强,使用GPT-4模型进行翻译可能会显著提高翻译的精确度和自然度。

OpenAI api 花费 :0.47美元(GPT-3.5模型的价格很便宜!价格表:https://openai.com/api/pricing/ )


请根据上述内容进行评估,并考虑在将来的翻译工作中使用GPT-4模型,以获得更高质量的翻译结果。

Link to comment
Share on other sites

  • Administrators

2024年6月5号 郭先生庭审英文文字笔录原文(英文)

https://nfsc.press/wp-content/uploads/2024/06/Case-23_cr_00118_Transcript-05-06-2024.pdf.pdf

2024年6月5号 郭先生庭审英文文字笔录(中文)AI翻译中文后PDF、Html文件链接:https://paymap.org/1a

 

参考信息

使用 OpenAI 模型(LLM_MODEL: gpt-3.5-turbo-0125)自动翻译 PDF 并保存为 PDF 文件的示例:

  • 文件页数: 142页
  • 费用: 约0.1美元
  • 实际运行耗时: 约15分钟
  • 完成任务: 自动翻译和保存为新文件

 

AI翻译中文后生成的 *.md 文件 (供技术人员参考):

Case-23_cr_00118_Transcript-05-06-2024.pdf.md

 

最终翻译后的成品PDF、Html 文件效果如下:

Case-23_cr_00118_Transcript-05-06-2024.pdf

Case-23_cr_00118_Transcript-05-06-2024.html

 

得益于翻译成本和技术的稳定性表现,PayMap将在以下的AI博客专栏持续更新法庭文件。

由于每天发布的法庭文档篇幅较长,如果您没有足够时间浏览细节,可以考虑使用 ChatGPT 来帮助总结概要。然而,PayMap依然建议您花一些时间浏览整个文档的细节。

 

NFSC官网的中文翻译网址: https://nfsc.press/2023/04/22/court-case-documents/

 

 

Link to comment
Share on other sites

  • Roger changed the title to 利用人工智能技术实现文档自动翻译和保存 Implementing Document Translation and Storage Using Artificial Intelligence
  • Administrators

2024年6月6日郭先生庭审的全文中文翻译

 

AI翻译后源文件:Case-23_cr_00118_Transcript-06-06-2024.pdf.md  

Case-23_cr_00118_Transcript-06-06-2024.pdf.md

AI翻译后Html文件:Case-23_cr_00118_Transcript-06-06-2024.html

Case-23_cr_00118_Transcript-06-06-2024.html

AI翻译后PDF文件:CN_Case-23_cr_00118_Transcript-06-06-2024.pdf

CN_Case-23_cr_00118_Transcript-06-06-2024.pdf

 

Link to comment
Share on other sites

  • Administrators

2024年6月7日郭先生庭审的全文中文翻译

 

AI翻译后源文件:Case-23_cr_00118_Transcript-07-06-2024.pdf.md  

AI翻译后Html文件:Case-23_cr_00118_Transcript-07-06-2024.html

AI翻译后PDF文件:Case-23_cr_00118_Transcript-07-06-2024.pdf

 

下载地址: https://drive.google.com/drive/folders/1C_ZvbtzOJ88CxsexfwB5bSyOYElVHe6r?usp=sharing

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

Registration Terms & Conditions