Spaces:
Build error
Build error
test
Browse filesFiles changed (2)
- app.py+3-121
- requirements.txt+2-1
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124import streamlit as stfrom akaocr import TextEngine, BoxEngineimport cv2import numpy as npfrom PIL import Imageimport timeimport pyperclip # Import pyperclip for clipboard operationsfrom streamlit_drawable_canvas import st_canvas# Initialize the OCR enginesbox_engine = BoxEngine()text_engine = TextEngine()def transform_image(image, box):# Get perspective transform imageassert len(box) == 4, "Shape of points must be 4x2"img_crop_width = int(max(np.linalg.norm(box[0] - box[1]),np.linalg.norm(box[2] - box[3])))img_crop_height = int(max(np.linalg.norm(box[0] - box[3]),np.linalg.norm(box[1] - box[2])))pts_std = np.float32([[0, 0],[img_crop_width, 0],[img_crop_width, img_crop_height],[0, img_crop_height]])box = np.array(box, dtype="float32")M = cv2.getPerspectiveTransform(box, pts_std)dst_img = cv2.warpPerspective(image,M, (img_crop_width, img_crop_height),borderMode=cv2.BORDER_REPLICATE,flags=cv2.INTER_CUBIC)img_height, img_width = dst_img.shape[0:2]if img_height/img_width >= 1.25:dst_img = np.rot90(dst_img, k=3)return dst_imgdef is_point_in_box(point, box):"""Check if a point is inside a bounding box."""x, y = pointcontour = box.reshape((-1, 1, 2)).astype(np.int32)return cv2.pointPolygonTest(contour, (x, y), False) >= 0def main():st.title("Quick OCR Copy")uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])if uploaded_file is not None:# Convert the uploaded file to an OpenCV imagefile_bytes = np.asarray(bytearray(uploaded_file.read()), dtype=np.uint8)org_image = cv2.imdecode(file_bytes, 1)# st.image(org_image, channels="BGR", caption='Uploaded Image')images = []start = time.perf_counter()boxes = box_engine(org_image)processing_time = time.perf_counter() - startst.write(f"Box detection took {processing_time:.2f} seconds.")# Extracted text for each boxextracted_texts = []for box in boxes[::-1]:org_image = cv2.polylines(org_image, [box.astype(np.int32)], isClosed=True, color=(0, 255, 0), thickness=2)image = transform_image(org_image, box)images.append(image)# Get the texts from the boxestexts = text_engine(images)# Store extracted texts with corresponding boxesfor text, box in zip(texts, boxes[::-1]):extracted_texts.append((text, box))# Convert back to PIL Image for displayingoutput_image = Image.fromarray(cv2.cvtColor(org_image, cv2.COLOR_BGR2RGB))# st.image(output_image, caption='Detected Text Boxes', use_column_width=True)# Create a drawable canvascanvas_result = st_canvas(background_image=output_image,stroke_width=0,update_streamlit=True,height=output_image.height,width=output_image.width,drawing_mode="freedraw", # Disable drawing to make it click onlykey="canvas",)# Check if any clicks are detectedif canvas_result.json_data is not None:for annotation in canvas_result.json_data["objects"]:x = annotation["left"]y = annotation["top"]clicked_point = (x, y)# Check which bounding box the user clicked onfor text, box in extracted_texts:if is_point_in_box(clicked_point, box):# pyperclip.copy(text[0]) # Copy text to clipboard# Show popup messagest.toast(f"Text copied to clipboard: {text}")break # Exit after finding the first matchif __name__ == '__main__':main()123456import streamlit as stfrom st_copy_to_clipboard import st_copy_to_clipboard# Render copy to clipboard buttonst_copy_to_clipboard("Copy this to clipboard")
2 unmodified lines34562 unmodified linesopencv-python-headlessnumpypyperclipstreamlit_drawable_canvas2 unmodified lines345672 unmodified linesopencv-python-headlessnumpypyperclipstreamlit_drawable_canvasst-copy-to-clipboard
app.py+3-121
requirements.txt+2-1