Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -9,18 +9,18 @@ import pytz
|
|
| 9 |
import numpy as np
|
| 10 |
import logging
|
| 11 |
|
| 12 |
-
# Set up logging
|
| 13 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 14 |
|
| 15 |
-
# Configure Tesseract path
|
| 16 |
try:
|
| 17 |
-
pytesseract.pytesseract.tesseract_cmd = '/usr/bin/tesseract' #
|
| 18 |
pytesseract.get_tesseract_version() # Test Tesseract availability
|
| 19 |
logging.info("Tesseract is available")
|
| 20 |
except Exception as e:
|
| 21 |
logging.error(f"Tesseract not found or misconfigured: {str(e)}")
|
| 22 |
|
| 23 |
-
# Preprocessing
|
| 24 |
def preprocess_image(img_cv):
|
| 25 |
"""Preprocess image for OCR: enhance contrast, reduce noise, and apply adaptive thresholding."""
|
| 26 |
try:
|
|
@@ -40,33 +40,33 @@ def preprocess_image(img_cv):
|
|
| 40 |
logging.error(f"Image preprocessing failed: {str(e)}")
|
| 41 |
return img_cv
|
| 42 |
|
| 43 |
-
# Function to extract weight using OCR
|
| 44 |
def extract_weight(img):
|
| 45 |
-
"""Extract weight from image using Tesseract OCR
|
| 46 |
try:
|
| 47 |
if img is None:
|
| 48 |
logging.error("No image provided for OCR")
|
| 49 |
return "Not detected", 0.0, None
|
| 50 |
|
| 51 |
-
# Convert PIL image to OpenCV format
|
| 52 |
img_cv = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
|
| 53 |
-
# Preprocess the image
|
| 54 |
processed_img = preprocess_image(img_cv)
|
| 55 |
|
| 56 |
-
# OCR configuration
|
| 57 |
custom_config = r'--oem 3 --psm 6 -c tessedit_char_whitelist=0123456789.'
|
| 58 |
|
| 59 |
-
# Run OCR
|
| 60 |
text = pytesseract.image_to_string(processed_img, config=custom_config)
|
| 61 |
logging.info(f"OCR result: '{text}'")
|
| 62 |
|
| 63 |
-
# Extract valid weight
|
| 64 |
weight = ''.join(filter(lambda x: x in '0123456789.', text.strip()))
|
| 65 |
if weight:
|
| 66 |
try:
|
| 67 |
weight_float = float(weight)
|
| 68 |
-
if weight_float >= 0: #
|
| 69 |
-
confidence = 95.0 #
|
| 70 |
logging.info(f"Weight detected: {weight} (Confidence: {confidence:.2f}%)")
|
| 71 |
return weight, confidence, processed_img
|
| 72 |
except ValueError:
|
|
@@ -78,7 +78,7 @@ def extract_weight(img):
|
|
| 78 |
logging.error(f"OCR processing failed: {str(e)}")
|
| 79 |
return "Not detected", 0.0, None
|
| 80 |
|
| 81 |
-
# Main function to process image and
|
| 82 |
def process_image(img):
|
| 83 |
"""Process uploaded or captured image and extract weight."""
|
| 84 |
if img is None:
|
|
@@ -91,11 +91,12 @@ def process_image(img):
|
|
| 91 |
# Extract weight and confidence from the image
|
| 92 |
weight, confidence, processed_img = extract_weight(img)
|
| 93 |
|
|
|
|
| 94 |
if weight == "Not detected" or confidence < 95.0:
|
| 95 |
logging.warning(f"Weight detection failed: {weight} (Confidence: {confidence:.2f}%)")
|
| 96 |
return f"{weight} (Confidence: {confidence:.2f}%)", ist_time, gr.update(visible=True), gr.update(visible=False)
|
| 97 |
|
| 98 |
-
# Convert processed image to base64 for
|
| 99 |
pil_image = Image.fromarray(processed_img)
|
| 100 |
buffered = io.BytesIO()
|
| 101 |
pil_image.save(buffered, format="PNG")
|
|
@@ -103,7 +104,7 @@ def process_image(img):
|
|
| 103 |
|
| 104 |
return f"{weight} kg (Confidence: {confidence:.2f}%)", ist_time, img_base64, gr.update(visible=True)
|
| 105 |
|
| 106 |
-
# Gradio Interface
|
| 107 |
with gr.Blocks(title="⚖️ Auto Weight Logger") as demo:
|
| 108 |
gr.Markdown("## ⚖️ Auto Weight Logger")
|
| 109 |
gr.Markdown("📷 Upload or capture an image of a digital weight scale (max 5MB).")
|
|
|
|
| 9 |
import numpy as np
|
| 10 |
import logging
|
| 11 |
|
| 12 |
+
# Set up logging for better debugging
|
| 13 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 14 |
|
| 15 |
+
# Configure Tesseract path (ensure it's correctly set to your Tesseract installation)
|
| 16 |
try:
|
| 17 |
+
pytesseract.pytesseract.tesseract_cmd = '/usr/bin/tesseract' # Change this to your tesseract path
|
| 18 |
pytesseract.get_tesseract_version() # Test Tesseract availability
|
| 19 |
logging.info("Tesseract is available")
|
| 20 |
except Exception as e:
|
| 21 |
logging.error(f"Tesseract not found or misconfigured: {str(e)}")
|
| 22 |
|
| 23 |
+
# Image Preprocessing to improve OCR accuracy
|
| 24 |
def preprocess_image(img_cv):
|
| 25 |
"""Preprocess image for OCR: enhance contrast, reduce noise, and apply adaptive thresholding."""
|
| 26 |
try:
|
|
|
|
| 40 |
logging.error(f"Image preprocessing failed: {str(e)}")
|
| 41 |
return img_cv
|
| 42 |
|
| 43 |
+
# Function to extract weight from the image using Tesseract OCR
|
| 44 |
def extract_weight(img):
|
| 45 |
+
"""Extract weight from image using Tesseract OCR."""
|
| 46 |
try:
|
| 47 |
if img is None:
|
| 48 |
logging.error("No image provided for OCR")
|
| 49 |
return "Not detected", 0.0, None
|
| 50 |
|
| 51 |
+
# Convert PIL image to OpenCV format for processing
|
| 52 |
img_cv = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
|
| 53 |
+
# Preprocess the image (contrast, noise reduction, etc.)
|
| 54 |
processed_img = preprocess_image(img_cv)
|
| 55 |
|
| 56 |
+
# OCR configuration to focus on digits and decimals
|
| 57 |
custom_config = r'--oem 3 --psm 6 -c tessedit_char_whitelist=0123456789.'
|
| 58 |
|
| 59 |
+
# Run OCR on the processed image
|
| 60 |
text = pytesseract.image_to_string(processed_img, config=custom_config)
|
| 61 |
logging.info(f"OCR result: '{text}'")
|
| 62 |
|
| 63 |
+
# Extract valid weight (only digits and decimals)
|
| 64 |
weight = ''.join(filter(lambda x: x in '0123456789.', text.strip()))
|
| 65 |
if weight:
|
| 66 |
try:
|
| 67 |
weight_float = float(weight)
|
| 68 |
+
if weight_float >= 0: # Ensure valid weight value
|
| 69 |
+
confidence = 95.0 # High confidence if weight is valid
|
| 70 |
logging.info(f"Weight detected: {weight} (Confidence: {confidence:.2f}%)")
|
| 71 |
return weight, confidence, processed_img
|
| 72 |
except ValueError:
|
|
|
|
| 78 |
logging.error(f"OCR processing failed: {str(e)}")
|
| 79 |
return "Not detected", 0.0, None
|
| 80 |
|
| 81 |
+
# Main function to process the image and return results
|
| 82 |
def process_image(img):
|
| 83 |
"""Process uploaded or captured image and extract weight."""
|
| 84 |
if img is None:
|
|
|
|
| 91 |
# Extract weight and confidence from the image
|
| 92 |
weight, confidence, processed_img = extract_weight(img)
|
| 93 |
|
| 94 |
+
# If no weight detected, display the failure message
|
| 95 |
if weight == "Not detected" or confidence < 95.0:
|
| 96 |
logging.warning(f"Weight detection failed: {weight} (Confidence: {confidence:.2f}%)")
|
| 97 |
return f"{weight} (Confidence: {confidence:.2f}%)", ist_time, gr.update(visible=True), gr.update(visible=False)
|
| 98 |
|
| 99 |
+
# Convert processed image to base64 for displaying it as a snapshot
|
| 100 |
pil_image = Image.fromarray(processed_img)
|
| 101 |
buffered = io.BytesIO()
|
| 102 |
pil_image.save(buffered, format="PNG")
|
|
|
|
| 104 |
|
| 105 |
return f"{weight} kg (Confidence: {confidence:.2f}%)", ist_time, img_base64, gr.update(visible=True)
|
| 106 |
|
| 107 |
+
# Gradio Interface for user input and displaying results
|
| 108 |
with gr.Blocks(title="⚖️ Auto Weight Logger") as demo:
|
| 109 |
gr.Markdown("## ⚖️ Auto Weight Logger")
|
| 110 |
gr.Markdown("📷 Upload or capture an image of a digital weight scale (max 5MB).")
|