时间:2022-09-22 14:39:07 | 浏览:2232
来源 | hackernoon
编译 | 武明利
责编 | Carol
出品 | AI科技大本营(ID:rgznai100)
在这篇文章中,我将向您展示如何使用Python构建自己的答案查找系统。基本上,这种自动化可以从图片中找到多项选择题的答案。
有一件事我们要清楚,在考试期间不可能在互联网上搜索问题,但是当考官转过身去的时候,我可以很快地拍一张照片。这是算法的第一部分。我得想办法把这个问题从图中提取出来。
似乎有很多服务可以提供文本提取工具,但是我需要某种API来解决此问题。最后,Google的VisionAPI正是我正在寻找的工具。很棒的事情是,每月前1000个API调用是免费的,这足以让我测试和使用该API。
Vision AI
首先,创建Google云帐户,然后在服务中搜索Vision AI。使用VisionAI,您可以执行诸如为图像分配标签来组织图像,获取推荐的裁切顶点,检测著名的风景或地方,提取文本等工作。
检查文档以启用和设置API。配置后,您必须创建JSON文件,包含您下载到计算机的密钥。
运行以下命令安装客户端库:
pip install google-cloud-vision
然后通过设置环境变量
GOOGLE_APPLICATION_CREDENTIALS,为应用程序代码提供身份验证凭据。
import os, io
from google.cloud import vision
from google.cloud.vision import types
# JSON file that contains your key
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "your_private_key.json"
# Instantiates a client
client = vision.ImageAnnotatorClient
FILE_NAME = "your_image_file.jpg"
# Loads the image into memory
with io.open(os.path.join(FILE_NAME), "rb") as image_file:
content = image_file.read
image = vision.types.Image(content=content)
# Performs text detection on the image file
response = client.text_detection(image=image)
print(response)
# Extract description
texts = response.text_annotations[0]
print(texts.description)
在运行代码时,您将看到JSON格式的响应,其中包括检测到的文本的规范。但我们只需要纯描述,所以我从响应中提取了这部分。
在Google上搜索问题
下一步是在Google上搜索问题部分来获得一些信息。我使用正则表达式(regex)库从描述(响应)中提取问题部分。然后我们必须将提取出的问题部分进行模糊化,以便能够对其进行搜索。
import re
import urllib
# If ending with question mark
if "?" in texts.description:
question = re.search("([^?]+)", texts.description).group(1)
# If ending with colon
elif ":" in texts.description:
question = re.search("([^:]+)", texts.description).group(1)
# If ending with newline
elif "
" in texts.description:
question = re.search("([^
]+)", texts.description).group(1)
# Slugify the match
slugify_keyword = urllib.parse.quote_plus(question)
print(slugify_keyword)
抓取的信息
我们将使用 BeautifulSoup 抓取前3个结果,以获得关于问题的一些信息,因为答案可能位于其中之一。
另外,如果您想从Google的搜索列表中抓取特定的数据,不要使用inspect元素来查找元素的属性,而是打印整个页面来查看属性,因为它与实际的属性有所不同。
我们需要对搜索结果中的前3个链接进行抓取,但是这些链接确实被弄乱了,因此获取用于抓取的干净链接很重要。
/url?q=https://en.wikipedia.org/wiki/IAU_definition_of_planet&sa=U&ved=2ahUKEwiSmtrEsaTnAhXtwsQBHduCCO4QFjAAegQIBBAB&usg=AOvVaw0HzMKrBxdHZj5u1Yq1t0en
正如您所看到的,实际的链接位于q=和&sa之间。通过使用正则表达式Regex,我们可以获得这个特定的字段或有效的URL。
result_urls =
def crawl_result_urls:
req = Request("https://google.com/search?q=" + slugify_keyword, headers={"User-Agent": "Mozilla/5.0"})
html = urlopen(req).read
bs = BeautifulSoup(html, "html.parser")
results = bs.find_all("div", class_="ZINbbc")
try:
for result in results:
link = result.find("a")["href"]
# Checking if it is url (in case)
if "url" in link:
result_urls.append(re.search("q=(.*)&sa", link).group(1))
except (AttributeError, IndexError) as e:
pass
在我们抓取这些URLs的内容之前,让我向您展示使用Python的问答系统。
问答系统
这是算法的主要部分。从前3个结果中抓取信息后,程序应该通过迭代文档来检测答案。首先,我认为最好使用相似度算法来检测与问题最相似的文档,但是我不知道如何实现它。
经过几个小时的研究,我在Medium上找到了一篇文章,用Python解释了问答系统。它有易于使用的python软件包能够对您自己的私有数据实现一个QA系统。
让我们先安装这个包:
pip install cdqa
我正在使用下面的示例代码块中包含的下载功能来手动下载经过预训练的模型和数据:
import pandas as pd
from ast import literal_eval
from cdqa.utils.filters import filter_paragraphs
from cdqa.utils.download import download_model, download_bnpp_data
from cdqa.pipeline.cdqa_sklearn import QAPipeline
# Download data and models
download_bnpp_data(dir="./data/bnpp_newsroom_v1.1/")
download_model(model="bert-squad_1.1", dir="./models")
# Loading data and filtering / preprocessing the documents
df = pd.read_csv("data/bnpp_newsroom_v1.1/bnpp_newsroom-v1.1.csv", converters={"paragraphs": literal_eval})
df = filter_paragraphs(df)
# Loading QAPipeline with CPU version of BERT Reader pretrained on SQuAD 1.1
cdqa_pipeline = QAPipeline(reader="models/bert_qa.joblib")
# Fitting the retriever to the list of documents in the dataframe
cdqa_pipeline.fit_retriever(df)
# Sending a question to the pipeline and getting prediction
query = "Since when does the Excellence Program of BNP Paribas exist?"
prediction = cdqa_pipeline.predict(query)
print("query: {}
".format(query))
print("answer: {}
".format(prediction[0]))
print("title: {}
".format(prediction[1]))
print("paragraph: {}
".format(prediction[2]))
它的输出应该是这样的:
它打印出确切的答案和包含答案的段落。
基本上,当从图片中提取问题并将其发送到系统时,检索器将从已抓取数据中选择最有可能包含答案的文档列表。如前所述,它计算问题与抓取数据中每个文档之间的余弦相似度。
在选择了最可能的文档后,系统将每个文档分成几个段落,并将问题一起发送给读者,这基本上是一个预先训练好的深度学习模型。所使用的模型是著名的NLP模型BERT的Pytorch 版本。
然后,读者输出在每个段落中找到的最可能的答案。在阅读者之后,系统中的最后一层通过使用内部评分函数对答案进行比较,并根据分数输出最有可能的答案,这将得到我们问题的答案。
下面是系统机制的模式。
你必须在特定的结构中设置数据帧(CSV),以便将其发送到 cdQA 管道。
但是实际上我使用PDF转换器从PDF文件目录创建了一个输入数据框。因此,我要在pdf文件中保存每个结果的所有抓取数据。我们希望总共有3个pdf文件(也可以是1个或2个)。另外,我们需要命名这些pdf文件,这就是为什么我抓取每个页面的标题的原因。
def get_result_details(url):
try:
req = Request(url, headers={"User-Agent": "Mozilla/5.0"})
html = urlopen(req).read
bs = BeautifulSoup(html, "html.parser")
try:
# Crawl any heading in result to name pdf file
title = bs.find(re.compile("^h[1-6]$")).get_text.strip.replace("?", "").lower
# Naming the pdf file
filename = "/home/coderasha/autoans/pdfs/" + title + ".pdf"
if not os.path.exists(os.path.dirname(filename)):
try:
os.makedirs(os.path.dirname(filename))
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
raise
with open(filename, "w") as f:
# Crawl first 5 paragraphs
for line in bs.find_all("p")[:5]:
f.write(line.text + "
")
except AttributeError:
pass
except urllib.error.HTTPError:
pass
def find_answer:
df = pdf_converter(directory_path="/home/coderasha/autoans/pdfs")
cdqa_pipeline = QAPipeline(reader="models/bert_qa.joblib")
cdqa_pipeline.fit_retriever(df)
query = question + "?"
prediction = cdqa_pipeline.predict(query)
print("query: {}
".format(query))
print("answer: {}
".format(prediction[0]))
print("title: {}
".format(prediction[1]))
print("paragraph: {}
".format(prediction[2]))
return prediction[0]
我总结一下算法:它将从图片中提取问题,在Google上搜索它,抓取前3个结果,从抓取的数据中创建3个pdf文件,最后使用问答系统找到答案。
如果你想看看它是如何工作的,请检查我做的一个可以从图片中解决考试问题的机器人。
以下是完整的代码:
import os, io
import errno
import urllib
import urllib.request
import hashlib
import re
import requests
from time import sleep
from google.cloud import vision
from google.cloud.vision import types
from urllib.request import urlopen, Request
from bs4 import BeautifulSoup
import pandas as pd
from ast import literal_eval
from cdqa.utils.filters import filter_paragraphs
from cdqa.utils.download import download_model, download_bnpp_data
from cdqa.pipeline.cdqa_sklearn import QAPipeline
from cdqa.utils.converters import pdf_converter
result_urls =
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "your_private_key.json"
client = vision.ImageAnnotatorClient
FILE_NAME = "your_image_file.jpg"
with io.open(os.path.join(FILE_NAME), "rb") as image_file:
content = image_file.read
image = vision.types.Image(content=content)
response = client.text_detection(image=image)
texts = response.text_annotations[0]
# print(texts.description)
if "?" in texts.description:
question = re.search("([^?]+)", texts.description).group(1)
elif ":" in texts.description:
question = re.search("([^:]+)", texts.description).group(1)
elif "
" in texts.description:
question = re.search("([^
]+)", texts.description).group(1)
slugify_keyword = urllib.parse.quote_plus(question)
# print(slugify_keyword)
def crawl_result_urls:
req = Request("https://google.com/search?q=" + slugify_keyword, headers={"User-Agent": "Mozilla/5.0"})
html = urlopen(req).read
bs = BeautifulSoup(html, "html.parser")
results = bs.find_all("div", class_="ZINbbc")
try:
for result in results:
link = result.find("a")["href"]
print(link)
if "url" in link:
result_urls.append(re.search("q=(.*)&sa", link).group(1))
except (AttributeError, IndexError) as e:
pass
def get_result_details(url):
try:
req = Request(url, headers={"User-Agent": "Mozilla/5.0"})
html = urlopen(req).read
bs = BeautifulSoup(html, "html.parser")
try:
title = bs.find(re.compile("^h[1-6]$")).get_text.strip.replace("?", "").lower
# Set your path to pdf directory
filename = "/path/to/pdf_folder/" + title + ".pdf"
if not os.path.exists(os.path.dirname(filename)):
try:
os.makedirs(os.path.dirname(filename))
except OSError as exc:
if exc.errno != errno.EEXIST:
raise
with open(filename, "w") as f:
for line in bs.find_all("p")[:5]:
f.write(line.text + "
")
except AttributeError:
pass
except urllib.error.HTTPError:
pass
def find_answer:
# Set your path to pdf directory
df = pdf_converter(directory_path="/path/to/pdf_folder/")
cdqa_pipeline = QAPipeline(reader="models/bert_qa.joblib")
cdqa_pipeline.fit_retriever(df)
query = question + "?"
prediction = cdqa_pipeline.predict(query)
# print("query: {}
".format(query))
# print("answer: {}
".format(prediction[0]))
# print("title: {}
".format(prediction[1]))
# print("paragraph: {}
".format(prediction[2]))
return prediction[0]
crawl_result_urls
for url in result_urls[:3]:
get_result_details(url)
sleep(5)
answer = find_answer
print("Answer: " + answer)
有时它可能会混淆,但我认为总体来说是可以的。至少我可以用60%的正确答案通过考试。
欢迎开发者们在评论中告诉我你的看法!实际上,最好是一次遍历所有问题,但我没有足够的时间来做这件事,所以只好下次继续再做。
(*本文由AI科技大本营编译,转载请联系微信1092722531)
【end】
福利直达!CSDN技术公开课评选进行中
直播进行中 | 技术驰援抗疫一线, Python 线上峰会全天精彩呈现
分布式数据集训营,从入门到精通,从理论到实践,你不可错过的精品课程!
区块链的阴暗面
QQ 群文件紧急扩容;钟南山团队与阿里云联手推进新冠疫苗研发;PhpStorm 2019.3.3 发布
愿得一心人:硅谷亿万富豪们的婚姻怎样?有人白首相守七十年
来源 | hackernoon编译 | 武明利责编 | Carol出品 | AI科技大本营(ID:rgznai100)在这篇文章中,我将向您展示如何使用Python构建自己的答案查找系统。基本上,这种自动化可以从图片中找到多项选择题的答案。
财联社8月9日讯(编辑 刘蕊)据网站故障实时监控平台DownDetector报告,北京时间周二上午,全球多地数万名用户报告谷歌搜索引擎出现故障。据报道称,美东时间周一晚9点20分左右(北京时间周二上午9点20分左右),全球有超过4万人报告谷
财联社(上海 编辑 夏军雄)讯,谷歌周三对欧洲第二最高法院表示,该公司向手机制造商支付预装谷歌搜索的费用,并不是为了排除竞争,而是与苹果争夺市场份额所必需的举措。在屡次被欧盟处以天价罚单之后,谷歌本周发起了反击,该公司试图让法院驳回创纪录的
近日,用谷歌搜索“idiot”一词后显示大量特朗普图片的这一事件引起热烈关注。在使用搜索引擎的时候,你有没有碰到过搜索出来的结果里出现了奇怪的东西的情况?前段时间,这个情况发生在了美国总统特朗普身上。12月11日,谷歌在听证会上遇到了一个非
据澎湃新闻12月12日报道,美国时间12月11日,谷歌CEO桑达尔·皮查伊(Sundar Pichai)在美国国会参加听证会,就谷歌搜索美国保守派内容是否遭到歧视、数据安全、假新闻、仇恨言论等议题展开讨论。 其中,美国国会众议员佐伊·洛夫格
今年,谷歌开发者大会将于12月8日和12月14日分别在北京和上海举办。这是2011年谷歌在中国举办开发者大会之后的再次回归。12月8日(今天)上午9点,谷歌开发者大会(Google Developer Day - GDD)正式在北京国家会议
想要了解更多热门资讯、玩机技巧、数码评测、科普深扒,可以点击右上角关注我们的头条号:雷科技-----------------------------------自谷歌因为某些原因退出中国市场后,这数年里有关“谷歌重回中国”的话题从未断绝。虽
机器之心报道机器之心编辑部BERT 是谷歌开源的一款自然语言处理预训练模型,一经推出就刷新了 11 项 NLP 任务的 SOTA 记录,登顶 GLUE 基准排行榜。具体到搜索引擎来说,BERT 可以帮助搜索引擎更好地理解 web 页面上的内
IT之家10月29日消息 在此前,谷歌搜索的结果可以通过域名来改变,比如你使用google.com.hk搜索的结果优先显示香港当地的搜索结果,不过谷歌已经决定取消这种搜索方式。谷歌近日在官方博客中宣布,其将取消通过域名决定搜索结果的搜索设定
在提供更精准的搜索结果之外,Google希望通过功能丰富的卡片和可扩展标签也进一步拓展搜索结果。在 今天更新的官方博文 中, 用户在搜索结果中可以扩展自动生成的标签额内容,从而提供更多关于用户搜索内容相关的子主题。谷歌产品经理皮尔斯·沃卢奇
6月8日,据外媒engadget报道,谷歌推出了一项搜索更新,旨在为用户提供更多的结果选项。该技术巨头表示,更新的内容将提供更好的搜索结果多样性。搜索结果的多样性丰富意味着我们不会在搜索结果中看到来自同一网站来源的两个以上的信息。但是如果特
根据外媒seroundtable报道称,谷歌现在显示一些时间、转化次数和计算相关的查询搜索结果的时候,有时候其搜索结果页面不显示全部搜索结果,相反,谷歌仅会提供一个搜索结果或答案。然后,如果你想要在搜索结果页面上查到搜索结果,就需要点击“显
IT之家4月26日消息 漫威大作《复仇者联盟4》正在全球各地热映。据9to5Google报道,谷歌在搜索服务中加入了一个来自《复仇者联盟》人物灭霸(Thanos)的彩蛋。现在在谷歌搜索上搜索“灭霸”,谷歌会在页面右侧的图片搜索结果附近“混”
谷歌搜索日前上线了一项新功能,把搜索历史展现在了显眼的位置,谷歌这样做貌似把用户搜索兴趣给存留下来,用户可以快速访问返回之前的搜索网站或者搜索结果页。谷歌 谷歌搜索引擎当打开Google搜索不想重复的搜索输入查询相同的问题,在Google
谷歌计划在其搜索服务中推出一项新功能,允许用户在搜索结果中留下其他人可以看到的评论。不过,用户发布的这些内容必须服从谷歌的政策,否则可能会无法显示。据《搜索引擎杂志》报道称,虽然这一功能还没有上线,但谷歌官方帮助文档已经描述了这一新功能的工