在 GenAI 的世界里,文件格式太 20 世纪了!

文章介绍了如何使用Llama 3在本地环境中解析和索引PDF及DOCX文件,利用Ollama运行Llama模型,提取文档中的关键信息,如邮编、IP地址、邮箱等,展示了GenAI在处理传统文件格式方面的潜力。

在 GenAI 的世界里,文件格式是上个世纪的东西!

我们正在进入一个将消除我们过去使用的所有愚蠢的文件文档的世界。为什么我们需要 PDF、DOCX、XLSX 等等?在 GenAI 的世界里,这些文档可以很容易地被解析和索引,然后我们可以构建任何我们想要的文档。

在 LastingAsset,我们正在研究具有隐私意识的欺诈分析,公司可以在不违反隐私的情况下在彼此之间共享数据。现在,通常可以选择是从文档中提取数据时,使用像 ChatGPT 这样的闭源模型,还是像 Llama 3 这样的开源模型。对于包含个人身份信息 (PII) 的应用程序,我们可能会通过将数据传递给闭源模型来侵犯用户隐私,因此开源模型允许你简单地将完整的模型下载到本地计算机,然后从那里运行查询。

在之前的一篇文章中,我概述了我们如何使用 LlamaCloud 来解析文档并对其进行索引:

**数字取证和欺诈分析变得更容易

在本文中,我将概述如何使用 Llama 来索引文档。

在本地运行

在这种情况下,我们将使用 Ollama 程序,它可以下载 Llama 模型并在本地运行它们。我们可以安装 ollama [ here] 然后运行:

% ollama
Available Commands:
  serve       Start ollama
  create      Create a model from a Modelfile
  show        Show information for a model
  run         Run a model
  stop        Stop a running model
  pull        Pull a model from a registry
  push        Push a model to a registry
  list        List models
  ps          List running models
  cp          Copy a model
  rm          Remove a model
  help        Help about any command
Flags:
  -h, --help      help for ollama
  -v, --version   Show version information

为了获取并运行一个模型:

% ollama pull llama3
% ollama run llama3
>>> What is elliptic curve cryptography
Elliptic curve cryptography (ECC) is a type of public-key encryption that
uses the mathematical properties of elliptic curves to create secure keys.
It is used to establish secure connections and protect sensitive data over
the internet.
>>>

如果我们需要更大的模型,我们可以使用 70b:

% ollama pull llama3:70b
% ollama run llama3:70b
⠋

我们现在可以列出我们的模型:

% ollama list
NAME             ID              SIZE      MODIFIED
llama3:70b       786f3184aec0    39 GB     2 hours ago
llama3:latest    365c0bd3c000    4.7 GB    2 hours ago

对于标准模型,我们有 80 亿个参数:

% ollama show llama3:latest
  Model
    architecture        llama
    parameters          8.0B
    context length      8192
    embedding length    4096
    quantization        Q4_0
Capabilities
    completion
  Parameters
    num_keep    24
    stop        "<|start_header_id|>"
    stop        "<|end_header_id|>"
    stop        "<|eot_id|>"
  License
    META LLAMA 3 COMMUNITY LICENSE AGREEMENT
    Meta Llama 3 Version Release Date: April 18, 2024

对于 70b,我们有 706 亿个参数:

% ollama show llama3:70b
  Model
    architecture        llama
    parameters          70.6B
    context length      8192
    embedding length    8192
    quantization        Q4_0
Capabilities
    completion
  Parameters
    num_keep    24
    stop        "<|start_header_id|>"
    stop        "<|end_header_id|>"
    stop        "<|eot_id|>"
  License
    META LLAMA 3 COMMUNITY LICENSE AGREEMENT
    Meta Llama 3 Version Release Date: April 18, 2024

解析 PDF

该文档位于 PDF 文档中,内容为:

使用 llama 读取 PDF 并解析它的 Python 代码是:

import sys
import time
import subprocess

def query_llama(prompt):
    print("Llama now processing.") # Llama 现在正在处理。
    start_time = time.time()
    try:
        result = subprocess.run(["ollama", "run", "llama3"], input=prompt,text=True,capture_output=True,check=True)
        return result.stdout
    except subprocess.CalledProcessError as e:
        print("llama problem:", e.stderr) # llama 问题:
        return None

def get_text(pdf_name):
 from pypdf import PdfReader
 reader = PdfReader(pdf_name)
 page = reader.pages[0]
 text = page.extract_text()
 return(text)

if (len(sys.argv)>1):
 fname=str(sys.argv[1])
 text=get_text(fname)
 res=query_llama("For the text of '"+text+"'. Find the UK postcodes, IP addresses, email addresses, bank details, telephone numbers, credit card details, MAC addresss, cities and passwords.")
 print(res)

结果是:

