DSatishchandra's picture
Update app.py
f57aa87 verified
Raw
History Blame Contribute Delete
2.47 kB
import pytesseract as pyt
import cv2
import re
import gradio as gr
# Function to extract text from image and identify relevant details
def extract_patient_info(image):
# Convert the image to a numpy array
img = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) # Gradio loads the image as RGB, OpenCV uses BGR
text = pyt.image_to_string(img) # Use Tesseract to extract text from the image
patient_info = {
"Name": None,
"Age": None,
"Gender": None,
"Phone Number": None
}
# Debug: Print the extracted OCR text for troubleshooting
print("OCR Text:\n", text)
# Extract Patient Name using regex (Look for 'Patient Name:' and capture the name)
name_match = re.search(r"Name[:\s]*([A-Za-z\s]+)", text)
if name_match:
patient_info["Name"] = name_match.group(1)
# Extract Age using regex (Look for 'Age' and capture the value)
age_match = re.search(r"Age\s*[:\-]?\s*(\d{1,2})", text)
if age_match:
patient_info["Age"] = age_match.group(1)
# Extract Gender using regex (Look for 'Gender' and capture the gender)
gender_match = re.search(r"Gender\s*[:\-]?\s*(Male|Female)", text, re.IGNORECASE)
if gender_match:
patient_info["Gender"] = gender_match.group(1)
# Extract Phone Number using regex (Look for a 10-digit number)
phone_match = re.search(r"\b\d{10}\b", text)
if phone_match:
patient_info["Phone Number"] = phone_match.group(0)
return patient_info["Name"], patient_info["Age"], patient_info["Gender"], patient_info["Phone Number"]
# Gradio interface setup
with gr.Blocks() as demo:
gr.Markdown("### Patient Information Extraction from Image")
# Image upload component
image_input = gr.Image(type="numpy", label="Upload Image")
# Output textboxes to display the extracted information
name_output = gr.Textbox(label="Name")
age_output = gr.Textbox(label="Age")
gender_output = gr.Textbox(label="Gender")
phone_output = gr.Textbox(label="Phone Number")
# Button to trigger image processing and text extraction
process_button = gr.Button("Process Image")
# When the button is clicked, process the image and show results in textboxes
process_button.click(fn=extract_patient_info, inputs=image_input, outputs=[name_output, age_output, gender_output, phone_output])
# Launch the Gradio app
if __name__ == "__main__":
demo.launch()