import os # os.system("pip install -q gradio==4.10.0") # os.system("pip install torch==2.1.0 torchvision torchaudio") # os.system("pip install 'git+https://github.com/facebookresearch/detectron2.git@v0.6'") # os.system("pip install layoutparser==0.3.4 layoutparser[layoutmodels] layoutparser[ocr]") # os.system("pip install requests==2.31.0") os.system("pip install torch") os.system("pip install 'git+https://github.com/facebookresearch/detectron2.git'") os.system("pip install layoutparser layoutparser[layoutmodels] layoutparser[ocr]") os.system("pip install Pillow==9.4.0") import gradio as gr import layoutparser as lp from PIL import Image from urllib.parse import urlparse import requests def get_RGB_image(image_or_path: str | Image.Image) -> bytes: if isinstance(image_or_path, str): if urlparse(image_or_path).scheme in ["http", "https"]: # Online image_or_path = Image.open( requests.get(image_or_path, stream=True).raw) else: # Local image_or_path = Image.open(image_or_path) return image_or_path.convert("RGB") def inference_factory(config_path: str, model_path: str, label_map: dict, color_map: dict, examples=[], launch=True): import traceback model: lp.elements.layout.Layout = lp.Detectron2LayoutModel( config_path=config_path, model_path=model_path, # extra_config = ["MODEL.ROI_HEADS.SCORE_THRESH_TEST", 0.8], label_map=label_map) default_threshold = 0.8 cache = { 'annotated_image': None, 'message': None, 'threshold': default_threshold, 'image': None, 'predicted': None } def truncate(f, n): return int(f * 10 ** n) / 10 ** n def fn(image: Image.Image, threshold: float = default_threshold, just_image=True): try: nonlocal cache if cache['image'] == image and cache['threshold'] == threshold and bool(cache['annotated_image']): return [cache['annotated_image'], cache['message'], cache['threshold']] layout_predicted = cache['predicted'] if cache['image'] == image else model.detect( image) threshold = truncate( min([max([block.score for block in layout_predicted] + [0])] + [threshold]), 1) blocks: List[lp.elements.layout_elements.TextBlock] = [block.set( id=f'{block.type}/{block.score:.2f}') for block in layout_predicted if block.score >= threshold] annotated_image = lp.draw_box( image, blocks, color_map=color_map, show_element_id=True, id_font_size=14, id_text_background_color='black', id_text_color='white') message = \ f'{len(blocks)} bounding boxes matched for {threshold} threshold, out of {len(layout_predicted)} total bounding boxes' if len(blocks) > 0 \ else f'No bounding boxesfor {threshold} threshold.' cache = { 'annotated_image': annotated_image, 'message': message, 'threshold': threshold, 'image': image, 'predicted': layout_predicted } return annotated_image if just_image else [annotated_image, message, threshold] except Exception as e: error = traceback.format_exc() return error if just_image else [None, error, threshold] if not launch: return fn ########################################################### ################### Start of Gradio setup ################# ########################################################### title = "Document Similarity Search using Detectron2" description = "