prompt: You will be provided with a partial code base and an issue statement explaining a problem to resolve.
  <issue>
  [demo] Improve UI for OCR result display
  For very dense documents, since the predicted text value is plotted statically, there can be some readability issues. We should try to improve this
  
  </issue>
  <code>
  [start of demo/app.py]
  1 # Copyright (C) 2021, Mindee.
  2 
  3 # This program is licensed under the Apache License version 2.
  4 # See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details.
  5 
  6 import os
  7 import streamlit as st
  8 import matplotlib.pyplot as plt
  9 
  10 os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
  11 
  12 import tensorflow as tf
  13 import cv2
  14 
  15 gpu_devices = tf.config.experimental.list_physical_devices('GPU')
  16 if any(gpu_devices):
  17     tf.config.experimental.set_memory_growth(gpu_devices[0], True)
  18 
  19 from doctr.documents import DocumentFile
  20 from doctr.models import ocr_predictor
  21 from doctr.utils.visualization import synthetize_page, visualize_page
  22 
  23 DET_ARCHS = ["db_resnet50"]
  24 RECO_ARCHS = ["crnn_vgg16_bn", "crnn_resnet31", "sar_vgg16_bn", "sar_resnet31"]
  25 
  26 
  27 def main():
  28 
  29     # Wide mode
  30     st.set_page_config(layout="wide")
  31 
  32     # Designing the interface
  33     st.title("DocTR: Document Text Recognition")
  34     # For newline
  35     st.write('\n')
  36     # Set the columns
  37     cols = st.beta_columns((1, 1))
  38     cols[0].subheader("Input document (first page)")
  39     cols[1].subheader("Raw heatmap (segmentation task)")
  40 
  41     # Sidebar
  42     # File selection
  43     st.sidebar.title("Document selection")
  44     # Disabling warning
  45     st.set_option('deprecation.showfileUploaderEncoding', False)
  46     # Choose your own image
  47     uploaded_file = st.sidebar.file_uploader("Upload files", type=['pdf', 'png', 'jpeg', 'jpg'])
  48     if uploaded_file is not None:
  49         if uploaded_file.name.endswith('.pdf'):
  50             doc = DocumentFile.from_pdf(uploaded_file.read()).as_images(output_size=(1024, 1024))
  51         else:
  52             doc = DocumentFile.from_images(uploaded_file.read())
  53         cols[0].image(doc[0], width=640)
  54 
  55     # Model selection
  56     st.sidebar.title("Model selection")
  57     det_arch = st.sidebar.selectbox("Text detection model", DET_ARCHS)
  58     reco_arch = st.sidebar.selectbox("Text recognition model", RECO_ARCHS)
  59 
  60     # For newline
  61     st.sidebar.write('\n')
  62 
  63     if st.sidebar.button("Analyze document"):
  64 
  65         if uploaded_file is None:
  66             st.sidebar.write("Please upload a document")
  67 
  68         else:
  69             with st.spinner('Loading model...'):
  70                 predictor = ocr_predictor(det_arch, reco_arch, pretrained=True)
  71 
  72             with st.spinner('Analyzing...'):
  73 
  74                 # Forward the image to the model
  75                 processed_batches = predictor.det_predictor.pre_processor(doc)
  76                 out = predictor.det_predictor.model(processed_batches[0], return_model_output=True, training=False)
  77                 seg_map = out["out_map"]
  78                 seg_map = tf.squeeze(seg_map[0, ...], axis=[2])
  79                 seg_map = cv2.resize(seg_map.numpy(), (doc[0].shape[1], doc[0].shape[0]),
  80                                      interpolation=cv2.INTER_LINEAR)
  81                 # Plot the raw heatmap
  82                 fig, ax = plt.subplots()
  83                 ax.imshow(seg_map)
  84                 ax.axis('off')
  85                 cols[1].pyplot(fig)
  86 
  87                 # Plot OCR output
  88                 out = predictor(doc, training=False)
  89                 cols[1].subheader("OCR output")
  90                 fig = visualize_page(out.pages[0].export(), doc[0], interactive=False)
  91                 cols[1].pyplot(fig)
  92 
  93                 # Page reconsitution under input page
  94                 cols[0].subheader("Page reconstitution from OCR output")
  95                 img = synthetize_page(out.pages[0].export())
  96                 cols[0].image(img, clamp=True, width=640)
  97 
  98 
  99 if __name__ == '__main__':
  100     main()
  101
  [end of demo/app.py]
  </code>
  
  I need you to solve this issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the following format.
  <patch>
  diff --git a/file.py b/file.py
  --- a/file.py
  +++ b/file.py
  @@ -1,27 +1,35 @@
   def euclidean(a, b):
  -    while b:
  -        a, b = b, a % b
  -    return a
  +    if b == 0:
  +        return a
  +    return euclidean(b, a % b)
   
   
   def bresenham(x0, y0, x1, y1):
       points = []
       dx = abs(x1 - x0)
       dy = abs(y1 - y0)
  -    sx = 1 if x0 < x1 else -1
  -    sy = 1 if y0 < y1 else -1
  -    err = dx - dy
  +    x, y = x0, y0
  +    sx = -1 if x0 > x1 else 1
  +    sy = -1 if y0 > y1 else 1
   
  -    while True:
  -        points.append((x0, y0))
  -        if x0 == x1 and y0 == y1:
  -            break
  -        e2 = 2 * err
  -        if e2 > -dy:
  -            err -= dy
  -            x0 += sx
  -        if e2 < dx:
  -            err += dx
  -            y0 += sy
  +    if dx > dy:
  +        err = dx / 2.0
  +        while x != x1:
  +            points.append((x, y))
  +            err -= dy
  +            if err < 0:
  +                y += sy
  +                err += dx
  +            x += sx
  +    else:
  +        err = dy / 2.0
  +        while y != y1:
  +            points.append((x, y))
  +            err -= dx
  +            if err < 0:
  +                x += sx
  +                err += dy
  +            y += sy
  +
  +    points.append((x, y))
       return points
  
  </patch>
