Spaces:
Sleeping
Sleeping
File size: 3,458 Bytes
2713e50 5ff8f69 2713e50 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 | import os
from paddleocr import PaddleOCR
import cv2
# OCR model instance
ocr_model = None
def load_ocr_model():
"""
Load PaddleOCR once and reuse.
Supports English + Hindi text detection.
"""
global ocr_model
if ocr_model is None:
print("[OCR] Loading PaddleOCR...")
ocr_model = PaddleOCR(
use_angle_cls=True,
lang="en",
use_gpu=False,
show_log=False
)
print("[OCR] Model loaded successfully")
return ocr_model
def extract_text(image_path: str):
"""
Extract text blocks from image.
Returns:
[
{
text,
confidence,
x,
y,
w,
h
}
]
"""
model = load_ocr_model()
result = model.ocr(image_path)
text_blocks = []
if result is None:
return text_blocks
for line in result[0]:
box = line[0]
text = line[1][0]
confidence = float(line[1][1])
# Skip low confidence detections
if confidence < 0.50:
continue
x_coords = [int(point[0]) for point in box]
y_coords = [int(point[1]) for point in box]
x = min(x_coords)
y = min(y_coords)
w = max(x_coords) - x
h = max(y_coords) - y
text_blocks.append(
{
"text": text,
"confidence": round(confidence, 3),
"x": x,
"y": y,
"w": w,
"h": h,
}
)
print(f"[OCR] Found {len(text_blocks)} text blocks")
return text_blocks
def save_ocr_debug(image_path, text_blocks, output_dir=None):
"""
Draw OCR boxes on image for verification.
"""
if output_dir is None:
output_dir = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
"outputs"
)
os.makedirs(output_dir, exist_ok=True)
image = cv2.imread(image_path)
for block in text_blocks:
x = block["x"]
y = block["y"]
w = block["w"]
h = block["h"]
cv2.rectangle(
image,
(x, y),
(x + w, y + h),
(0, 255, 0),
2
)
cv2.putText(
image,
block["text"],
(x, y - 5),
cv2.FONT_HERSHEY_SIMPLEX,
0.5,
(0, 255, 0),
1
)
output_path = os.path.join(
output_dir,
"ocr_debug.jpg"
)
cv2.imwrite(output_path, image)
print(f"[OCR] Saved debug image -> {output_path}")
return output_path
if __name__ == "__main__":
BACKEND_DIR = os.path.dirname(
os.path.abspath(__file__)
)
TEST_IMAGE = os.path.join(
BACKEND_DIR,
"test_images",
"logo_company.jpg"
)
if not os.path.exists(TEST_IMAGE):
print(f"ERROR: Missing image -> {TEST_IMAGE}")
exit(1)
print("=" * 50)
print("Testing PaddleOCR")
print("=" * 50)
text_blocks = extract_text(TEST_IMAGE)
print("\nDetected Text:")
for block in text_blocks:
print(
f"{block['text']} | "
f"conf={block['confidence']} | "
f"({block['x']},{block['y']})"
)
save_ocr_debug(TEST_IMAGE, text_blocks)
print("=" * 50)
print("Open outputs/ocr_debug.jpg")
print("=" * 50) |