Spaces:
Sleeping
Sleeping
Download backend/src/python/ocr_engine.py from simhaa-hat/generated-bill: direct link, hf CLI and curl.
- Browser
- Download file 5.21 kB
-
https://huggingface.co/spaces/simhaa-hat/generated-bill/resolve/main/backend/src/python/ocr_engine.py
- Command line
-
hf download hf://spaces/simhaa-hat/generated-bill/backend/src/python/ocr_engine.py
-
curl -L -o ocr_engine.py https://huggingface.co/spaces/simhaa-hat/generated-bill/resolve/main/backend/src/python/ocr_engine.py
5.21 kB
| import sys | |
| import json | |
| import base64 | |
| import cv2 | |
| import numpy as np | |
| import easyocr | |
| import logging | |
| import traceback | |
| # Configure logging | |
| logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') | |
| logger = logging.getLogger(__name__) | |
| # Global reader instance | |
| _reader = None | |
| def get_reader(): | |
| global _reader | |
| if _reader is None: | |
| # Initialize with English | |
| _reader = easyocr.Reader(['en'], gpu=False) | |
| return _reader | |
| def process_image(image_data): | |
| try: | |
| reader = get_reader() | |
| # Decode base64 image | |
| if ',' in image_data: | |
| image_data = image_data.split(',')[1] | |
| image_bytes = base64.b64decode(image_data) | |
| nparr = np.frombuffer(image_bytes, np.uint8) | |
| img = cv2.imdecode(nparr, cv2.IMREAD_COLOR) | |
| if img is None: | |
| raise ValueError("Could not decode image") | |
| # Run OCR | |
| result = reader.readtext(img) | |
| extracted_text = [] | |
| structured_data = [] | |
| # Process EasyOCR results | |
| for item in result: | |
| bbox, text, confidence = item | |
| # Convert bbox points to standard list of lists | |
| box = [[float(pt[0]), float(pt[1])] for pt in bbox] | |
| extracted_text.append(text) | |
| structured_data.append({ | |
| "text": text, | |
| "confidence": float(confidence), | |
| "box": box | |
| }) | |
| # Reconstruct lines based on Y-coordinates | |
| lines = [] | |
| if structured_data: | |
| def get_y_min(item): | |
| box = item['box'] | |
| return box[0][1] | |
| structured_data.sort(key=get_y_min) | |
| current_line = [] | |
| current_y = -1 | |
| y_threshold = 20 # Pixel threshold for same line | |
| for item in structured_data: | |
| box = item['box'] | |
| y_center = (box[0][1] + box[2][1]) / 2 | |
| if current_y == -1: | |
| current_y = y_center | |
| current_line.append(item) | |
| elif abs(y_center - current_y) < y_threshold: | |
| current_line.append(item) | |
| else: | |
| # Sort current line by X-coordinate | |
| def get_x_min(item): | |
| b = item['box'] | |
| return b[0][0] | |
| current_line.sort(key=get_x_min) | |
| lines.append(current_line) | |
| current_line = [item] | |
| current_y = y_center | |
| if current_line: | |
| def get_x_min(item): | |
| b = item['box'] | |
| return b[0][0] | |
| current_line.sort(key=get_x_min) | |
| lines.append(current_line) | |
| # Build full text from lines with enhancement (User request) | |
| import re | |
| final_lines = [] | |
| for line in lines: | |
| line_text = " ".join([str(item['text']) for item in line]) | |
| # 1. Filter out "thank you" and "visit" phrases | |
| junk_keywords = ["thank you", "visit again", "thanks", "welcome", "have a nice day", "visit us", "come again"] | |
| if any(k in line_text.lower() for k in junk_keywords): | |
| continue | |
| # 2. Remove any numbers (User request: "dont add any number") | |
| line_text = re.sub(r'\d+', '', line_text) | |
| # Clean up extra whitespace and punctuation | |
| line_text = re.sub(r'\s+', ' ', line_text).strip() | |
| # Skip empty lines or lines with no alphanumeric characters | |
| if line_text and any(c.isalnum() for c in line_text): | |
| final_lines.append(line_text) | |
| full_text = "\n".join(final_lines) | |
| engine_type = "easyocr" # Define engine_type as requested | |
| return { | |
| "success": True, | |
| "text": full_text, | |
| "data": structured_data, | |
| "engine": engine_type | |
| } | |
| except Exception as e: | |
| logger.error(f"OCR processing failed: {str(e)}") | |
| logger.error(traceback.format_exc()) | |
| return { | |
| "success": False, | |
| "error": str(e) | |
| } | |
| if __name__ == "__main__": | |
| try: | |
| # Read input from stdin | |
| input_data = sys.stdin.read() | |
| if not input_data: | |
| print(json.dumps({"success": False, "error": "No input data received"})) | |
| sys.exit(1) | |
| try: | |
| request = json.loads(input_data) | |
| except json.JSONDecodeError: | |
| print(json.dumps({"success": False, "error": "Invalid JSON input"})) | |
| sys.exit(1) | |
| image_base64 = request.get("imageBase64") | |
| if not image_base64: | |
| print(json.dumps({"success": False, "error": "imageBase64 is required"})) | |
| sys.exit(1) | |
| result = process_image(image_base64) | |
| print(json.dumps(result)) | |
| except Exception as e: | |
| print(json.dumps({"success": False, "error": f"Unexpected error: {str(e)}"})) | |
| sys.exit(1) | |