**UK Postcodes:**
* SW1 7AF
* EH105DT
* EH14 1DJ
**IP Addresses:**
* 10.0.0.1
* 192.168.0.1
* 192.168.1.1
**Email Addresses:**
* Fred.smith@home.net
* Fred.blogs@gmail.com
* f.blogs@mail.com
**Bank Details (IBAN, Sort Code, Account Number):**
* GB91BKEN10000041610008
        + IBAN: GB91BKEN10000041610008
        + Sort Code: 100000
        + Account Number: 41610008
* GB27BOFI90212729823529
        + IBAN: GB27BOFI90212729823529
        + Sort Code: 902127
        + Account Number: 29823529
* GB17BOFS80055100813796
        + IBAN: GB17BOFS80055100813796
        + Sort Code: 800551
        + Account Number: 00813796
* GB92BARC20005275849855
        + IBAN: GB92BARC20005275849855
        + Sort Code: 200052
        + Account Number: 75849855
**Telephone Numbers:**
* +44 (960) 000 00 00
* 444.3212.5431
**Credit Card Details:**
* Card Number 1: 4321-4444-5412-2310
* Card Number 2: 5430-5411-4333-5123
* Name on the card: Fred Smith
**MAC Addresses:**
* 01:23:45:67:89:ab
* 00.11.22.33.44.55
**Cities:**
* Glasgow
* Edinburgh
* Stirling
**Passwords:**
* a1b2c3
* Qwerty123
* inkwell!!

我们可以很容易地修改为带有发票的 DOCX 文件:

import sys
import time
import subprocess
from docx_parser import DocumentParser
from pypdf import PdfReader

def get_llama(prompt):
    print("Llama now processing.") # Llama 现在正在处理。
    start_time = time.time()
    try:
        result = subprocess.run(["ollama", "run", "llama3"], input=prompt,text=True,capture_output=True,check=True)
        return result.stdout
    except subprocess.CalledProcessError as e:
        print("llama problem:", e.stderr) # llama 问题:
        return None

def get_pdf(pdf_name):

 reader = PdfReader(pdf_name)

 page = reader.pages[0]

 text = page.extract_text()
 return(text)

def get_docx(docx_name):

 doc = DocumentParser(docx_name)
 text=""
 for _type, item in doc.parse():
  text=text+"\n"+text
 return(text)

if (len(sys.argv)>1):
 fname=str(sys.argv[1])
 text=""
 if (fname.endswith(".pdf")):
  text=get_text(fname)
 elif (fname.endswith(".docx")):
  text=get_docx(fname)

 res=get_llama("For the text of '"+text+"'. Find the UK postcodes, IP addresses, email addresses, bank details, telephone numbers, credit card details, MAC addresss, cities and passwords.")

 print(res)

在本例中,DOCX 具有以下形式:

当我们运行 Python 程序时,我们得到:

1. Billing Period: # 账单周期:
The billing period is not explicitly mentioned in the provided data. However, based on the "From" and "To" dates, it can be inferred that the billing period is from May 1, 2025, to July 7, 2025. # 提供的**数据**没有明确提到账单周期。然而,根据“从”和“到”的日期,可以推断出账单周期是从 2025 年 5 月 1 日到 2025 年 7 月 7 日。

2. Customer Details: # 客户详细信息:
The customer details are as follows: # 客户详细信息如下:

* Name: Robert Apple # 姓名:Robert Apple
* Company: Robot Shop # 公司:Robot Shop
* Address: 10 Colinton Road, Edinburgh # 地址:爱丁堡 Colinton Road 10 号

3. Payment Due Date: # 付款截止日期:
The payment due date is July 7, 2025. # 付款截止日期是 2025 年 7 月 7 日。

4. Total Payment Due: # 应付总额:
The total payment due is £580.00 (total price quote). # 应付总额为 £580.00 (总价报价)。

5. Names of Products Sold: # 销售的产品名称:
The products sold are: # 销售的产品是:

* Robot Waiter (50 units) with a unit price of £10.00 and a total price of £500.00 # 机器人服务员 (50 件),单价为 £10.00,总价为 £500.00

6. VAT Charged: # 收取的增值税:
The VAT charged is 20% of the subtotal, which is £30.00. # 收取的增值税是小计的 20%,即 £30.00。

Note that there might be additional products or services not explicitly mentioned in this invoice data. # 请注意,此发票**数据**中可能未明确提及其他产品或服务。

结论

所以与你最喜欢的文件格式说再见,并迎接一个 GenAI 的索引和解析世界。Llama 是一个很棒的工具,可以支持索引各种文档,并且也是一个开源模型。

  • 原文链接: medium.com/asecuritysite...
  • 登链社区 AI 助手,为大家转译优秀英文文章,如有翻译不通的地方,还请包涵~
点赞 0
收藏 0
分享
本文参与登链社区写作激励计划 ,好文好收益,欢迎正在阅读的你也加入。

0 条评论

请先 登录 后评论
asecuritysite
asecuritysite
江湖只有他的大名,没有他的介绍。