golden_diff: diff --git a/demo/app.py b/demo/app.py
  --- a/demo/app.py
  +++ b/demo/app.py
  @@ -33,10 +33,14 @@
       st.title("DocTR: Document Text Recognition")
       # For newline
       st.write('\n')
  +    # Instructions
  +    st.markdown("*Hint: click on the top-right corner of an image to enlarge it!*")
       # Set the columns
  -    cols = st.beta_columns((1, 1))
  -    cols[0].subheader("Input document (first page)")
  -    cols[1].subheader("Raw heatmap (segmentation task)")
  +    cols = st.beta_columns((1, 1, 1, 1))
  +    cols[0].subheader("Input page")
  +    cols[1].subheader("Segmentation heatmap")
  +    cols[2].subheader("OCR output")
  +    cols[3].subheader("Page reconstitution")
   
       # Sidebar
       # File selection
  @@ -50,7 +54,8 @@
               doc = DocumentFile.from_pdf(uploaded_file.read()).as_images(output_size=(1024, 1024))
           else:
               doc = DocumentFile.from_images(uploaded_file.read())
  -        cols[0].image(doc[0], width=640)
  +        page_idx = st.sidebar.selectbox("Page selection", [idx + 1 for idx in range(len(doc))]) - 1
  +        cols[0].image(doc[page_idx])
   
       # Model selection
       st.sidebar.title("Model selection")
  @@ -60,7 +65,7 @@
       # For newline
       st.sidebar.write('\n')
   
  -    if st.sidebar.button("Analyze document"):
  +    if st.sidebar.button("Analyze page"):
   
           if uploaded_file is None:
               st.sidebar.write("Please upload a document")
  @@ -72,11 +77,11 @@
               with st.spinner('Analyzing...'):
   
                   # Forward the image to the model
  -                processed_batches = predictor.det_predictor.pre_processor(doc)
  +                processed_batches = predictor.det_predictor.pre_processor([doc[page_idx]])
                   out = predictor.det_predictor.model(processed_batches[0], return_model_output=True, training=False)
                   seg_map = out["out_map"]
                   seg_map = tf.squeeze(seg_map[0, ...], axis=[2])
  -                seg_map = cv2.resize(seg_map.numpy(), (doc[0].shape[1], doc[0].shape[0]),
  +                seg_map = cv2.resize(seg_map.numpy(), (doc[page_idx].shape[1], doc[page_idx].shape[0]),
                                        interpolation=cv2.INTER_LINEAR)
                   # Plot the raw heatmap
                   fig, ax = plt.subplots()
  @@ -85,15 +90,18 @@
                   cols[1].pyplot(fig)
   
                   # Plot OCR output
  -                out = predictor(doc, training=False)
  -                cols[1].subheader("OCR output")
  -                fig = visualize_page(out.pages[0].export(), doc[0], interactive=False)
  -                cols[1].pyplot(fig)
  +                out = predictor([doc[page_idx]], training=False)
  +                fig = visualize_page(out.pages[0].export(), doc[page_idx], interactive=False)
  +                cols[2].pyplot(fig)
   
                   # Page reconsitution under input page
  -                cols[0].subheader("Page reconstitution from OCR output")
  -                img = synthetize_page(out.pages[0].export())
  -                cols[0].image(img, clamp=True, width=640)
  +                page_export = out.pages[0].export()
  +                img = synthetize_page(page_export)
  +                cols[3].image(img, clamp=True)
  +
  +                # Display JSON
  +                st.markdown("\nHere are your analysis results in JSON format:")
  +                st.json(page_export)
   
   
   if __name__ == '__main__':
  
verification_info: {"golden_diff": "diff --git a/demo/app.py b/demo/app.py\n--- a/demo/app.py\n+++ b/demo/app.py\n@@ -33,10 +33,14 @@\n     st.title(\"DocTR: Document Text Recognition\")\n     # For newline\n     st.write('\\n')\n+    # Instructions\n+    st.markdown(\"*Hint: click on the top-right corner of an image to enlarge it!*\")\n     # Set the columns\n-    cols = st.beta_columns((1, 1))\n-    cols[0].subheader(\"Input document (first page)\")\n-    cols[1].subheader(\"Raw heatmap (segmentation task)\")\n+    cols = st.beta_columns((1, 1, 1, 1))\n+    cols[0].subheader(\"Input page\")\n+    cols[1].subheader(\"Segmentation heatmap\")\n+    cols[2].subheader(\"OCR output\")\n+    cols[3].subheader(\"Page reconstitution\")\n \n     # Sidebar\n     # File selection\n@@ -50,7 +54,8 @@\n             doc = DocumentFile.from_pdf(uploaded_file.read()).as_images(output_size=(1024, 1024))\n         else:\n             doc = DocumentFile.from_images(uploaded_file.read())\n-        cols[0].image(doc[0], width=640)\n+        page_idx = st.sidebar.selectbox(\"Page selection\", [idx + 1 for idx in range(len(doc))]) - 1\n+        cols[0].image(doc[page_idx])\n \n     # Model selection\n     st.sidebar.title(\"Model selection\")\n@@ -60,7 +65,7 @@\n     # For newline\n     st.sidebar.write('\\n')\n \n-    if st.sidebar.button(\"Analyze document\"):\n+    if st.sidebar.button(\"Analyze page\"):\n \n         if uploaded_file is None:\n             st.sidebar.write(\"Please upload a document\")\n@@ -72,11 +77,11 @@\n             with st.spinner('Analyzing...'):\n \n                 # Forward the image to the model\n-                processed_batches = predictor.det_predictor.pre_processor(doc)\n+                processed_batches = predictor.det_predictor.pre_processor([doc[page_idx]])\n                 out = predictor.det_predictor.model(processed_batches[0], return_model_output=True, training=False)\n                 seg_map = out[\"out_map\"]\n                 seg_map = tf.squeeze(seg_map[0, ...], axis=[2])\n-                seg_map = cv2.resize(seg_map.numpy(), (doc[0].shape[1], doc[0].shape[0]),\n+                seg_map = cv2.resize(seg_map.numpy(), (doc[page_idx].shape[1], doc[page_idx].shape[0]),\n                                      interpolation=cv2.INTER_LINEAR)\n                 # Plot the raw heatmap\n                 fig, ax = plt.subplots()\n@@ -85,15 +90,18 @@\n                 cols[1].pyplot(fig)\n \n                 # Plot OCR output\n-                out = predictor(doc, training=False)\n-                cols[1].subheader(\"OCR output\")\n-                fig = visualize_page(out.pages[0].export(), doc[0], interactive=False)\n-                cols[1].pyplot(fig)\n+                out = predictor([doc[page_idx]], training=False)\n+                fig = visualize_page(out.pages[0].export(), doc[page_idx], interactive=False)\n+                cols[2].pyplot(fig)\n \n                 # Page reconsitution under input page\n-                cols[0].subheader(\"Page reconstitution from OCR output\")\n-                img = synthetize_page(out.pages[0].export())\n-                cols[0].image(img, clamp=True, width=640)\n+                page_export = out.pages[0].export()\n+                img = synthetize_page(page_export)\n+                cols[3].image(img, clamp=True)\n+\n+                # Display JSON\n+                st.markdown(\"\\nHere are your analysis results in JSON format:\")\n+                st.json(page_export)\n \n \n if __name__ == '__main__':\n", "issue": "[demo] Improve UI for OCR result display\nFor very dense documents, since the predicted text value is plotted statically, there can be some readability issues. We should try to improve this\n", "before_files": [{"content": "# Copyright (C) 2021, Mindee.\n\n# This program is licensed under the Apache License version 2.\n# See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details.\n\nimport os\nimport streamlit as st\nimport matplotlib.pyplot as plt\n\nos.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = \"2\"\n\nimport tensorflow as tf\nimport cv2\n\ngpu_devices = tf.config.experimental.list_physical_devices('GPU')\nif any(gpu_devices):\n    tf.config.experimental.set_memory_growth(gpu_devices[0], True)\n\nfrom doctr.documents import DocumentFile\nfrom doctr.models import ocr_predictor\nfrom doctr.utils.visualization import synthetize_page, visualize_page\n\nDET_ARCHS = [\"db_resnet50\"]\nRECO_ARCHS = [\"crnn_vgg16_bn\", \"crnn_resnet31\", \"sar_vgg16_bn\", \"sar_resnet31\"]\n\n\ndef main():\n\n    # Wide mode\n    st.set_page_config(layout=\"wide\")\n\n    # Designing the interface\n    st.title(\"DocTR: Document Text Recognition\")\n    # For newline\n    st.write('\\n')\n    # Set the columns\n    cols = st.beta_columns((1, 1))\n    cols[0].subheader(\"Input document (first page)\")\n    cols[1].subheader(\"Raw heatmap (segmentation task)\")\n\n    # Sidebar\n    # File selection\n    st.sidebar.title(\"Document selection\")\n    # Disabling warning\n    st.set_option('deprecation.showfileUploaderEncoding', False)\n    # Choose your own image\n    uploaded_file = st.sidebar.file_uploader(\"Upload files\", type=['pdf', 'png', 'jpeg', 'jpg'])\n    if uploaded_file is not None:\n        if uploaded_file.name.endswith('.pdf'):\n            doc = DocumentFile.from_pdf(uploaded_file.read()).as_images(output_size=(1024, 1024))\n        else:\n            doc = DocumentFile.from_images(uploaded_file.read())\n        cols[0].image(doc[0], width=640)\n\n    # Model selection\n    st.sidebar.title(\"Model selection\")\n    det_arch = st.sidebar.selectbox(\"Text detection model\", DET_ARCHS)\n    reco_arch = st.sidebar.selectbox(\"Text recognition model\", RECO_ARCHS)\n\n    # For newline\n    st.sidebar.write('\\n')\n\n    if st.sidebar.button(\"Analyze document\"):\n\n        if uploaded_file is None:\n            st.sidebar.write(\"Please upload a document\")\n\n        else:\n            with st.spinner('Loading model...'):\n                predictor = ocr_predictor(det_arch, reco_arch, pretrained=True)\n\n            with st.spinner('Analyzing...'):\n\n                # Forward the image to the model\n                processed_batches = predictor.det_predictor.pre_processor(doc)\n                out = predictor.det_predictor.model(processed_batches[0], return_model_output=True, training=False)\n                seg_map = out[\"out_map\"]\n                seg_map = tf.squeeze(seg_map[0, ...], axis=[2])\n                seg_map = cv2.resize(seg_map.numpy(), (doc[0].shape[1], doc[0].shape[0]),\n                                     interpolation=cv2.INTER_LINEAR)\n                # Plot the raw heatmap\n                fig, ax = plt.subplots()\n                ax.imshow(seg_map)\n                ax.axis('off')\n                cols[1].pyplot(fig)\n\n                # Plot OCR output\n                out = predictor(doc, training=False)\n                cols[1].subheader(\"OCR output\")\n                fig = visualize_page(out.pages[0].export(), doc[0], interactive=False)\n                cols[1].pyplot(fig)\n\n                # Page reconsitution under input page\n                cols[0].subheader(\"Page reconstitution from OCR output\")\n                img = synthetize_page(out.pages[0].export())\n                cols[0].image(img, clamp=True, width=640)\n\n\nif __name__ == '__main__':\n    main()\n", "path": "demo/app.py"}]}