import streamlit as st
import numpy as np
import cv2
from PIL import Image
from fpdf import FPDF
import tempfile
import os
import uuid
import datetime
from model import load_model, predict
# โโ Page config โโ
st.set_page_config(
page_title = 'DocSight',
page_icon = '๐๏ธ',
layout = 'wide'
)
# โโ CSS โโ
st.markdown("""
""", unsafe_allow_html=True)
# โโ Load model โโ
@st.cache_resource
def get_model():
with st.spinner('Loading AI model...'):
return load_model()
model = get_model()
# โโ Helper: generate patient ID โโ
def generate_patient_id():
today = datetime.datetime.now().strftime('%Y%m%d')
uid = str(uuid.uuid4()).upper()[:6]
return f"PAT-{today}-{uid}"
# โโ Session state init โโ
if 'patient_id' not in st.session_state:
st.session_state.patient_id = generate_patient_id()
if 'reset' not in st.session_state:
st.session_state.reset = False
# โโ Sidebar โโ
with st.sidebar:
st.markdown("""
DocSight
AI Diagnostic Platform
""", unsafe_allow_html=True)
st.markdown('Model Performance
', unsafe_allow_html=True)
for val, lbl in [("0.9986","AUC-ROC"),("98.18%","Accuracy"),("98.86%","Sensitivity"),("97.16%","Specificity")]:
st.markdown(f"""
""", unsafe_allow_html=True)
st.markdown('About
', unsafe_allow_html=True)
st.markdown("""
Model: EfficientNet-B4
Data: APTOS 2019 + IDRiD
Images: 4,117
Threshold: 0.35
Explainability: Grad-CAM
""", unsafe_allow_html=True)
st.markdown('How to Use
', unsafe_allow_html=True)
st.markdown("""
1๏ธโฃ Patient ID is auto-generated
2๏ธโฃ Enter patient details
3๏ธโฃ Upload fundus image
4๏ธโฃ View AI analysis
5๏ธโฃ Download PDF report
6๏ธโฃ Click Next Patient to reset
""", unsafe_allow_html=True)
# โโ Header โโ
st.markdown("""
""", unsafe_allow_html=True)
# โโ Patient Info โโ
st.markdown('Patient Information
', unsafe_allow_html=True)
st.markdown(f"""
๐ชช Patient ID: {st.session_state.patient_id}
""", unsafe_allow_html=True)
col_a, col_b, col_c = st.columns(3)
with col_a:
patient_name = st.text_input('', placeholder='๐ค Patient Name',
key=f'name_{st.session_state.patient_id}')
with col_b:
patient_age = st.text_input('', placeholder='๐ Age',
key=f'age_{st.session_state.patient_id}')
with col_c:
patient_gender = st.text_input('', placeholder='โง Gender (Male / Female)',
key=f'gender_{st.session_state.patient_id}')
# โโ Buttons row โโ
btn1, btn2 = st.columns(2)
with btn1:
if st.button('๐ Generate New Patient ID'):
st.session_state.patient_id = generate_patient_id()
st.rerun()
with btn2:
if st.button('๐ค Test Next Patient โ Clear All'):
st.session_state.patient_id = generate_patient_id()
st.rerun()
# โโ Upload โโ
st.markdown('Fundus Image Upload
', unsafe_allow_html=True)
if st.session_state.reset:
st.session_state.reset = False
uploaded = st.file_uploader(
'Upload a retinal fundus image (PNG, JPG, JPEG)',
type=['png', 'jpg', 'jpeg'],
key=f'upload_{st.session_state.patient_id}'
)
# โโ Analysis โโ
if uploaded is not None:
pil_img = Image.open(uploaded).convert('RGB')
img_array = np.array(pil_img)
st.markdown('Analysis
', unsafe_allow_html=True)
progress = st.progress(0, text='Initializing...')
import time
progress.progress(25, text='Preprocessing image...')
time.sleep(0.3)
progress.progress(55, text='Running AI inference...')
img_rgb, cam, prediction, prob = predict(model, img_array, threshold=0.35)
progress.progress(80, text='Generating Grad-CAM...')
heatmap = cv2.applyColorMap(np.uint8(255 * cam), cv2.COLORMAP_JET)
heatmap = cv2.cvtColor(heatmap, cv2.COLOR_BGR2RGB)
overlay = cv2.addWeighted(img_rgb, 0.5, heatmap, 0.5, 0)
time.sleep(0.2)
progress.progress(100, text='Analysis complete!')
time.sleep(0.3)
progress.empty()
# โโ Images โโ
st.markdown('Visual Analysis
', unsafe_allow_html=True)
c1, c2, c3 = st.columns(3)
with c1:
st.image(img_rgb, use_column_width=True)
st.markdown('Preprocessed Image
', unsafe_allow_html=True)
with c2:
st.image(heatmap, use_column_width=True)
st.markdown('Grad-CAM ยท Red = High Attention
', unsafe_allow_html=True)
with c3:
st.image(overlay, use_column_width=True)
st.markdown('Overlay
', unsafe_allow_html=True)
# โโ Result โโ
st.markdown('Diagnostic Result
', unsafe_allow_html=True)
conf = 'Refer to Specialist' if prediction == 'DR' else 'Routine Checkup Advised'
if prediction == 'DR':
st.markdown(f"""
๐ด Diabetic Retinopathy Detected
DR Probability: {prob:.1%} ยท
Recommendation: {conf}
""", unsafe_allow_html=True)
elif prob >= 0.2:
st.markdown(f"""
๐ก Borderline โ Manual Review Advised
DR Probability: {prob:.1%} ยท
Further examination recommended
""", unsafe_allow_html=True)
else:
st.markdown(f"""
๐ข No Diabetic Retinopathy Detected
DR Probability: {prob:.1%} ยท
Recommendation: {conf}
""", unsafe_allow_html=True)
# โโ Metrics โโ
st.markdown(f"""
{'DR' if prediction=='DR' else 'No DR'}
Prediction
{prob:.4f}
DR Probability
""", unsafe_allow_html=True)
# โโ PDF โโ
st.markdown('Download Report
', unsafe_allow_html=True)
if st.button('๐ Generate PDF Report'):
with st.spinner('Generating report...'):
tmp_dir = tempfile.mkdtemp()
orig_path = os.path.join(tmp_dir, 'original.png')
heat_path = os.path.join(tmp_dir, 'heatmap.png')
overlay_path = os.path.join(tmp_dir, 'overlay.png')
Image.fromarray(img_rgb).save(orig_path)
Image.fromarray(heatmap).save(heat_path)
Image.fromarray(overlay).save(overlay_path)
pdf = FPDF()
pdf.add_page()
pdf.set_fill_color(15, 118, 110)
pdf.rect(0, 0, 210, 28, 'F')
pdf.set_font('Arial', 'B', 18)
pdf.set_text_color(255, 255, 255)
pdf.set_y(8)
pdf.cell(0, 10, 'DocSight - AI Diagnostic Report', ln=True, align='C')
pdf.set_font('Arial', '', 9)
pdf.set_text_color(204, 251, 241)
pdf.cell(0, 6, 'AI Powered GUI for Diabetic Retinopathy Diagnosis', ln=True, align='C')
pdf.set_y(34)
pdf.set_fill_color(240, 253, 250)
pdf.rect(10, pdf.get_y(), 190, 30, 'F')
pdf.set_y(pdf.get_y() + 4)
pdf.set_font('Arial', 'B', 10)
pdf.set_text_color(15, 118, 110)
pdf.cell(0, 6, 'PATIENT INFORMATION', ln=True, align='C')
pdf.set_font('Arial', '', 10)
pdf.set_text_color(30, 41, 59)
pdf.cell(47, 6, f'ID: {st.session_state.patient_id}', align='C')
pdf.cell(47, 6, f'Name: {patient_name if patient_name else "N/A"}', align='C')
pdf.cell(47, 6, f'Age: {patient_age if patient_age else "N/A"}', align='C')
pdf.cell(47, 6, f'Gender: {patient_gender if patient_gender else "N/A"}', align='C', ln=True)
pdf.ln(4)
pdf.set_font('Arial', '', 9)
pdf.set_text_color(100, 116, 139)
pdf.cell(0, 6, f'Report generated: {datetime.datetime.now().strftime("%d %B %Y, %I:%M %p")}',
ln=True, align='C')
pdf.ln(4)
if prediction == 'DR':
pdf.set_fill_color(255, 241, 242)
r, g, b = 190, 18, 60
else:
pdf.set_fill_color(240, 253, 244)
r, g, b = 21, 128, 61
pdf.rect(10, pdf.get_y(), 190, 20, 'F')
pdf.set_y(pdf.get_y() + 4)
pdf.set_font('Arial', 'B', 13)
pdf.set_text_color(r, g, b)
result_text = 'DIABETIC RETINOPATHY DETECTED' if prediction == 'DR' else 'NO DIABETIC RETINOPATHY DETECTED'
pdf.cell(0, 8, result_text, ln=True, align='C')
pdf.set_font('Arial', '', 9)
pdf.set_text_color(100, 116, 139)
pdf.cell(0, 5,
f'DR Probability: {prob:.4f} ({prob:.1%}) | Confidence: {conf} | Threshold: 0.35',
ln=True, align='C')
pdf.ln(6)
pdf.set_font('Arial', 'B', 11)
pdf.set_text_color(15, 118, 110)
pdf.cell(0, 8, 'IMAGE ANALYSIS', ln=True)
img_y = pdf.get_y()
pdf.image(orig_path, x=10, y=img_y, w=58)
pdf.image(heat_path, x=76, y=img_y, w=58)
pdf.image(overlay_path, x=142, y=img_y, w=58)
pdf.set_y(img_y + 60)
pdf.set_font('Arial', '', 9)
pdf.set_text_color(100, 116, 139)
pdf.cell(63, 5, 'Preprocessed Image', align='C')
pdf.cell(63, 5, 'Grad-CAM Heatmap', align='C')
pdf.cell(63, 5, 'Overlay', align='C')
pdf.ln(12)
pdf.line(10, pdf.get_y(), 200, pdf.get_y())
pdf.ln(3)
pdf.set_font('Arial', 'I', 8)
pdf.set_text_color(120, 120, 120)
pdf.multi_cell(0, 5,
'Note: This report has been generated by an AI-assisted diagnostic tool '
'for clinical reference only. The findings presented are based on automated '
'image analysis and must be reviewed and verified by a qualified medical '
'professional before any clinical decision is made. AI results may not '
'account for all clinical factors. Final diagnosis remains the sole '
'responsibility of the treating physician.'
)
pdf_path = os.path.join(tmp_dir, 'report.pdf')
pdf.output(pdf_path)
with open(pdf_path, 'rb') as f:
pdf_bytes = f.read()
fname = f"DocSight_Report_{st.session_state.patient_id}.pdf"
st.download_button(
label = 'โฌ๏ธ Download PDF Report',
data = pdf_bytes,
file_name = fname,
mime = 'application/pdf'
)
st.success('PDF ready!')
# โโ Footer โโ
st.markdown("""
DocSight ยท EfficientNet-B4 ยท
APTOS 2019 + IDRiD ยท AUC 0.9986
""", unsafe_allow_html=True)