Spaces:
Sleeping
Sleeping
gauthambalraj07@gmail.com
commited on
Commit
·
a1c932a
1
Parent(s):
0f7b8c8
Initial commit with model files
Browse files- .DS_Store +0 -0
- Dockerfile +35 -0
- app.py +133 -0
- download_models.py +40 -0
- requirements.txt +21 -0
- utils.py +535 -0
.DS_Store
ADDED
|
Binary file (6.15 kB). View file
|
|
|
Dockerfile
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Use Python 3.9 slim base image
|
| 2 |
+
FROM python:3.9-slim
|
| 3 |
+
|
| 4 |
+
# Install system dependencies
|
| 5 |
+
RUN apt-get update && apt-get install -y \
|
| 6 |
+
libgl1-mesa-glx \
|
| 7 |
+
libglib2.0-0 \
|
| 8 |
+
wget \
|
| 9 |
+
git \
|
| 10 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 11 |
+
|
| 12 |
+
# Set working directory
|
| 13 |
+
WORKDIR /app
|
| 14 |
+
|
| 15 |
+
# Copy requirements and install dependencies
|
| 16 |
+
COPY requirements.txt .
|
| 17 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 18 |
+
|
| 19 |
+
# Create directories for models and temporary files with proper permissions
|
| 20 |
+
RUN mkdir -p /app/weights/icon_detect /app/weights/icon_caption_florence /app/imgs \
|
| 21 |
+
&& chown -R 1000:1000 /app
|
| 22 |
+
|
| 23 |
+
# Copy application code
|
| 24 |
+
COPY main.py utils.py download_models.py ./
|
| 25 |
+
|
| 26 |
+
# Download models during build
|
| 27 |
+
RUN python download_models.py
|
| 28 |
+
|
| 29 |
+
# Set up user for HF Spaces
|
| 30 |
+
RUN useradd -m -u 1000 user
|
| 31 |
+
USER user
|
| 32 |
+
ENV PATH="/home/user/.local/bin:$PATH"
|
| 33 |
+
|
| 34 |
+
# Run the application
|
| 35 |
+
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
|
app.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, File, UploadFile, HTTPException
|
| 2 |
+
from fastapi.responses import JSONResponse
|
| 3 |
+
from pydantic import BaseModel
|
| 4 |
+
from typing import Optional
|
| 5 |
+
import base64
|
| 6 |
+
import io
|
| 7 |
+
from PIL import Image
|
| 8 |
+
import torch
|
| 9 |
+
import numpy as np
|
| 10 |
+
import os
|
| 11 |
+
|
| 12 |
+
# Existing imports
|
| 13 |
+
import numpy as np
|
| 14 |
+
import torch
|
| 15 |
+
from PIL import Image
|
| 16 |
+
import io
|
| 17 |
+
|
| 18 |
+
from utils import (
|
| 19 |
+
check_ocr_box,
|
| 20 |
+
get_yolo_model,
|
| 21 |
+
get_caption_model_processor,
|
| 22 |
+
get_som_labeled_img,
|
| 23 |
+
)
|
| 24 |
+
import torch
|
| 25 |
+
|
| 26 |
+
# yolo_model = get_yolo_model(model_path='/data/icon_detect/best.pt')
|
| 27 |
+
# caption_model_processor = get_caption_model_processor(model_name="florence2", model_name_or_path="/data/icon_caption_florence")
|
| 28 |
+
|
| 29 |
+
from ultralytics import YOLO
|
| 30 |
+
|
| 31 |
+
# if not os.path.exists("/data/icon_detect"):
|
| 32 |
+
# os.makedirs("/data/icon_detect")
|
| 33 |
+
|
| 34 |
+
try:
|
| 35 |
+
yolo_model = torch.load("weights/icon_detect/best.pt", map_location="cuda", weights_only=False)["model"]
|
| 36 |
+
yolo_model = yolo_model.to("cuda")
|
| 37 |
+
except:
|
| 38 |
+
yolo_model = torch.load("weights/icon_detect/best.pt", map_location="cpu", weights_only=False)["model"]
|
| 39 |
+
|
| 40 |
+
from transformers import AutoProcessor, AutoModelForCausalLM
|
| 41 |
+
|
| 42 |
+
processor = AutoProcessor.from_pretrained(
|
| 43 |
+
"microsoft/Florence-2-base", trust_remote_code=True
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
try:
|
| 47 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 48 |
+
"weights/icon_caption_florence",
|
| 49 |
+
torch_dtype=torch.float16,
|
| 50 |
+
trust_remote_code=True,
|
| 51 |
+
).to("cuda")
|
| 52 |
+
except:
|
| 53 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 54 |
+
"weights/icon_caption_florence",
|
| 55 |
+
torch_dtype=torch.float16,
|
| 56 |
+
trust_remote_code=True,
|
| 57 |
+
)
|
| 58 |
+
caption_model_processor = {"processor": processor, "model": model}
|
| 59 |
+
print("finish loading model!!!")
|
| 60 |
+
|
| 61 |
+
app = FastAPI()
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class ProcessResponse(BaseModel):
|
| 65 |
+
image: str # Base64 encoded image
|
| 66 |
+
parsed_content_list: str
|
| 67 |
+
label_coordinates: str
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def process(
|
| 71 |
+
image_input: Image.Image, box_threshold: float, iou_threshold: float
|
| 72 |
+
) -> ProcessResponse:
|
| 73 |
+
image_save_path = "imgs/saved_image_demo.png"
|
| 74 |
+
image_input.save(image_save_path)
|
| 75 |
+
image = Image.open(image_save_path)
|
| 76 |
+
box_overlay_ratio = image.size[0] / 3200
|
| 77 |
+
draw_bbox_config = {
|
| 78 |
+
"text_scale": 0.8 * box_overlay_ratio,
|
| 79 |
+
"text_thickness": max(int(2 * box_overlay_ratio), 1),
|
| 80 |
+
"text_padding": max(int(3 * box_overlay_ratio), 1),
|
| 81 |
+
"thickness": max(int(3 * box_overlay_ratio), 1),
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
ocr_bbox_rslt, is_goal_filtered = check_ocr_box(
|
| 85 |
+
image_save_path,
|
| 86 |
+
display_img=False,
|
| 87 |
+
output_bb_format="xyxy",
|
| 88 |
+
goal_filtering=None,
|
| 89 |
+
easyocr_args={"paragraph": False, "text_threshold": 0.9},
|
| 90 |
+
use_paddleocr=True,
|
| 91 |
+
)
|
| 92 |
+
text, ocr_bbox = ocr_bbox_rslt
|
| 93 |
+
dino_labled_img, label_coordinates, parsed_content_list = get_som_labeled_img(
|
| 94 |
+
image_save_path,
|
| 95 |
+
yolo_model,
|
| 96 |
+
BOX_TRESHOLD=box_threshold,
|
| 97 |
+
output_coord_in_ratio=True,
|
| 98 |
+
ocr_bbox=ocr_bbox,
|
| 99 |
+
draw_bbox_config=draw_bbox_config,
|
| 100 |
+
caption_model_processor=caption_model_processor,
|
| 101 |
+
ocr_text=text,
|
| 102 |
+
iou_threshold=iou_threshold,
|
| 103 |
+
)
|
| 104 |
+
image = Image.open(io.BytesIO(base64.b64decode(dino_labled_img)))
|
| 105 |
+
print("finish processing")
|
| 106 |
+
parsed_content_list_str = "\n".join(parsed_content_list)
|
| 107 |
+
|
| 108 |
+
# Encode image to base64
|
| 109 |
+
buffered = io.BytesIO()
|
| 110 |
+
image.save(buffered, format="PNG")
|
| 111 |
+
img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
|
| 112 |
+
|
| 113 |
+
return ProcessResponse(
|
| 114 |
+
image=img_str,
|
| 115 |
+
parsed_content_list=str(parsed_content_list_str),
|
| 116 |
+
label_coordinates=str(label_coordinates),
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
@app.post("/process_image", response_model=ProcessResponse)
|
| 121 |
+
async def process_image(
|
| 122 |
+
image_file: UploadFile = File(...),
|
| 123 |
+
box_threshold: float = 0.05,
|
| 124 |
+
iou_threshold: float = 0.1,
|
| 125 |
+
):
|
| 126 |
+
try:
|
| 127 |
+
contents = await image_file.read()
|
| 128 |
+
image_input = Image.open(io.BytesIO(contents)).convert("RGB")
|
| 129 |
+
except Exception as e:
|
| 130 |
+
raise HTTPException(status_code=400, detail="Invalid image file")
|
| 131 |
+
|
| 132 |
+
response = process(image_input, box_threshold, iou_threshold)
|
| 133 |
+
return response
|
download_models.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from huggingface_hub import hf_hub_download
|
| 3 |
+
import shutil
|
| 4 |
+
|
| 5 |
+
def download_models():
|
| 6 |
+
# Create directories if they don't exist
|
| 7 |
+
os.makedirs("weights/icon_detect", exist_ok=True)
|
| 8 |
+
os.makedirs("weights/icon_caption_florence", exist_ok=True)
|
| 9 |
+
|
| 10 |
+
# Define file mappings (repository path -> local path)
|
| 11 |
+
files_to_download = {
|
| 12 |
+
"icon_caption_florence/config.json": "weights/icon_caption_florence/config.json",
|
| 13 |
+
"icon_caption_florence/generation_config.json": "weights/icon_caption_florence/generation_config.json",
|
| 14 |
+
"icon_caption_florence/model.safetensors": "weights/icon_caption_florence/model.safetensors",
|
| 15 |
+
"icon_detect/best.pt": "weights/icon_detect/best.pt"
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
# Download each file
|
| 19 |
+
for repo_path, local_path in files_to_download.items():
|
| 20 |
+
if not os.path.exists(local_path):
|
| 21 |
+
print(f"Downloading {repo_path}...")
|
| 22 |
+
try:
|
| 23 |
+
downloaded_file = hf_hub_download(
|
| 24 |
+
repo_id="banao-tech/OmniParser",
|
| 25 |
+
filename=repo_path,
|
| 26 |
+
local_dir="temp"
|
| 27 |
+
)
|
| 28 |
+
# Move the file to the correct location
|
| 29 |
+
os.makedirs(os.path.dirname(local_path), exist_ok=True)
|
| 30 |
+
shutil.move(downloaded_file, local_path)
|
| 31 |
+
print(f"Successfully downloaded and moved to {local_path}")
|
| 32 |
+
except Exception as e:
|
| 33 |
+
print(f"Error downloading {repo_path}: {str(e)}")
|
| 34 |
+
|
| 35 |
+
# Clean up temp directory
|
| 36 |
+
if os.path.exists("temp"):
|
| 37 |
+
shutil.rmtree("temp")
|
| 38 |
+
|
| 39 |
+
if __name__ == "__main__":
|
| 40 |
+
download_models()
|
requirements.txt
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch==2.0.1
|
| 2 |
+
easyocr
|
| 3 |
+
torchvision
|
| 4 |
+
supervision==0.18.0
|
| 5 |
+
openai==1.3.5
|
| 6 |
+
transformers
|
| 7 |
+
ultralytics==8.1.24
|
| 8 |
+
azure-identity
|
| 9 |
+
numpy
|
| 10 |
+
opencv-python
|
| 11 |
+
opencv-python-headless
|
| 12 |
+
gradio
|
| 13 |
+
dill
|
| 14 |
+
accelerate
|
| 15 |
+
timm
|
| 16 |
+
einops==0.8.0
|
| 17 |
+
paddlepaddle
|
| 18 |
+
paddleocr
|
| 19 |
+
fastapi
|
| 20 |
+
uvicorn
|
| 21 |
+
huggingface_hub
|
utils.py
ADDED
|
@@ -0,0 +1,535 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# from ultralytics import YOLO
|
| 2 |
+
import os
|
| 3 |
+
import io
|
| 4 |
+
import base64
|
| 5 |
+
import time
|
| 6 |
+
from PIL import Image, ImageDraw, ImageFont
|
| 7 |
+
import json
|
| 8 |
+
import requests
|
| 9 |
+
# utility function
|
| 10 |
+
import os
|
| 11 |
+
from openai import AzureOpenAI
|
| 12 |
+
|
| 13 |
+
import json
|
| 14 |
+
import sys
|
| 15 |
+
import os
|
| 16 |
+
import cv2
|
| 17 |
+
import numpy as np
|
| 18 |
+
# %matplotlib inline
|
| 19 |
+
from matplotlib import pyplot as plt
|
| 20 |
+
import easyocr
|
| 21 |
+
from paddleocr import PaddleOCR
|
| 22 |
+
reader = easyocr.Reader(['en'])
|
| 23 |
+
paddle_ocr = PaddleOCR(
|
| 24 |
+
lang='en', # other lang also available
|
| 25 |
+
use_angle_cls=False,
|
| 26 |
+
use_gpu=False, # using cuda will conflict with pytorch in the same process
|
| 27 |
+
show_log=False,
|
| 28 |
+
max_batch_size=1024,
|
| 29 |
+
use_dilation=True, # improves accuracy
|
| 30 |
+
det_db_score_mode='slow', # improves accuracy
|
| 31 |
+
rec_batch_num=1024)
|
| 32 |
+
import time
|
| 33 |
+
import base64
|
| 34 |
+
|
| 35 |
+
import os
|
| 36 |
+
import ast
|
| 37 |
+
import torch
|
| 38 |
+
from typing import Tuple, List
|
| 39 |
+
from torchvision.ops import box_convert
|
| 40 |
+
import re
|
| 41 |
+
from torchvision.transforms import ToPILImage
|
| 42 |
+
import supervision as sv
|
| 43 |
+
import torchvision.transforms as T
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def get_caption_model_processor(model_name, model_name_or_path="Salesforce/blip2-opt-2.7b", device=None):
|
| 47 |
+
if not device:
|
| 48 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 49 |
+
if model_name == "blip2":
|
| 50 |
+
from transformers import Blip2Processor, Blip2ForConditionalGeneration
|
| 51 |
+
processor = Blip2Processor.from_pretrained("Salesforce/blip2-opt-2.7b")
|
| 52 |
+
if device == 'cpu':
|
| 53 |
+
model = Blip2ForConditionalGeneration.from_pretrained(
|
| 54 |
+
model_name_or_path, device_map=None, torch_dtype=torch.float32
|
| 55 |
+
)
|
| 56 |
+
else:
|
| 57 |
+
model = Blip2ForConditionalGeneration.from_pretrained(
|
| 58 |
+
model_name_or_path, device_map=None, torch_dtype=torch.float16
|
| 59 |
+
).to(device)
|
| 60 |
+
elif model_name == "florence2":
|
| 61 |
+
from transformers import AutoProcessor, AutoModelForCausalLM
|
| 62 |
+
processor = AutoProcessor.from_pretrained("microsoft/Florence-2-base", trust_remote_code=True)
|
| 63 |
+
if device == 'cpu':
|
| 64 |
+
model = AutoModelForCausalLM.from_pretrained(model_name_or_path, torch_dtype=torch.float32, trust_remote_code=True)
|
| 65 |
+
else:
|
| 66 |
+
model = AutoModelForCausalLM.from_pretrained(model_name_or_path, torch_dtype=torch.float16, trust_remote_code=True).to(device)
|
| 67 |
+
return {'model': model.to(device), 'processor': processor}
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def get_yolo_model(model_path):
|
| 71 |
+
from ultralytics import YOLO
|
| 72 |
+
# Load the model.
|
| 73 |
+
model = YOLO(model_path)
|
| 74 |
+
return model
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
@torch.inference_mode()
|
| 78 |
+
def get_parsed_content_icon(filtered_boxes, starting_idx, image_source, caption_model_processor, prompt=None, batch_size=32):
|
| 79 |
+
# Number of samples per batch, --> 256 roughly takes 23 GB of GPU memory for florence model
|
| 80 |
+
|
| 81 |
+
to_pil = ToPILImage()
|
| 82 |
+
if starting_idx:
|
| 83 |
+
non_ocr_boxes = filtered_boxes[starting_idx:]
|
| 84 |
+
else:
|
| 85 |
+
non_ocr_boxes = filtered_boxes
|
| 86 |
+
croped_pil_image = []
|
| 87 |
+
for i, coord in enumerate(non_ocr_boxes):
|
| 88 |
+
xmin, xmax = int(coord[0]*image_source.shape[1]), int(coord[2]*image_source.shape[1])
|
| 89 |
+
ymin, ymax = int(coord[1]*image_source.shape[0]), int(coord[3]*image_source.shape[0])
|
| 90 |
+
cropped_image = image_source[ymin:ymax, xmin:xmax, :]
|
| 91 |
+
croped_pil_image.append(to_pil(cropped_image))
|
| 92 |
+
|
| 93 |
+
model, processor = caption_model_processor['model'], caption_model_processor['processor']
|
| 94 |
+
if not prompt:
|
| 95 |
+
if 'florence' in model.config.name_or_path:
|
| 96 |
+
prompt = "<CAPTION>"
|
| 97 |
+
else:
|
| 98 |
+
prompt = "The image shows"
|
| 99 |
+
|
| 100 |
+
generated_texts = []
|
| 101 |
+
device = model.device
|
| 102 |
+
for i in range(0, len(croped_pil_image), batch_size):
|
| 103 |
+
start = time.time()
|
| 104 |
+
batch = croped_pil_image[i:i+batch_size]
|
| 105 |
+
if model.device.type == 'cuda':
|
| 106 |
+
inputs = processor(images=batch, text=[prompt]*len(batch), return_tensors="pt").to(device=device, dtype=torch.float16)
|
| 107 |
+
else:
|
| 108 |
+
inputs = processor(images=batch, text=[prompt]*len(batch), return_tensors="pt").to(device=device)
|
| 109 |
+
if 'florence' in model.config.name_or_path:
|
| 110 |
+
generated_ids = model.generate(input_ids=inputs["input_ids"],pixel_values=inputs["pixel_values"],max_new_tokens=100,num_beams=3, do_sample=False)
|
| 111 |
+
else:
|
| 112 |
+
generated_ids = model.generate(**inputs, max_length=100, num_beams=5, no_repeat_ngram_size=2, early_stopping=True, num_return_sequences=1) # temperature=0.01, do_sample=True,
|
| 113 |
+
generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)
|
| 114 |
+
generated_text = [gen.strip() for gen in generated_text]
|
| 115 |
+
generated_texts.extend(generated_text)
|
| 116 |
+
|
| 117 |
+
return generated_texts
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def get_parsed_content_icon_phi3v(filtered_boxes, ocr_bbox, image_source, caption_model_processor):
|
| 122 |
+
to_pil = ToPILImage()
|
| 123 |
+
if ocr_bbox:
|
| 124 |
+
non_ocr_boxes = filtered_boxes[len(ocr_bbox):]
|
| 125 |
+
else:
|
| 126 |
+
non_ocr_boxes = filtered_boxes
|
| 127 |
+
croped_pil_image = []
|
| 128 |
+
for i, coord in enumerate(non_ocr_boxes):
|
| 129 |
+
xmin, xmax = int(coord[0]*image_source.shape[1]), int(coord[2]*image_source.shape[1])
|
| 130 |
+
ymin, ymax = int(coord[1]*image_source.shape[0]), int(coord[3]*image_source.shape[0])
|
| 131 |
+
cropped_image = image_source[ymin:ymax, xmin:xmax, :]
|
| 132 |
+
croped_pil_image.append(to_pil(cropped_image))
|
| 133 |
+
|
| 134 |
+
model, processor = caption_model_processor['model'], caption_model_processor['processor']
|
| 135 |
+
device = model.device
|
| 136 |
+
messages = [{"role": "user", "content": "<|image_1|>\ndescribe the icon in one sentence"}]
|
| 137 |
+
prompt = processor.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 138 |
+
|
| 139 |
+
batch_size = 5 # Number of samples per batch
|
| 140 |
+
generated_texts = []
|
| 141 |
+
|
| 142 |
+
for i in range(0, len(croped_pil_image), batch_size):
|
| 143 |
+
images = croped_pil_image[i:i+batch_size]
|
| 144 |
+
image_inputs = [processor.image_processor(x, return_tensors="pt") for x in images]
|
| 145 |
+
inputs ={'input_ids': [], 'attention_mask': [], 'pixel_values': [], 'image_sizes': []}
|
| 146 |
+
texts = [prompt] * len(images)
|
| 147 |
+
for i, txt in enumerate(texts):
|
| 148 |
+
input = processor._convert_images_texts_to_inputs(image_inputs[i], txt, return_tensors="pt")
|
| 149 |
+
inputs['input_ids'].append(input['input_ids'])
|
| 150 |
+
inputs['attention_mask'].append(input['attention_mask'])
|
| 151 |
+
inputs['pixel_values'].append(input['pixel_values'])
|
| 152 |
+
inputs['image_sizes'].append(input['image_sizes'])
|
| 153 |
+
max_len = max([x.shape[1] for x in inputs['input_ids']])
|
| 154 |
+
for i, v in enumerate(inputs['input_ids']):
|
| 155 |
+
inputs['input_ids'][i] = torch.cat([processor.tokenizer.pad_token_id * torch.ones(1, max_len - v.shape[1], dtype=torch.long), v], dim=1)
|
| 156 |
+
inputs['attention_mask'][i] = torch.cat([torch.zeros(1, max_len - v.shape[1], dtype=torch.long), inputs['attention_mask'][i]], dim=1)
|
| 157 |
+
inputs_cat = {k: torch.concatenate(v).to(device) for k, v in inputs.items()}
|
| 158 |
+
|
| 159 |
+
generation_args = {
|
| 160 |
+
"max_new_tokens": 25,
|
| 161 |
+
"temperature": 0.01,
|
| 162 |
+
"do_sample": False,
|
| 163 |
+
}
|
| 164 |
+
generate_ids = model.generate(**inputs_cat, eos_token_id=processor.tokenizer.eos_token_id, **generation_args)
|
| 165 |
+
# # remove input tokens
|
| 166 |
+
generate_ids = generate_ids[:, inputs_cat['input_ids'].shape[1]:]
|
| 167 |
+
response = processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)
|
| 168 |
+
response = [res.strip('\n').strip() for res in response]
|
| 169 |
+
generated_texts.extend(response)
|
| 170 |
+
|
| 171 |
+
return generated_texts
|
| 172 |
+
|
| 173 |
+
def remove_overlap(boxes, iou_threshold, ocr_bbox=None):
|
| 174 |
+
assert ocr_bbox is None or isinstance(ocr_bbox, List)
|
| 175 |
+
|
| 176 |
+
def box_area(box):
|
| 177 |
+
return (box[2] - box[0]) * (box[3] - box[1])
|
| 178 |
+
|
| 179 |
+
def intersection_area(box1, box2):
|
| 180 |
+
x1 = max(box1[0], box2[0])
|
| 181 |
+
y1 = max(box1[1], box2[1])
|
| 182 |
+
x2 = min(box1[2], box2[2])
|
| 183 |
+
y2 = min(box1[3], box2[3])
|
| 184 |
+
return max(0, x2 - x1) * max(0, y2 - y1)
|
| 185 |
+
|
| 186 |
+
def IoU(box1, box2):
|
| 187 |
+
intersection = intersection_area(box1, box2)
|
| 188 |
+
union = box_area(box1) + box_area(box2) - intersection + 1e-6
|
| 189 |
+
if box_area(box1) > 0 and box_area(box2) > 0:
|
| 190 |
+
ratio1 = intersection / box_area(box1)
|
| 191 |
+
ratio2 = intersection / box_area(box2)
|
| 192 |
+
else:
|
| 193 |
+
ratio1, ratio2 = 0, 0
|
| 194 |
+
return max(intersection / union, ratio1, ratio2)
|
| 195 |
+
|
| 196 |
+
def is_inside(box1, box2):
|
| 197 |
+
# return box1[0] >= box2[0] and box1[1] >= box2[1] and box1[2] <= box2[2] and box1[3] <= box2[3]
|
| 198 |
+
intersection = intersection_area(box1, box2)
|
| 199 |
+
ratio1 = intersection / box_area(box1)
|
| 200 |
+
return ratio1 > 0.95
|
| 201 |
+
|
| 202 |
+
boxes = boxes.tolist()
|
| 203 |
+
filtered_boxes = []
|
| 204 |
+
if ocr_bbox:
|
| 205 |
+
filtered_boxes.extend(ocr_bbox)
|
| 206 |
+
# print('ocr_bbox!!!', ocr_bbox)
|
| 207 |
+
for i, box1 in enumerate(boxes):
|
| 208 |
+
# if not any(IoU(box1, box2) > iou_threshold and box_area(box1) > box_area(box2) for j, box2 in enumerate(boxes) if i != j):
|
| 209 |
+
is_valid_box = True
|
| 210 |
+
for j, box2 in enumerate(boxes):
|
| 211 |
+
# keep the smaller box
|
| 212 |
+
if i != j and IoU(box1, box2) > iou_threshold and box_area(box1) > box_area(box2):
|
| 213 |
+
is_valid_box = False
|
| 214 |
+
break
|
| 215 |
+
if is_valid_box:
|
| 216 |
+
# add the following 2 lines to include ocr bbox
|
| 217 |
+
if ocr_bbox:
|
| 218 |
+
# only add the box if it does not overlap with any ocr bbox
|
| 219 |
+
if not any(IoU(box1, box3) > iou_threshold and not is_inside(box1, box3) for k, box3 in enumerate(ocr_bbox)):
|
| 220 |
+
filtered_boxes.append(box1)
|
| 221 |
+
else:
|
| 222 |
+
filtered_boxes.append(box1)
|
| 223 |
+
return torch.tensor(filtered_boxes)
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def remove_overlap_new(boxes, iou_threshold, ocr_bbox=None):
|
| 227 |
+
'''
|
| 228 |
+
ocr_bbox format: [{'type': 'text', 'bbox':[x,y], 'interactivity':False, 'content':str }, ...]
|
| 229 |
+
boxes format: [{'type': 'icon', 'bbox':[x,y], 'interactivity':True, 'content':None }, ...]
|
| 230 |
+
|
| 231 |
+
'''
|
| 232 |
+
assert ocr_bbox is None or isinstance(ocr_bbox, List)
|
| 233 |
+
|
| 234 |
+
def box_area(box):
|
| 235 |
+
return (box[2] - box[0]) * (box[3] - box[1])
|
| 236 |
+
|
| 237 |
+
def intersection_area(box1, box2):
|
| 238 |
+
x1 = max(box1[0], box2[0])
|
| 239 |
+
y1 = max(box1[1], box2[1])
|
| 240 |
+
x2 = min(box1[2], box2[2])
|
| 241 |
+
y2 = min(box1[3], box2[3])
|
| 242 |
+
return max(0, x2 - x1) * max(0, y2 - y1)
|
| 243 |
+
|
| 244 |
+
def IoU(box1, box2):
|
| 245 |
+
intersection = intersection_area(box1, box2)
|
| 246 |
+
union = box_area(box1) + box_area(box2) - intersection + 1e-6
|
| 247 |
+
if box_area(box1) > 0 and box_area(box2) > 0:
|
| 248 |
+
ratio1 = intersection / box_area(box1)
|
| 249 |
+
ratio2 = intersection / box_area(box2)
|
| 250 |
+
else:
|
| 251 |
+
ratio1, ratio2 = 0, 0
|
| 252 |
+
return max(intersection / union, ratio1, ratio2)
|
| 253 |
+
|
| 254 |
+
def is_inside(box1, box2):
|
| 255 |
+
# return box1[0] >= box2[0] and box1[1] >= box2[1] and box1[2] <= box2[2] and box1[3] <= box2[3]
|
| 256 |
+
intersection = intersection_area(box1, box2)
|
| 257 |
+
ratio1 = intersection / box_area(box1)
|
| 258 |
+
return ratio1 > 0.80
|
| 259 |
+
|
| 260 |
+
# boxes = boxes.tolist()
|
| 261 |
+
filtered_boxes = []
|
| 262 |
+
if ocr_bbox:
|
| 263 |
+
filtered_boxes.extend(ocr_bbox)
|
| 264 |
+
# print('ocr_bbox!!!', ocr_bbox)
|
| 265 |
+
for i, box1_elem in enumerate(boxes):
|
| 266 |
+
box1 = box1_elem['bbox']
|
| 267 |
+
is_valid_box = True
|
| 268 |
+
for j, box2_elem in enumerate(boxes):
|
| 269 |
+
# keep the smaller box
|
| 270 |
+
box2 = box2_elem['bbox']
|
| 271 |
+
if i != j and IoU(box1, box2) > iou_threshold and box_area(box1) > box_area(box2):
|
| 272 |
+
is_valid_box = False
|
| 273 |
+
break
|
| 274 |
+
if is_valid_box:
|
| 275 |
+
# add the following 2 lines to include ocr bbox
|
| 276 |
+
if ocr_bbox:
|
| 277 |
+
# keep yolo boxes + prioritize ocr label
|
| 278 |
+
box_added = False
|
| 279 |
+
for box3_elem in ocr_bbox:
|
| 280 |
+
if not box_added:
|
| 281 |
+
box3 = box3_elem['bbox']
|
| 282 |
+
if is_inside(box3, box1): # ocr inside icon
|
| 283 |
+
# box_added = True
|
| 284 |
+
# delete the box3_elem from ocr_bbox
|
| 285 |
+
try:
|
| 286 |
+
filtered_boxes.append({'type': 'text', 'bbox': box1_elem['bbox'], 'interactivity': True, 'content': box3_elem['content']})
|
| 287 |
+
filtered_boxes.remove(box3_elem)
|
| 288 |
+
# print('remove ocr bbox:', box3_elem)
|
| 289 |
+
except:
|
| 290 |
+
continue
|
| 291 |
+
# break
|
| 292 |
+
elif is_inside(box1, box3): # icon inside ocr
|
| 293 |
+
box_added = True
|
| 294 |
+
# try:
|
| 295 |
+
# filtered_boxes.append({'type': 'icon', 'bbox': box1_elem['bbox'], 'interactivity': True, 'content': None})
|
| 296 |
+
# filtered_boxes.remove(box3_elem)
|
| 297 |
+
# except:
|
| 298 |
+
# continue
|
| 299 |
+
break
|
| 300 |
+
else:
|
| 301 |
+
continue
|
| 302 |
+
if not box_added:
|
| 303 |
+
filtered_boxes.append({'type': 'icon', 'bbox': box1_elem['bbox'], 'interactivity': True, 'content': None})
|
| 304 |
+
|
| 305 |
+
else:
|
| 306 |
+
filtered_boxes.append(box1)
|
| 307 |
+
return filtered_boxes # torch.tensor(filtered_boxes)
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
def load_image(image_path: str) -> Tuple[np.array, torch.Tensor]:
|
| 311 |
+
transform = T.Compose(
|
| 312 |
+
[
|
| 313 |
+
T.RandomResize([800], max_size=1333),
|
| 314 |
+
T.ToTensor(),
|
| 315 |
+
T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
|
| 316 |
+
]
|
| 317 |
+
)
|
| 318 |
+
image_source = Image.open(image_path).convert("RGB")
|
| 319 |
+
image = np.asarray(image_source)
|
| 320 |
+
image_transformed, _ = transform(image_source, None)
|
| 321 |
+
return image, image_transformed
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
def annotate(image_source: np.ndarray, boxes: torch.Tensor, logits: torch.Tensor, phrases: List[str], text_scale: float,
|
| 325 |
+
text_padding=5, text_thickness=2, thickness=3) -> np.ndarray:
|
| 326 |
+
"""
|
| 327 |
+
This function annotates an image with bounding boxes and labels.
|
| 328 |
+
|
| 329 |
+
Parameters:
|
| 330 |
+
image_source (np.ndarray): The source image to be annotated.
|
| 331 |
+
boxes (torch.Tensor): A tensor containing bounding box coordinates. in cxcywh format, pixel scale
|
| 332 |
+
logits (torch.Tensor): A tensor containing confidence scores for each bounding box.
|
| 333 |
+
phrases (List[str]): A list of labels for each bounding box.
|
| 334 |
+
text_scale (float): The scale of the text to be displayed. 0.8 for mobile/web, 0.3 for desktop # 0.4 for mind2web
|
| 335 |
+
|
| 336 |
+
Returns:
|
| 337 |
+
np.ndarray: The annotated image.
|
| 338 |
+
"""
|
| 339 |
+
h, w, _ = image_source.shape
|
| 340 |
+
boxes = boxes * torch.Tensor([w, h, w, h])
|
| 341 |
+
xyxy = box_convert(boxes=boxes, in_fmt="cxcywh", out_fmt="xyxy").numpy()
|
| 342 |
+
xywh = box_convert(boxes=boxes, in_fmt="cxcywh", out_fmt="xywh").numpy()
|
| 343 |
+
detections = sv.Detections(xyxy=xyxy)
|
| 344 |
+
|
| 345 |
+
labels = [f"{phrase}" for phrase in range(boxes.shape[0])]
|
| 346 |
+
|
| 347 |
+
from util.box_annotator import BoxAnnotator
|
| 348 |
+
box_annotator = BoxAnnotator(text_scale=text_scale, text_padding=text_padding,text_thickness=text_thickness,thickness=thickness) # 0.8 for mobile/web, 0.3 for desktop # 0.4 for mind2web
|
| 349 |
+
annotated_frame = image_source.copy()
|
| 350 |
+
annotated_frame = box_annotator.annotate(scene=annotated_frame, detections=detections, labels=labels, image_size=(w,h))
|
| 351 |
+
|
| 352 |
+
label_coordinates = {f"{phrase}": v for phrase, v in zip(phrases, xywh)}
|
| 353 |
+
return annotated_frame, label_coordinates
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
def predict(model, image, caption, box_threshold, text_threshold):
|
| 357 |
+
""" Use huggingface model to replace the original model
|
| 358 |
+
"""
|
| 359 |
+
model, processor = model['model'], model['processor']
|
| 360 |
+
device = model.device
|
| 361 |
+
|
| 362 |
+
inputs = processor(images=image, text=caption, return_tensors="pt").to(device)
|
| 363 |
+
with torch.no_grad():
|
| 364 |
+
outputs = model(**inputs)
|
| 365 |
+
|
| 366 |
+
results = processor.post_process_grounded_object_detection(
|
| 367 |
+
outputs,
|
| 368 |
+
inputs.input_ids,
|
| 369 |
+
box_threshold=box_threshold, # 0.4,
|
| 370 |
+
text_threshold=text_threshold, # 0.3,
|
| 371 |
+
target_sizes=[image.size[::-1]]
|
| 372 |
+
)[0]
|
| 373 |
+
boxes, logits, phrases = results["boxes"], results["scores"], results["labels"]
|
| 374 |
+
return boxes, logits, phrases
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
def predict_yolo(model, image_path, box_threshold, imgsz, scale_img, iou_threshold=0.7):
|
| 378 |
+
""" Use huggingface model to replace the original model
|
| 379 |
+
"""
|
| 380 |
+
# model = model['model']
|
| 381 |
+
if scale_img:
|
| 382 |
+
result = model.predict(
|
| 383 |
+
source=image_path,
|
| 384 |
+
conf=box_threshold,
|
| 385 |
+
imgsz=imgsz,
|
| 386 |
+
iou=iou_threshold, # default 0.7
|
| 387 |
+
)
|
| 388 |
+
else:
|
| 389 |
+
result = model.predict(
|
| 390 |
+
source=image_path,
|
| 391 |
+
conf=box_threshold,
|
| 392 |
+
iou=iou_threshold, # default 0.7
|
| 393 |
+
)
|
| 394 |
+
boxes = result[0].boxes.xyxy#.tolist() # in pixel space
|
| 395 |
+
conf = result[0].boxes.conf
|
| 396 |
+
phrases = [str(i) for i in range(len(boxes))]
|
| 397 |
+
|
| 398 |
+
return boxes, conf, phrases
|
| 399 |
+
|
| 400 |
+
|
| 401 |
+
def get_som_labeled_img(img_path, model=None, BOX_TRESHOLD = 0.01, output_coord_in_ratio=False, ocr_bbox=None, text_scale=0.4, text_padding=5, draw_bbox_config=None, caption_model_processor=None, ocr_text=[], use_local_semantics=True, iou_threshold=0.9,prompt=None, scale_img=False, imgsz=None, batch_size=None):
|
| 402 |
+
""" ocr_bbox: list of xyxy format bbox
|
| 403 |
+
"""
|
| 404 |
+
image_source = Image.open(img_path).convert("RGB")
|
| 405 |
+
w, h = image_source.size
|
| 406 |
+
if not imgsz:
|
| 407 |
+
imgsz = (h, w)
|
| 408 |
+
# print('image size:', w, h)
|
| 409 |
+
xyxy, logits, phrases = predict_yolo(model=model, image_path=img_path, box_threshold=BOX_TRESHOLD, imgsz=imgsz, scale_img=scale_img, iou_threshold=0.1)
|
| 410 |
+
xyxy = xyxy / torch.Tensor([w, h, w, h]).to(xyxy.device)
|
| 411 |
+
image_source = np.asarray(image_source)
|
| 412 |
+
phrases = [str(i) for i in range(len(phrases))]
|
| 413 |
+
|
| 414 |
+
# annotate the image with labels
|
| 415 |
+
h, w, _ = image_source.shape
|
| 416 |
+
if ocr_bbox:
|
| 417 |
+
ocr_bbox = torch.tensor(ocr_bbox) / torch.Tensor([w, h, w, h])
|
| 418 |
+
ocr_bbox=ocr_bbox.tolist()
|
| 419 |
+
else:
|
| 420 |
+
print('no ocr bbox!!!')
|
| 421 |
+
ocr_bbox = None
|
| 422 |
+
# filtered_boxes = remove_overlap(boxes=xyxy, iou_threshold=iou_threshold, ocr_bbox=ocr_bbox)
|
| 423 |
+
# starting_idx = len(ocr_bbox)
|
| 424 |
+
# print('len(filtered_boxes):', len(filtered_boxes), starting_idx)
|
| 425 |
+
|
| 426 |
+
ocr_bbox_elem = [{'type': 'text', 'bbox':box, 'interactivity':False, 'content':txt} for box, txt in zip(ocr_bbox, ocr_text)]
|
| 427 |
+
xyxy_elem = [{'type': 'icon', 'bbox':box, 'interactivity':True, 'content':None} for box in xyxy.tolist()]
|
| 428 |
+
filtered_boxes = remove_overlap_new(boxes=xyxy_elem, iou_threshold=iou_threshold, ocr_bbox=ocr_bbox_elem)
|
| 429 |
+
|
| 430 |
+
# sort the filtered_boxes so that the one with 'content': None is at the end, and get the index of the first 'content': None
|
| 431 |
+
filtered_boxes_elem = sorted(filtered_boxes, key=lambda x: x['content'] is None)
|
| 432 |
+
# get the index of the first 'content': None
|
| 433 |
+
starting_idx = next((i for i, box in enumerate(filtered_boxes_elem) if box['content'] is None), -1)
|
| 434 |
+
filtered_boxes = torch.tensor([box['bbox'] for box in filtered_boxes_elem])
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
# get parsed icon local semantics
|
| 438 |
+
if use_local_semantics:
|
| 439 |
+
caption_model = caption_model_processor['model']
|
| 440 |
+
if 'phi3_v' in caption_model.config.model_type:
|
| 441 |
+
parsed_content_icon = get_parsed_content_icon_phi3v(filtered_boxes, ocr_bbox, image_source, caption_model_processor)
|
| 442 |
+
else:
|
| 443 |
+
parsed_content_icon = get_parsed_content_icon(filtered_boxes, starting_idx, image_source, caption_model_processor, prompt=prompt,batch_size=batch_size)
|
| 444 |
+
ocr_text = [f"Text Box ID {i}: {txt}" for i, txt in enumerate(ocr_text)]
|
| 445 |
+
icon_start = len(ocr_text)
|
| 446 |
+
parsed_content_icon_ls = []
|
| 447 |
+
# fill the filtered_boxes_elem None content with parsed_content_icon in order
|
| 448 |
+
for i, box in enumerate(filtered_boxes_elem):
|
| 449 |
+
if box['content'] is None:
|
| 450 |
+
box['content'] = parsed_content_icon.pop(0)
|
| 451 |
+
for i, txt in enumerate(parsed_content_icon):
|
| 452 |
+
parsed_content_icon_ls.append(f"Icon Box ID {str(i+icon_start)}: {txt}")
|
| 453 |
+
parsed_content_merged = ocr_text + parsed_content_icon_ls
|
| 454 |
+
else:
|
| 455 |
+
ocr_text = [f"Text Box ID {i}: {txt}" for i, txt in enumerate(ocr_text)]
|
| 456 |
+
parsed_content_merged = ocr_text
|
| 457 |
+
|
| 458 |
+
filtered_boxes = box_convert(boxes=filtered_boxes, in_fmt="xyxy", out_fmt="cxcywh")
|
| 459 |
+
|
| 460 |
+
phrases = [i for i in range(len(filtered_boxes))]
|
| 461 |
+
|
| 462 |
+
# draw boxes
|
| 463 |
+
if draw_bbox_config:
|
| 464 |
+
annotated_frame, label_coordinates = annotate(image_source=image_source, boxes=filtered_boxes, logits=logits, phrases=phrases, **draw_bbox_config)
|
| 465 |
+
else:
|
| 466 |
+
annotated_frame, label_coordinates = annotate(image_source=image_source, boxes=filtered_boxes, logits=logits, phrases=phrases, text_scale=text_scale, text_padding=text_padding)
|
| 467 |
+
|
| 468 |
+
pil_img = Image.fromarray(annotated_frame)
|
| 469 |
+
buffered = io.BytesIO()
|
| 470 |
+
pil_img.save(buffered, format="PNG")
|
| 471 |
+
encoded_image = base64.b64encode(buffered.getvalue()).decode('ascii')
|
| 472 |
+
if output_coord_in_ratio:
|
| 473 |
+
# h, w, _ = image_source.shape
|
| 474 |
+
label_coordinates = {k: [v[0]/w, v[1]/h, v[2]/w, v[3]/h] for k, v in label_coordinates.items()}
|
| 475 |
+
assert w == annotated_frame.shape[1] and h == annotated_frame.shape[0]
|
| 476 |
+
|
| 477 |
+
return encoded_image, label_coordinates, filtered_boxes_elem
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
def get_xywh(input):
|
| 481 |
+
x, y, w, h = input[0][0], input[0][1], input[2][0] - input[0][0], input[2][1] - input[0][1]
|
| 482 |
+
x, y, w, h = int(x), int(y), int(w), int(h)
|
| 483 |
+
return x, y, w, h
|
| 484 |
+
|
| 485 |
+
def get_xyxy(input):
|
| 486 |
+
x, y, xp, yp = input[0][0], input[0][1], input[2][0], input[2][1]
|
| 487 |
+
x, y, xp, yp = int(x), int(y), int(xp), int(yp)
|
| 488 |
+
return x, y, xp, yp
|
| 489 |
+
|
| 490 |
+
def get_xywh_yolo(input):
|
| 491 |
+
x, y, w, h = input[0], input[1], input[2] - input[0], input[3] - input[1]
|
| 492 |
+
x, y, w, h = int(x), int(y), int(w), int(h)
|
| 493 |
+
return x, y, w, h
|
| 494 |
+
|
| 495 |
+
|
| 496 |
+
|
| 497 |
+
def check_ocr_box(image_path, display_img = True, output_bb_format='xywh', goal_filtering=None, easyocr_args=None, use_paddleocr=False):
|
| 498 |
+
if use_paddleocr:
|
| 499 |
+
if easyocr_args is None:
|
| 500 |
+
text_threshold = 0.5
|
| 501 |
+
else:
|
| 502 |
+
text_threshold = easyocr_args['text_threshold']
|
| 503 |
+
result = paddle_ocr.ocr(image_path, cls=False)[0]
|
| 504 |
+
conf = [item[1] for item in result]
|
| 505 |
+
coord = [item[0] for item in result if item[1][1] > text_threshold]
|
| 506 |
+
text = [item[1][0] for item in result if item[1][1] > text_threshold]
|
| 507 |
+
else: # EasyOCR
|
| 508 |
+
if easyocr_args is None:
|
| 509 |
+
easyocr_args = {}
|
| 510 |
+
result = reader.readtext(image_path, **easyocr_args)
|
| 511 |
+
# print('goal filtering pred:', result[-5:])
|
| 512 |
+
coord = [item[0] for item in result]
|
| 513 |
+
text = [item[1] for item in result]
|
| 514 |
+
# read the image using cv2
|
| 515 |
+
if display_img:
|
| 516 |
+
opencv_img = cv2.imread(image_path)
|
| 517 |
+
opencv_img = cv2.cvtColor(opencv_img, cv2.COLOR_RGB2BGR)
|
| 518 |
+
bb = []
|
| 519 |
+
for item in coord:
|
| 520 |
+
x, y, a, b = get_xywh(item)
|
| 521 |
+
# print(x, y, a, b)
|
| 522 |
+
bb.append((x, y, a, b))
|
| 523 |
+
cv2.rectangle(opencv_img, (x, y), (x+a, y+b), (0, 255, 0), 2)
|
| 524 |
+
|
| 525 |
+
# Display the image
|
| 526 |
+
plt.imshow(opencv_img)
|
| 527 |
+
else:
|
| 528 |
+
if output_bb_format == 'xywh':
|
| 529 |
+
bb = [get_xywh(item) for item in coord]
|
| 530 |
+
elif output_bb_format == 'xyxy':
|
| 531 |
+
bb = [get_xyxy(item) for item in coord]
|
| 532 |
+
# print('bounding box!!!', bb)
|
| 533 |
+
return (text, bb), goal_filtering
|
| 534 |
+
|
| 535 |
+
|