anoopreddyyeddula commited on
Commit
38f4471
·
0 Parent(s):

Initial commit: Insurance Claim Validation System with updated dependencies and documentation

Browse files
Files changed (5) hide show
  1. .gitattributes +35 -0
  2. Dockerfile +32 -0
  3. README.md +52 -0
  4. app.py +184 -0
  5. requirements.txt +10 -0
.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
Dockerfile ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:20.04
2
+
3
+ ENV DEBIAN_FRONTEND=noninteractive
4
+
5
+ # Install Python and system dependencies
6
+ RUN apt-get update && apt-get install -y \
7
+ python3.9 \
8
+ python3-pip \
9
+ tesseract-ocr \
10
+ tesseract-ocr-eng \
11
+ libgl1-mesa-glx \
12
+ libglib2.0-0 \
13
+ poppler-utils \
14
+ && apt-get clean \
15
+ && rm -rf /var/lib/apt/lists/*
16
+
17
+ WORKDIR /code
18
+
19
+ # Upgrade pip and install dependencies
20
+ COPY requirements.txt .
21
+ RUN python3.9 -m pip install --no-cache-dir --upgrade pip && \
22
+ python3.9 -m pip install --no-cache-dir -r requirements.txt
23
+
24
+ # Copy the application
25
+ COPY . .
26
+
27
+ # Set environment variables
28
+ ENV PYTHONUNBUFFERED=1
29
+ ENV TESSDATA_PREFIX=/usr/share/tesseract-ocr/4.00/tessdata
30
+
31
+ # Run the application
32
+ CMD ["python3.9", "app.py"]
README.md ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Automated Insurance Claim Validation System
3
+ emoji: 📄
4
+ colorFrom: blue
5
+ colorTo: red
6
+ sdk: gradio
7
+ sdk_version: 3.50.2
8
+ app_file: app.py
9
+ pinned: false
10
+ license: mit
11
+ ---
12
+
13
+ # Automated Insurance Claim Validation System
14
+
15
+ This project automates the validation process for insurance claims using image processing and NLP techniques.
16
+
17
+ ## Features:
18
+ - Support for both PDF and image files
19
+ - Multiple page processing
20
+ - EasyOCR for reliable text extraction
21
+ - BERT-based text validation
22
+ - Document classification using pre-trained models
23
+ - Export results to Excel
24
+ - User-friendly Gradio interface
25
+
26
+ ## System Requirements:
27
+ - Python 3.9+
28
+ - Required Python packages (see requirements.txt)
29
+ - System dependencies: tesseract-ocr, poppler-utils
30
+
31
+ ## Installation:
32
+ ```bash
33
+ pip install -r requirements.txt
34
+ ```
35
+
36
+ ## Usage:
37
+ 1. Upload an insurance claim document (PDF or image)
38
+ 2. The system will:
39
+ - Process all pages in the document
40
+ - Extract text using EasyOCR
41
+ - Validate the extracted text
42
+ - Classify each page
43
+ - Generate a downloadable report
44
+ 3. Download the Excel report for detailed analysis
45
+
46
+ ## Models Used:
47
+ - OCR: EasyOCR
48
+ - Text Classification: DistilBERT (distilbert-base-uncased-finetuned-sst-2-english)
49
+ - Document Classification: Donut (naver-clova-ix/donut-base-finetuned-rvlcdip)
50
+
51
+ ## Live Demo:
52
+ Access the live demo at: https://huggingface.co/spaces/anoopreddyyeddula/Automated-Insurance-Claim-Validation-System
app.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import easyocr
2
+ import numpy as np
3
+ from PIL import Image
4
+ from transformers import pipeline
5
+ import gradio as gr
6
+ import pdf2image
7
+ import PyPDF2
8
+ import pandas as pd
9
+ import io
10
+ from datetime import datetime
11
+
12
+ # Initialize the OCR reader
13
+ reader = easyocr.Reader(['en'])
14
+
15
+ # Use text classification model
16
+ text_classifier = pipeline("text-classification", model="distilbert-base-uncased-finetuned-sst-2-english")
17
+
18
+ # Use document classification model
19
+ doc_classifier = pipeline("document-classification", model="naver-clova-ix/donut-base-finetuned-rvlcdip")
20
+
21
+ def convert_pdf_to_images(pdf_file):
22
+ """Convert PDF to list of images"""
23
+ try:
24
+ return pdf2image.convert_from_bytes(pdf_file.read())
25
+ except Exception as e:
26
+ return None
27
+
28
+ def process_single_image(image):
29
+ """Process a single image and return results"""
30
+ extracted_text = ocr_function(image)
31
+
32
+ validation_result = text_classifier(extracted_text[:512])
33
+ sentiment = validation_result[0]['label']
34
+ confidence = validation_result[0]['score']
35
+
36
+ doc_result = doc_classifier(image)
37
+ doc_type = doc_result[0]['label']
38
+ doc_confidence = doc_result[0]['score']
39
+
40
+ return {
41
+ 'text': extracted_text,
42
+ 'validation': sentiment,
43
+ 'validation_confidence': confidence,
44
+ 'doc_type': doc_type,
45
+ 'doc_confidence': doc_confidence
46
+ }
47
+
48
+ def generate_report(results):
49
+ """Generate a formatted report from results"""
50
+ df = pd.DataFrame(results)
51
+
52
+ # Create Excel buffer
53
+ excel_buffer = io.BytesIO()
54
+ with pd.ExcelWriter(excel_buffer) as writer:
55
+ df.to_excel(writer, index=False)
56
+ excel_buffer.seek(0)
57
+
58
+ # Create summary text
59
+ summary = f"""
60
+ Insurance Claim Processing Report
61
+ Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
62
+
63
+ Total Pages Processed: {len(results)}
64
+ Document Types Found: {', '.join(set(df['doc_type']))}
65
+ """
66
+
67
+ return summary, excel_buffer
68
+
69
+ def ocr_function(image):
70
+ try:
71
+ # Convert PIL image to numpy array
72
+ if isinstance(image, Image.Image):
73
+ image = np.array(image)
74
+
75
+ # Perform OCR
76
+ results = reader.readtext(image)
77
+
78
+ # Extract text
79
+ text = ' '.join([result[1] for result in results])
80
+
81
+ if not text.strip():
82
+ return "No text was detected in the image"
83
+
84
+ return text.strip()
85
+ except Exception as e:
86
+ return f"OCR Error: {str(e)}"
87
+
88
+ def validate_text(text):
89
+ try:
90
+ result = text_classifier(text[:512]) # Limit text length to avoid token limit
91
+ return result[0]['label']
92
+ except Exception as e:
93
+ return f"Validation Error: {str(e)}"
94
+
95
+ def classify_document(image):
96
+ try:
97
+ # Convert PIL image to RGB if needed
98
+ if image.mode != 'RGB':
99
+ image = image.convert('RGB')
100
+ result = doc_classifier(image)
101
+ return f"Document Type: {result[0]['label']}"
102
+ except Exception as e:
103
+ return f"Classification Error: {str(e)}"
104
+
105
+ def validate_image(image):
106
+ """Validate image before processing"""
107
+ try:
108
+ if image is None:
109
+ return False, "No image provided"
110
+
111
+ if isinstance(image, np.ndarray):
112
+ image = Image.fromarray(image)
113
+
114
+ if not isinstance(image, Image.Image):
115
+ return False, "Invalid image format"
116
+
117
+ # Check image size
118
+ if image.size[0] * image.size[1] > 5000 * 5000:
119
+ return False, "Image too large. Maximum size: 5000x5000"
120
+
121
+ return True, image
122
+ except Exception as e:
123
+ return False, f"Image validation error: {str(e)}"
124
+
125
+ def process_claim(file):
126
+ try:
127
+ if file is None:
128
+ return "No file provided", "N/A", "N/A", None
129
+
130
+ # Check if file is PDF
131
+ if hasattr(file, 'name') and file.name.lower().endswith('.pdf'):
132
+ images = convert_pdf_to_images(file)
133
+ if not images:
134
+ return "Failed to process PDF", "Error", "Error", None
135
+ else:
136
+ # Handle single image
137
+ if isinstance(file, np.ndarray):
138
+ images = [Image.fromarray(file)]
139
+ else:
140
+ images = [file]
141
+
142
+ # Process each page
143
+ results = []
144
+ for idx, img in enumerate(images):
145
+ result = process_single_image(img)
146
+ result['page'] = idx + 1
147
+ results.append(result)
148
+
149
+ # Generate report
150
+ summary, excel_file = generate_report(results)
151
+
152
+ # Return results for display
153
+ return (
154
+ "\n\n=== Page Break ===\n\n".join([r['text'] for r in results]),
155
+ "\n".join([f"Page {r['page']}: {r['validation']} ({r['validation_confidence']:.2%})" for r in results]),
156
+ "\n".join([f"Page {r['page']}: {r['doc_type']} ({r['doc_confidence']:.2%})" for r in results]),
157
+ excel_file
158
+ )
159
+
160
+ except Exception as e:
161
+ return f"Processing error: {str(e)}", "Error", "Error", None
162
+
163
+ # Create Gradio interface
164
+ iface = gr.Interface(
165
+ fn=process_claim,
166
+ inputs=gr.File(label="Upload Insurance Document (Image or PDF)"),
167
+ outputs=[
168
+ gr.Textbox(label="Extracted Text"),
169
+ gr.Textbox(label="Text Validation"),
170
+ gr.Textbox(label="Document Classification"),
171
+ gr.File(label="Download Report")
172
+ ],
173
+ title="Insurance Claim Validation System",
174
+ description="Upload an insurance claim document (PDF or image) to validate and classify it.",
175
+ examples=[
176
+ "examples/insurance_claim1.jpg",
177
+ "examples/insurance_claim2.jpg"
178
+ ],
179
+ cache_examples=True,
180
+ theme=gr.themes.Soft()
181
+ )
182
+
183
+ if __name__ == "__main__":
184
+ iface.launch()
requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ gradio>=3.50.2
2
+ transformers>=4.30.0
3
+ pillow>=9.0.0
4
+ numpy>=1.21.0
5
+ torch>=2.0.0
6
+ easyocr>=1.7.0
7
+ opencv-python>=4.5.0
8
+ pdf2image>=1.16.3
9
+ PyPDF2>=3.0.0
10
+ pandas>=1.3.0