File size: 5,235 Bytes
add57fc
cfb52b3
add57fc
cfb52b3
add57fc
 
fb7d282
74dd904
add57fc
fb7d282
 
 
cfb52b3
 
add57fc
cfb52b3
 
 
 
 
3594567
cfb52b3
 
74dd904
 
 
 
 
 
 
 
5637e13
 
 
 
74dd904
 
 
fb7d282
094fb8a
34f285a
fb7d282
 
 
 
 
34f285a
cfb52b3
add57fc
74dd904
 
5637e13
74dd904
 
 
 
cfb52b3
 
 
 
9170bfd
74dd904
 
 
 
 
cfb52b3
74dd904
cfb52b3
74dd904
cfb52b3
74dd904
 
 
add57fc
cfb52b3
 
 
 
34f285a
cfb52b3
add57fc
cfb52b3
 
 
 
 
 
 
 
 
 
1120d0b
cfb52b3
 
1120d0b
 
 
 
 
 
 
cfb52b3
094fb8a
cfb52b3
094fb8a
cfb52b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
add57fc
cfb52b3
094fb8a
add57fc
cfb52b3
 
add57fc
cfb52b3
add57fc
cfb52b3
 
add57fc
cfb52b3
 
 
 
fb7d282
cfb52b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
add57fc
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
import gradio as gr
from transformers import pipeline
from PIL import Image
import json
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
import easyocr
import re

# Initialize EasyOCR reader
reader = easyocr.Reader(["en"], gpu=False)

# Load BioGPT model for recommendations
bio_gpt = pipeline("text-generation", model="microsoft/BioGPT")

# Load reference ranges from dataset.json
def load_reference_ranges(file_path="dataset.json"):
    with open(file_path, "r") as file:
        reference_ranges = json.load(file)
    return reference_ranges

reference_ranges = load_reference_ranges()

# Parameter name mapping
parameter_mapping = {
    "hgb": "hemoglobin",
    "hemoglobin": "hemoglobin",
    "rbc": "rbc",
    "wbc": "wbc",
    "plt": "platelet",
    "platelets": "platelet",
    "hematocrit": "hematocrit",
    "mcv": "mcv",
    "mch": "mch",
    "mchc": "mchc",
    # Add more mappings as needed
}

# Extract text from uploaded image using EasyOCR
def extract_text_from_image(image_path):
    try:
        # Read text from image
        result = reader.readtext(image_path, detail=0)  # Extract only the text
        extracted_text = " ".join(result)
        print("Extracted Text:", extracted_text)  # Debugging
        return extracted_text
    except Exception as e:
        return f"Error extracting text: {e}"

# Extract value using regex
def extract_value(text, param):
    match = re.search(rf"{param}[:\s]*([\d.]+)", text, re.IGNORECASE)
    if match:
        return float(match.group(1))
    return None

# Analyze extracted text and compare against reference ranges
def analyze_blood_report(text):
    abnormalities = []
    analysis = "Blood Test Analysis Results:\n\n"

    for key, standard_param in parameter_mapping.items():
        if key in text.lower():
            ranges = reference_ranges[standard_param]
            value = extract_value(text, key)
            if value is not None:
                if value < ranges["low"]:
                    abnormalities.append(f"{standard_param.capitalize()} is LOW ({value} {ranges['unit']}).")
                elif value > ranges["high"]:
                    abnormalities.append(f"{standard_param.capitalize()} is HIGH ({value} {ranges['unit']}).")
                else:
                    analysis += f"{standard_param.capitalize()} is NORMAL ({value} {ranges['unit']}).\n"
            else:
                analysis += f"{standard_param.capitalize()} could not be analyzed.\n"

    if abnormalities:
        analysis += "\nAbnormalities Detected:\n" + "\n".join(abnormalities) + "\n"
    else:
        analysis += "\nNo abnormalities detected.\n"

    return analysis, abnormalities

# Generate recommendations using BioGPT
def get_recommendations(abnormalities):
    if not abnormalities:
        return "No recommendations needed."
    query = " ".join(abnormalities) + " Provide medical recommendations."
    recommendations = bio_gpt(query, max_length=100, num_return_sequences=1)[0]["generated_text"]
    return recommendations

# Create a PDF report
def create_pdf_report(content, output_path="blood_test_report.pdf"):
    c = canvas.Canvas(output_path, pagesize=letter)
    c.drawString(100, 750, "Blood Test Report")
    c.drawString(100, 730, "-----------------")
    y_position = 700
    for line in content.split("\n"):
        c.drawString(100, y_position, line)
        y_position -= 20
    c.save()
    return output_path

# Main function to process blood test image
def process_blood_test(image_path):
    # Step 1: Extract text
    extracted_text = extract_text_from_image(image_path)
    if "Error" in extracted_text:
        return extracted_text, None

    # Step 2: Analyze extracted text
    analysis, abnormalities = analyze_blood_report(extracted_text)

    # Step 3: Generate recommendations
    recommendations = get_recommendations(abnormalities)

    # Step 4: Combine results and create PDF
    full_report = analysis + "\nRecommendations:\n" + recommendations
    pdf_path = create_pdf_report(full_report)

    return full_report, pdf_path

# Gradio Interface
interface = gr.Interface(
    fn=process_blood_test,
    inputs=gr.Image(type="filepath", label="Upload Blood Test Report Image (PNG, JPG, JPEG)"),
    outputs=[
        gr.Textbox(label="Analysis and Recommendations"),
        gr.File(label="Download PDF Report"),
    ],
    title="AI Blood Test Analyzer",
    description=(
        "Upload a blood test report image (PNG, JPG, JPEG), and the app will analyze the values, flag abnormalities, "
        "and provide recommendations using BioGPT. You can also download a PDF report."
    ),
    theme="compact",
    css="""
        body {
            font-family: 'Arial', sans-serif;
            background-color: #f9f9f9;
        }
        .gradio-container {
            color: #333;
            max-width: 800px;
            margin: 0 auto;
        }
        .gradio-container .label {
            font-weight: bold;
            font-size: 18px;
        }
        .gradio-container .output {
            background-color: #eef;
            padding: 10px;
            border-radius: 10px;
        }
    """,
    allow_flagging="never"
)

if __name__ == "__main__":
    interface.launch()