Spaces:
Paused
Paused
Commit ·
4eb7c20
1
Parent(s): 049c6c7
Switch HF Spaces to Torch (credit: @Felix92 )
Browse filesFiles changed (4)
- README.md+12-11
- app.py+46-50
- backend/pytorch.pyAdded+86
- requirements.txt+1-2
3 unmodified lines45678910111213141516171819202122232425262728293031323334353637383 unmodified linescolorFrom: purplecolorTo: pinksdk: streamlitsdk_version: 0.84.2app_file: app.pypinned: false---# Configuration`title`: _string_Display title for the Space`emoji`: _string_Space emoji (emoji-only character allowed)`colorFrom`: _string_Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray)`colorTo`: _string_Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray)`sdk`: _string_Can be either `gradio` or `streamlit``sdk_version` : _string_Only applicable for `streamlit` SDK.See [doc](https://hf.co/docs/hub/spaces) for more info on supported versions.`app_file`: _string_Path to your main application file (which contains either `gradio` or `streamlit` Python code).Path is relative to the root of the repository.`pinned`: _boolean_Whether the Space stays on top of your list.3 unmodified lines4567891011121314151617181920212223242526272829303132333435363738393 unmodified linescolorFrom: purplecolorTo: pinksdk: streamlitsdk_version: 1.30.0app_file: app.pypinned: falselicense: apache-2.0---# Configuration`title`: _string_Display title for the Space`emoji`: _string_Space emoji (emoji-only character allowed)`colorFrom`: _string_Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray)`colorTo`: _string_Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray)`sdk`: _string_Can be either `gradio` or `streamlit``sdk_version` : _string_Only applicable for `streamlit` SDK.See [doc](https://hf.co/docs/hub/spaces) for more info on supported versions.`app_file`: _string_Path to your main application file (which contains either `gradio` or `streamlit` Python code).Path is relative to the root of the repository.`pinned`: _boolean_Whether the Space stays on top of your list.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546472 unmodified lines5051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113# Copyright (C) 2021, Mindee.# This program is licensed under the Apache License version 2.# See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details.import osimport matplotlib.pyplot as pltimport streamlit as stos.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"import cv2import tensorflow as tfgpu_devices = tf.config.experimental.list_physical_devices('GPU')if any(gpu_devices):tf.config.experimental.set_memory_growth(gpu_devices[0], True)from doctr.io import DocumentFilefrom doctr.models import ocr_predictorfrom doctr.utils.visualization import visualize_pageDET_ARCHS = ["db_resnet50", "db_mobilenet_v3_large"]RECO_ARCHS = ["crnn_vgg16_bn", "crnn_mobilenet_v3_small", "master", "sar_resnet31"]def main():# Wide modest.set_page_config(layout="wide")# Designing the interfacest.title("docTR: Document Text Recognition")# For newlinest.write('\n')#st.write('Find more info at: https://github.com/mindee/doctr')# For newlinest.write('\n')# Instructionsst.markdown("*Hint: click on the top-right corner of an image to enlarge it!*")# Set the columnscols = st.beta_columns((1, 1, 1, 1))cols[0].subheader("Input page")cols[1].subheader("Segmentation heatmap")cols[2].subheader("OCR output")2 unmodified lines# Sidebar# File selectionst.sidebar.title("Document selection")# Disabling warningst.set_option('deprecation.showfileUploaderEncoding', False)# Choose your own imageuploaded_file = st.sidebar.file_uploader("Upload files", type=['pdf', 'png', 'jpeg', 'jpg'])if uploaded_file is not None:if uploaded_file.name.endswith('.pdf'):doc = DocumentFile.from_pdf(uploaded_file.read())else:doc = DocumentFile.from_images(uploaded_file.read())page_idx = st.sidebar.selectbox("Page selection", [idx + 1 for idx in range(len(doc))]) - 1cols[0].image(doc[page_idx])# Model selectionst.sidebar.title("Model selection")det_arch = st.sidebar.selectbox("Text detection model", DET_ARCHS)reco_arch = st.sidebar.selectbox("Text recognition model", RECO_ARCHS)# For newlinest.sidebar.write('\n')if st.sidebar.button("Analyze page"):if uploaded_file is None:st.sidebar.write("Please upload a document")else:with st.spinner('Loading model...'):predictor = ocr_predictor(det_arch, reco_arch, pretrained=True)with st.spinner('Analyzing...'):# Forward the image to the modelprocessed_batches = predictor.det_predictor.pre_processor([doc[page_idx]])out = predictor.det_predictor.model(processed_batches[0], return_model_output=True)seg_map = out["out_map"]seg_map = tf.squeeze(seg_map[0, ...], axis=[2])seg_map = cv2.resize(seg_map.numpy(), (doc[page_idx].shape[1], doc[page_idx].shape[0]),interpolation=cv2.INTER_LINEAR)# Plot the raw heatmapfig, ax = plt.subplots()ax.imshow(seg_map)ax.axis('off')cols[1].pyplot(fig)# Plot OCR outputout = predictor([doc[page_idx]])fig = visualize_page(out.pages[0].export(), doc[page_idx], interactive=False)cols[2].pyplot(fig)# Page reconsitution under input pagepage_export = out.pages[0].export()img = out.pages[0].synthesize()cols[3].image(img, clamp=True)# Display JSONst.markdown("\nHere are your analysis results in JSON format:")st.json(page_export)if __name__ == '__main__':main()12345678910111213141516171819202122232425262728293031323334352 unmodified lines3839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109# Copyright (C) 2021-2024, Mindee.# This program is licensed under the Apache License 2.0.# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.import cv2import matplotlib.pyplot as pltimport numpy as npimport streamlit as stimport torchfrom doctr.io import DocumentFilefrom doctr.utils.visualization import visualize_pagefrom backend.pytorch import DET_ARCHS, RECO_ARCHS, forward_image, load_predictorforward_device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")def main(det_archs, reco_archs):"""Build a streamlit layout"""# Wide modest.set_page_config(layout="wide")# Designing the interfacest.title("docTR: Document Text Recognition")# For newlinest.write("\n")# Instructionsst.markdown("*Hint: click on the top-right corner of an image to enlarge it!*")# Set the columnscols = st.columns((1, 1, 1, 1))cols[0].subheader("Input page")cols[1].subheader("Segmentation heatmap")cols[2].subheader("OCR output")2 unmodified lines# Sidebar# File selectionst.sidebar.title("Document selection")# Choose your own imageuploaded_file = st.sidebar.file_uploader("Upload files", type=["pdf", "png", "jpeg", "jpg"])if uploaded_file is not None:if uploaded_file.name.endswith(".pdf"):doc = DocumentFile.from_pdf(uploaded_file.read())else:doc = DocumentFile.from_images(uploaded_file.read())page_idx = st.sidebar.selectbox("Page selection", [idx + 1 for idx in range(len(doc))]) - 1page = doc[page_idx]cols[0].image(page)# Model selectionst.sidebar.title("Model selection")det_arch = st.sidebar.selectbox("Text detection model", det_archs)reco_arch = st.sidebar.selectbox("Text recognition model", reco_archs)# For newlinest.sidebar.write("\n")# Only straight pages or possible rotationst.sidebar.title("Parameters")assume_straight_pages = st.sidebar.checkbox("Assume straight pages", value=True)st.sidebar.write("\n")# Straighten pagesstraighten_pages = st.sidebar.checkbox("Straighten pages", value=False)st.sidebar.write("\n")# Binarization thresholdbin_thresh = st.sidebar.slider("Binarization threshold", min_value=0.1, max_value=0.9, value=0.3, step=0.1)st.sidebar.write("\n")if st.sidebar.button("Analyze page"):if uploaded_file is None:st.sidebar.write("Please upload a document")else:with st.spinner("Loading model..."):predictor = load_predictor(det_arch, reco_arch, assume_straight_pages, straighten_pages, bin_thresh, forward_device)with st.spinner("Analyzing..."):# Forward the image to the modelseg_map = forward_image(predictor, page, forward_device)seg_map = np.squeeze(seg_map)seg_map = cv2.resize(seg_map, (page.shape[1], page.shape[0]), interpolation=cv2.INTER_LINEAR)# Plot the raw heatmapfig, ax = plt.subplots()ax.imshow(seg_map)ax.axis("off")cols[1].pyplot(fig)# Plot OCR outputout = predictor([page])fig = visualize_page(out.pages[0].export(), out.pages[0].page, interactive=False, add_labels=False)cols[2].pyplot(fig)# Page reconsitution under input pagepage_export = out.pages[0].export()if assume_straight_pages or (not assume_straight_pages and straighten_pages):img = out.pages[0].synthesize()cols[3].image(img, clamp=True)# Display JSONst.markdown("\nHere are your analysis results in JSON format:")st.json(page_export)if __name__ == "__main__":main(DET_ARCHS, RECO_ARCHS)
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586# Copyright (C) 2021-2024, Mindee.
# This program is licensed under the Apache License 2.0.# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
import numpy as npimport torch
from doctr.models import ocr_predictorfrom doctr.models.predictor import OCRPredictor
DET_ARCHS = [ "db_resnet50", "db_resnet34", "db_mobilenet_v3_large", "linknet_resnet18", "linknet_resnet34", "linknet_resnet50",]RECO_ARCHS = [ "crnn_vgg16_bn", "crnn_mobilenet_v3_small", "crnn_mobilenet_v3_large", "master", "sar_resnet31", "vitstr_small", "vitstr_base", "parseq",]
def load_predictor( det_arch: str, reco_arch: str, assume_straight_pages: bool, straighten_pages: bool, bin_thresh: float, device: torch.device,) -> OCRPredictor: """Load a predictor from doctr.models
Args: ---- det_arch: detection architecture reco_arch: recognition architecture assume_straight_pages: whether to assume straight pages or not straighten_pages: whether to straighten rotated pages or not bin_thresh: binarization threshold for the segmentation map device: torch.device, the device to load the predictor on
Returns: ------- instance of OCRPredictor """ predictor = ocr_predictor( det_arch, reco_arch, pretrained=True, assume_straight_pages=assume_straight_pages, straighten_pages=straighten_pages, export_as_straight_boxes=straighten_pages, detect_orientation=not assume_straight_pages, ).to(device) predictor.det_predictor.model.postprocessor.bin_thresh = bin_thresh return predictor
def forward_image(predictor: OCRPredictor, image: np.ndarray, device: torch.device) -> np.ndarray: """Forward an image through the predictor
Args: ---- predictor: instance of OCRPredictor image: image to process device: torch.device, the device to process the image on
Returns: ------- segmentation map """ with torch.no_grad(): processed_batches = predictor.det_predictor.pre_processor([image]) out = predictor.det_predictor.model(processed_batches[0].to(device), return_model_output=True) seg_map = out["out_map"].to("cpu").numpy()
return seg_map123-e git+https://github.com/mindee/doctr.git#egg=python-doctr[tf]streamlit>=1.0.0PyMuPDF>=1.16.0,!=1.18.11,!=1.18.12,!=1.19.512-e git+https://github.com/mindee/doctr.git#egg=python-doctr[torch]streamlit>=1.0.0
README.md+12-11
app.py+46-50
backend/pytorch.pyAdded+86
requirements.txt+1-2