import time
import cv2
from PIL import Image
import pyocr
import pyocr.builders
import streamlit as st

if __name__ == "__main__":

    st.title("RT OCR demo")
    state = st.checkbox("use web cam")
    tools = pyocr.get_available_tools()
    ocr = tools[0]

    live_view = st.empty()
    draw_view = st.empty()
    text_area = st.empty()

    cap = cv2.VideoCapture(0)
    while cap.isOpened and state:
        ret, frame = cap.read()

        im = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))

        live_view.image(im)

        lines = ocr.image_to_string(
            im, lang="jpn_best", builder=pyocr.builders.LineBoxBuilder()
        )

        texts = []
        for line in lines:
            # line の描画
            (l, t), (r, b) = line.position
            cv2.rectangle(frame, (l, t), (r, b), (255, 0, 0), 5)
            cv2.line(frame, (l, (t + b) // 2), (r, (t + b) // 2), (255, 0, 0), 5)

            # word box の描画
            texts.append(line.content)
            for box in line.word_boxes:
                ul, lr = box.position
                cv2.rectangle(frame, ul, lr, (0, 255, 0), 5)

        text_area.text("\n".join(texts))
        drawd = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))

        draw_view.image(drawd)

    # if cv2.waitKey(1) & 0xFF == ord("q"):
    #     break
    # while cap.isOpened:
    #     print("d")
    # a = st.sidebar.radio("R:", [1, 2])
    # st.text("Fixed width text")
    # st.markdown("_Markdown_")  # see *
    # st.latex(r""" e^{i\pi} + 1 = 0 """)
    # st.write("Most objects")  # df, err, func, keras!
    # st.write(["st", "is <", 3])  # see *

    # st.title("My title")
    # st.header("My header")
    # st.subheader("My sub")
    # st.code(
    #     """
    # for i in ranee(8):
    #     foo()
    # """
    # )
    # li = [
    #     st.button("Hit me"),
    #     st.checkbox("Check me out"),
    #     st.radio("Radio", [1, 2, 3]),
    #     st.selectbox("Select", [1, 2, 3]),
    #     st.multiselect("Multiselect", [1, 2, 3]),
    #     st.slider("Slide me", min_value=0, max_value=10),
    #     st.select_slider("Slide to select", options=[1, "2"]),
    #     st.text_input("Enter some text"),
    #     st.number_input("Enter a number"),
    #     st.text_area("Area for textual entry"),
    #     st.date_input("Date input"),
    #     st.time_input("Time entry"),
    #     st.file_uploader("File uploader"),
    #     st.color_picker("Pick a color"),
    # ]

    # st.image("testdata/title2.jpg")

    # print("----===== data =====----")
    # for ll in li:
    #     print(ll)
