Spaces:
Runtime error
Runtime error
GitHub Copilot commited on
Commit ·
f6e608d
1
Parent(s): 1d1958d
Feature: Add EasyOCR pipeline for screenshot text extraction
Browse files- logos/ocr_pipeline.py +174 -0
- requirements.txt +1 -0
logos/ocr_pipeline.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
ocr_pipeline.py - LOGOS OCR Pipeline
|
| 3 |
+
Extract text from architectural diagrams and UI screenshots using EasyOCR.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
import json
|
| 8 |
+
from typing import List, Dict, Optional
|
| 9 |
+
from dataclasses import dataclass, asdict
|
| 10 |
+
|
| 11 |
+
try:
|
| 12 |
+
import easyocr
|
| 13 |
+
EASYOCR_AVAILABLE = True
|
| 14 |
+
except ImportError:
|
| 15 |
+
EASYOCR_AVAILABLE = False
|
| 16 |
+
print("[OCR] EasyOCR not available. Install with: pip install easyocr")
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@dataclass
|
| 20 |
+
class TextBlock:
|
| 21 |
+
"""A single detected text region."""
|
| 22 |
+
text: str
|
| 23 |
+
confidence: float
|
| 24 |
+
bbox: Optional[List[List[int]]] = None # [[x1,y1], [x2,y2], [x3,y3], [x4,y4]]
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@dataclass
|
| 28 |
+
class OCRResult:
|
| 29 |
+
"""OCR result for a single image."""
|
| 30 |
+
filename: str
|
| 31 |
+
path: str
|
| 32 |
+
text_blocks: List[TextBlock]
|
| 33 |
+
full_text: str
|
| 34 |
+
word_count: int
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class LOGOSOCRPipeline:
|
| 38 |
+
"""
|
| 39 |
+
OCR pipeline for extracting text from LOGOS protocol screenshots.
|
| 40 |
+
Uses EasyOCR for reliable text detection without GPU requirement.
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
def __init__(self, languages: List[str] = None, gpu: bool = False):
|
| 44 |
+
"""
|
| 45 |
+
Initialize the OCR pipeline.
|
| 46 |
+
|
| 47 |
+
Args:
|
| 48 |
+
languages: List of language codes (default: ['en'])
|
| 49 |
+
gpu: Whether to use GPU acceleration
|
| 50 |
+
"""
|
| 51 |
+
if not EASYOCR_AVAILABLE:
|
| 52 |
+
raise ImportError("EasyOCR is required. Install with: pip install easyocr")
|
| 53 |
+
|
| 54 |
+
self.languages = languages or ['en']
|
| 55 |
+
self.reader = easyocr.Reader(self.languages, gpu=gpu)
|
| 56 |
+
print(f"[OCR] Initialized EasyOCR with languages: {self.languages}")
|
| 57 |
+
|
| 58 |
+
def extract_text(self, image_path: str, detail: bool = True) -> OCRResult:
|
| 59 |
+
"""
|
| 60 |
+
Extract text from a single image.
|
| 61 |
+
|
| 62 |
+
Args:
|
| 63 |
+
image_path: Path to the image file
|
| 64 |
+
detail: If True, include bounding boxes
|
| 65 |
+
|
| 66 |
+
Returns:
|
| 67 |
+
OCRResult with extracted text blocks
|
| 68 |
+
"""
|
| 69 |
+
if not os.path.exists(image_path):
|
| 70 |
+
raise FileNotFoundError(f"Image not found: {image_path}")
|
| 71 |
+
|
| 72 |
+
# Run OCR
|
| 73 |
+
results = self.reader.readtext(image_path)
|
| 74 |
+
|
| 75 |
+
# Parse results
|
| 76 |
+
text_blocks = []
|
| 77 |
+
for bbox, text, confidence in results:
|
| 78 |
+
block = TextBlock(
|
| 79 |
+
text=text,
|
| 80 |
+
confidence=round(confidence, 4),
|
| 81 |
+
bbox=bbox if detail else None
|
| 82 |
+
)
|
| 83 |
+
text_blocks.append(block)
|
| 84 |
+
|
| 85 |
+
# Build full text (sorted by Y position for reading order)
|
| 86 |
+
sorted_blocks = sorted(text_blocks, key=lambda b: b.bbox[0][1] if b.bbox else 0)
|
| 87 |
+
full_text = " ".join([b.text for b in sorted_blocks])
|
| 88 |
+
|
| 89 |
+
return OCRResult(
|
| 90 |
+
filename=os.path.basename(image_path),
|
| 91 |
+
path=image_path,
|
| 92 |
+
text_blocks=text_blocks,
|
| 93 |
+
full_text=full_text,
|
| 94 |
+
word_count=len(full_text.split())
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
def batch_process(self, folder: str, extensions: List[str] = None) -> List[OCRResult]:
|
| 98 |
+
"""
|
| 99 |
+
Process all images in a folder.
|
| 100 |
+
|
| 101 |
+
Args:
|
| 102 |
+
folder: Path to folder containing images
|
| 103 |
+
extensions: File extensions to include (default: ['.png', '.jpg', '.jpeg'])
|
| 104 |
+
|
| 105 |
+
Returns:
|
| 106 |
+
List of OCRResult objects
|
| 107 |
+
"""
|
| 108 |
+
if extensions is None:
|
| 109 |
+
extensions = ['.png', '.jpg', '.jpeg', '.bmp', '.webp']
|
| 110 |
+
|
| 111 |
+
results = []
|
| 112 |
+
files = sorted([f for f in os.listdir(folder)
|
| 113 |
+
if os.path.splitext(f)[1].lower() in extensions])
|
| 114 |
+
|
| 115 |
+
print(f"[OCR] Processing {len(files)} images from {folder}")
|
| 116 |
+
|
| 117 |
+
for i, filename in enumerate(files):
|
| 118 |
+
path = os.path.join(folder, filename)
|
| 119 |
+
try:
|
| 120 |
+
result = self.extract_text(path)
|
| 121 |
+
results.append(result)
|
| 122 |
+
print(f"[OCR] [{i+1}/{len(files)}] {filename}: {result.word_count} words")
|
| 123 |
+
except Exception as e:
|
| 124 |
+
print(f"[OCR] Error processing {filename}: {e}")
|
| 125 |
+
|
| 126 |
+
return results
|
| 127 |
+
|
| 128 |
+
def export_to_json(self, results: List[OCRResult], output_path: str):
|
| 129 |
+
"""Export OCR results to JSON file."""
|
| 130 |
+
data = [asdict(r) for r in results]
|
| 131 |
+
with open(output_path, 'w', encoding='utf-8') as f:
|
| 132 |
+
json.dump(data, f, indent=2, ensure_ascii=False)
|
| 133 |
+
print(f"[OCR] Exported {len(results)} results to {output_path}")
|
| 134 |
+
|
| 135 |
+
def search(self, results: List[OCRResult], query: str) -> List[OCRResult]:
|
| 136 |
+
"""Search OCR results for a query string."""
|
| 137 |
+
query_lower = query.lower()
|
| 138 |
+
return [r for r in results if query_lower in r.full_text.lower()]
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def build_knowledge_base(folder: str, output_path: str = "logos_knowledge_base.json"):
|
| 142 |
+
"""
|
| 143 |
+
Build a knowledge base from all screenshots in a folder.
|
| 144 |
+
|
| 145 |
+
Args:
|
| 146 |
+
folder: Path to LOGOS Screenshots folder
|
| 147 |
+
output_path: Path for output JSON file
|
| 148 |
+
"""
|
| 149 |
+
pipeline = LOGOSOCRPipeline(gpu=False)
|
| 150 |
+
results = pipeline.batch_process(folder)
|
| 151 |
+
pipeline.export_to_json(results, output_path)
|
| 152 |
+
|
| 153 |
+
# Summary
|
| 154 |
+
total_words = sum(r.word_count for r in results)
|
| 155 |
+
print(f"\n[OCR] Knowledge Base Summary:")
|
| 156 |
+
print(f" - Images processed: {len(results)}")
|
| 157 |
+
print(f" - Total words extracted: {total_words}")
|
| 158 |
+
print(f" - Output file: {output_path}")
|
| 159 |
+
|
| 160 |
+
return results
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
# CLI for standalone usage
|
| 164 |
+
if __name__ == "__main__":
|
| 165 |
+
import sys
|
| 166 |
+
|
| 167 |
+
if len(sys.argv) < 2:
|
| 168 |
+
print("Usage: python ocr_pipeline.py <folder_path> [output.json]")
|
| 169 |
+
sys.exit(1)
|
| 170 |
+
|
| 171 |
+
folder = sys.argv[1]
|
| 172 |
+
output = sys.argv[2] if len(sys.argv) > 2 else "logos_knowledge_base.json"
|
| 173 |
+
|
| 174 |
+
build_knowledge_base(folder, output)
|
requirements.txt
CHANGED
|
@@ -6,3 +6,4 @@ gradio==4.20.0
|
|
| 6 |
huggingface_hub<0.21.0
|
| 7 |
plotly
|
| 8 |
sympy
|
|
|
|
|
|
| 6 |
huggingface_hub<0.21.0
|
| 7 |
plotly
|
| 8 |
sympy
|
| 9 |
+
easyocr
|