
原帖:https://baxin.netlify.app/build-text-extractor-python-under-30-lines/
从图像中提取文本,称为光学字符识别 (ocr),对于文档处理、数据提取和可访问性应用程序来说是一项很有价值的功能。在本指南中,我们将使用 python 库创建一个 ocr 应用程序,例如用于 ocr 的 pytesseract、用于图像处理的 pillow 以及用于构建交互式 ui 的 gradio。我们将在 hugging face spaces 上部署此应用程序。
先决条件
开始之前,您需要一个 hugging face 帐户并对 docker 有基本的了解。
分步指南
第 1 步:创建一个拥抱脸部空间
导航到 hugging face spaces:登录 hugging face 并转到“spaces”部分。创建一个新空间:点击“新空间”。为您的空间命名(例如,图像文本提取器)。选择gradio作为sdk并设置可见性(公共或私有)。点击“创建空间”。
第 2 步:创建 dockerfile
要在具有所需系统依赖项的 hugging face spaces 上部署(例如用于 ocr 的 tesseract),我们需要一个用于配置环境的 dockerfile。
立即学习“Python免费学习笔记(深入)”;
创建一个包含以下内容的 dockerfile:
# use an official python runtime as a parent imagefrom python:3.12env pip_root_user_action=ignore# set the working directory in the containerworkdir $home/app# install system dependenciesrun apt-get update && apt-get install -yrun apt-get install -y tesseract-ocrrun apt-get install -y libtesseract-devrun apt-get install -y libgl1-mesa-glxrun apt-get install -y libglib2.0-0run pip install --upgrade pip# copy requirements and install dependenciescopy requirements.txt requirements.txtrun pip install --no-cache-dir -r requirements.txt# copy the app codecopy app.py ./# expose the port for gradioexpose 7860# run the applicationcmd ["python", "app.py"]
第 3 步:创建 ocr 应用程序
创建一个名为 app.py 的文件,其中包含以下内容:
import gradio as grimport pytesseractfrom pil import imageimport osdef extract_text(image_path): if not image_path: return "no image uploaded. please upload an image." if not os.path.exists(image_path): return f"error: file not found at {image_path}" try: img = image.open(image_path) text = pytesseract.image_to_string(img) return text if text.strip() else "no text detected in the image." except exception as e: return f"an error occurred: {str(e)}"iface = gr.interface( fn=extract_text, inputs=gr.image(type="filepath", label="upload an image"), outputs=gr.textbox(label="extracted text"), title="image text extractor", description="upload an image and extract text from it using ocr.")iface.launch(server_name="0.0.0.0", server_port=7860)
创建requirements.txt文件来指定依赖项:
gradiopytesseractPillow
此设置包括:
图像上传:gr.image(type=”filepath”) 允许用户将图像作为文件路径上传,由 pytesseract 处理。文本提取:pytesseract.image_to_string 从图像中提取文本。用户界面:gradio 生成一个简单的 ui,供用户上传图像和查看提取的文本。
第 4 步:将所有文件推送到拥抱面部空间
创建所有文件后,将它们推送到您的拥抱空间
以上就是使用 Gradio 和 Hugging Face 在 Lines 下使用 Python 代码构建文本提取器应用程序的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1350655.html
微信扫一扫
支付宝扫一扫