File size: 4,523 Bytes
add57fc
cfb52b3
add57fc
cfb52b3
 
add57fc
 
 
cfb52b3
 
add57fc
cfb52b3
 
 
 
 
3594567
cfb52b3
 
 
094fb8a
34f285a
094fb8a
cfb52b3
34f285a
cfb52b3
add57fc
cfb52b3
 
 
 
9170bfd
cfb52b3
 
 
 
 
 
 
 
 
 
 
 
 
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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
from transformers import pipeline
from PIL import Image
import pytesseract
import json
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas

# 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()

# Extract text from uploaded image using OCR
def extract_text_from_image(image_path):
    try:
        text = pytesseract.image_to_string(Image.open(image_path))
        return text
    except Exception as e:
        return f"Error extracting text: {e}"

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

    for param, ranges in reference_ranges.items():
        if param in text.lower():
            try:
                # Mock parsing logic to extract the value
                value = float(text.split(param)[1].split()[0])  # Extract value after the parameter name
                if value < ranges["low"]:
                    abnormalities.append(f"{param.capitalize()} is LOW ({value} {ranges['unit']}).")
                elif value > ranges["high"]:
                    abnormalities.append(f"{param.capitalize()} is HIGH ({value} {ranges['unit']}).")
                else:
                    analysis += f"{param.capitalize()} is NORMAL ({value} {ranges['unit']}).\n"
            except Exception:
                analysis += f"{param.capitalize()} could not be analyzed.\n"

    # Flag abnormalities
    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()