sunbal7 commited on
Commit
6679896
·
verified ·
1 Parent(s): 25b01a7

Delete ocr_processor.py

Browse files
Files changed (1) hide show
  1. ocr_processor.py +0 -118
ocr_processor.py DELETED
@@ -1,118 +0,0 @@
1
- import cv2
2
- import numpy as np
3
- import pytesseract
4
- from PIL import Image
5
- import re
6
-
7
- class PrescriptionOCR:
8
- def __init__(self):
9
- self.medication_keywords = [
10
- 'tablet', 'capsule', 'mg', 'ml', 'injection', 'dose',
11
- 'twice', 'thrice', 'daily', 'weekly', 'monthly'
12
- ]
13
-
14
- def preprocess_image(self, image):
15
- """Enhanced image preprocessing for medical prescriptions"""
16
- try:
17
- # Convert to numpy array
18
- img_array = np.array(image)
19
-
20
- # Convert to grayscale
21
- if len(img_array.shape) == 3:
22
- gray = cv2.cvtColor(img_array, cv2.COLOR_RGB2GRAY)
23
- else:
24
- gray = img_array
25
-
26
- # Noise removal
27
- denoised = cv2.medianBlur(gray, 3)
28
-
29
- # Thresholding
30
- _, thresh = cv2.threshold(denoised, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
31
-
32
- # Morphological operations
33
- kernel = np.ones((2, 2), np.uint8)
34
- processed = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
35
-
36
- return processed
37
-
38
- except Exception as e:
39
- print(f"Image preprocessing error: {e}")
40
- return np.array(image)
41
-
42
- def extract_medication_info(self, text):
43
- """Extract medication information from OCR text"""
44
- medications = []
45
- lines = text.split('\n')
46
-
47
- for line in lines:
48
- line_clean = line.strip()
49
- if any(keyword in line_clean.lower() for keyword in self.medication_keywords):
50
- # Extract dosage information
51
- dosage_pattern = r'(\d+\s*(?:mg|ml|tablet|cap)s?)'
52
- dosages = re.findall(dosage_pattern, line_clean, re.IGNORECASE)
53
-
54
- # Extract frequency
55
- freq_pattern = r'(?:once|twice|thrice|\d+\s*times)\s*(?:daily|a day|per day)'
56
- frequency = re.findall(freq_pattern, line_clean, re.IGNORECASE)
57
-
58
- medication_info = {
59
- 'text': line_clean,
60
- 'dosages': dosages,
61
- 'frequency': frequency[0] if frequency else 'Unknown',
62
- 'confidence': 'High' if dosages else 'Medium'
63
- }
64
- medications.append(medication_info)
65
-
66
- return medications
67
-
68
- def process_prescription(self, image):
69
- """Main method to process prescription and extract information"""
70
- try:
71
- # Preprocess image
72
- processed_img = self.preprocess_image(image)
73
-
74
- # OCR with medical-specific configuration
75
- custom_config = r'--oem 3 --psm 6 -l eng'
76
- extracted_text = pytesseract.image_to_string(processed_img, config=custom_config)
77
-
78
- # Extract medication information
79
- medications = self.extract_medication_info(extracted_text)
80
-
81
- # Calculate confidence score
82
- confidence = self.calculate_confidence(extracted_text, medications)
83
-
84
- return {
85
- 'raw_text': extracted_text,
86
- 'medications': medications,
87
- 'confidence_score': confidence,
88
- 'medication_count': len(medications)
89
- }
90
-
91
- except Exception as e:
92
- return {
93
- 'raw_text': '',
94
- 'medications': [],
95
- 'confidence_score': 0,
96
- 'error': str(e)
97
- }
98
-
99
- def calculate_confidence(self, text, medications):
100
- """Calculate confidence score for OCR extraction"""
101
- if not text.strip():
102
- return 0
103
-
104
- # Base score based on text length and medication detection
105
- base_score = min(100, len(text) / 10)
106
-
107
- # Bonus for medication detection
108
- medication_bonus = len(medications) * 15
109
-
110
- # Penalty for likely errors
111
- error_penalty = 0
112
- if len(text) < 20:
113
- error_penalty += 20
114
- if len(re.findall(r'[^\w\s.,]', text)) > len(text) * 0.3:
115
- error_penalty += 15
116
-
117
- final_score = base_score + medication_bonus - error_penalty
118
- return max(0, min(100, final_score))