RakeshNJ12345 commited on
Commit
393cbcb
Β·
verified Β·
1 Parent(s): 50bdaa2

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +79 -102
src/streamlit_app.py CHANGED
@@ -1,162 +1,139 @@
1
- # app.py
2
  import os
3
- import torch
4
- import torch.nn as nn
5
- import torchvision.transforms as T
6
- import streamlit as st
7
- from PIL import Image
8
- from transformers import (
9
- ViTConfig, ViTModel,
10
- T5ForConditionalGeneration,
11
- T5Tokenizer,
12
- )
13
-
14
- # ─── FORCE ALL CACHE & CONFIG INTO /tmp ─────────────────────────────────────
15
  for ENV, VAL in [
16
- ("HOME", "/tmp"),
17
- ("XDG_CONFIG_HOME", "/tmp"),
18
- ("STREAMLIT_HOME", "/tmp"),
19
- ("XDG_CACHE_HOME", "/tmp"),
20
- ("HF_HOME", "/tmp/hf"),
21
- ("TRANSFORMERS_CACHE", "/tmp/hf/transformers"),
22
  ]:
23
  os.environ[ENV] = VAL
24
- os.makedirs("/tmp/streamlit", exist_ok=True)
25
- os.makedirs("/tmp/hf/transformers", exist_ok=True)
26
 
 
 
27
 
28
- # ─── YOUR HF MODEL REPO ───────────────────────────────────────────────────────
29
- HF_MODEL_ID = "RakeshNJ12345/Chest-Radiology"
30
 
 
 
 
 
 
 
 
 
31
 
32
  @st.cache_resource(show_spinner=False)
33
  def load_models():
34
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
35
 
36
- # 1) VIT: load its config, build fresh, then we'll load YOUR weights into it
37
- vit_cfg = ViTConfig.from_pretrained("google/vit-base-patch16-224")
38
- vit = ViTModel(vit_cfg)
39
 
40
- # 2) T5 + tokenizer: same idea, fresh + load YOUR weights
41
- t5 = T5ForConditionalGeneration.from_pretrained("t5-base")
42
  tok = T5Tokenizer.from_pretrained(HF_MODEL_ID)
43
 
44
- # 3) grab the single combined file from your repo
45
- state = torch.hub.load_state_dict_from_url(
46
- f"https://huggingface.co/{HF_MODEL_ID}/resolve/main/pytorch_model.bin",
47
- map_location="cpu", check_hash=True
48
- )
49
-
50
- # 4) split into vit vs t5 state_dicts
51
- vit_state = {k[len("vit."):]: v for k,v in state.items() if k.startswith("vit.")}
52
- t5_state = {k[len("t5."):]: v for k,v in state.items() if k.startswith("t5.")}
53
-
54
- # 5) load them
55
- vit.load_state_dict(vit_state, strict=False)
56
- t5.load_state_dict(t5_state, strict=False)
57
-
58
- # 6) move to device & eval
59
- vit.to(device).eval()
60
- t5.to(device).eval()
61
-
62
  return device, vit, t5, tok
63
 
64
-
65
  device, vit, t5, tokenizer = load_models()
66
 
67
-
68
- # ─── IMAGE PREPROCESSING ─────────────────────────────────────────────────────
69
  transform = T.Compose([
70
  T.Resize((224, 224)),
71
  T.ToTensor(),
72
  T.Normalize(mean=0.5, std=0.5),
73
  ])
74
 
75
-
76
- # ─── STREAMLIT LAYOUT ────────────────────────────────────────────────────────
77
- st.set_page_config(page_title="Radiology Report Analysis", layout="wide")
78
- st.markdown("<h1 style='text-align:center;'>🩺 Radiology Report Analysis</h1>",
79
  unsafe_allow_html=True)
80
- st.markdown(
81
- "<p style='text-align:center;'>Upload a chest X-ray (PNG/JPG) to generate an AI report.</p>",
82
- unsafe_allow_html=True
83
- )
84
 
85
  if "stage" not in st.session_state:
86
  st.session_state.stage = "upload"
87
 
88
-
89
- # ─── UPLOAD SCREEN ───────────────────────────────────────────────────────────
90
  if st.session_state.stage == "upload":
91
- up = st.file_uploader("", type=["png","jpg","jpeg"], label_visibility="collapsed")
92
- if up:
93
- st.image(up, width=350, caption=f"{up.name} β€” {up.size/1e6:.2f} MB")
 
 
 
 
 
94
  if st.button("▢️ Generate Report"):
95
- st.session_state.uploaded = up
96
  st.session_state.stage = "report"
97
  st.experimental_rerun()
98
 
99
-
100
- # ─── REPORT SCREEN ───────────────────────────────────────────────────────────
101
  elif st.session_state.stage == "report":
102
  img = Image.open(st.session_state.uploaded).convert("RGB")
103
 
104
  with st.spinner("πŸ”Ž Analyzing…"):
105
  # 1) ViT features
106
- x = transform(img).unsqueeze(0).to(device)
107
- vfeat = vit(pixel_values=x).pooler_output # [1,768]
108
 
109
- # 2) project into T5’s hidden size
110
- proj = nn.Linear(vfeat.size(-1), t5.config.d_model).to(device)
111
- prefix = proj(vfeat).unsqueeze(1) # [1,1,d_model]
112
 
113
- # 3) β€œreport:” token embeddings
114
  enc = tokenizer("report:", return_tensors="pt").to(device)
115
- txt_emb = t5.encoder.embed_tokens(enc.input_ids) # [1,L,d_model]
116
-
117
- # 4) concat + mask
118
- emb = torch.cat([prefix, txt_emb], dim=1) # [1,1+L,d]
119
- mask = torch.cat([
120
- torch.ones(1,1,device=device),
121
- enc.attention_mask
122
- ], dim=1) # [1,1+L]
123
-
124
- # 5) encode + generate
125
- enc_out = t5.encoder(inputs_embeds=emb, attention_mask=mask)
126
- ids = t5.generate(
127
- encoder_outputs = enc_out,
128
- encoder_attention_mask = mask,
129
- max_length = 64,
130
- num_beams = 1,
131
- do_sample = False,
132
- eos_token_id = tokenizer.eos_token_id,
133
- )
134
- report = tokenizer.decode(ids[0], skip_special_tokens=True)
135
-
136
- # ── DISPLAY ────────────────────────────────────────────────────────────────
 
 
 
 
137
  c1, c2 = st.columns(2)
138
  with c1:
139
- st.subheader("Your Uploaded X-ray")
140
  st.image(img, use_column_width=True)
141
- st.markdown(
142
- f"**File:** {st.session_state.uploaded.name} \n"
143
- f"**Size:** {st.session_state.uploaded.size/1e6:.2f} MB"
144
- )
145
  with c2:
146
- st.subheader("AI Diagnosis & Report")
147
  st.markdown(
148
  f"<div style='background:#e0f7fa;padding:12px;border-radius:6px;'>"
149
- f"<strong>Primary Diagnosis</strong><br>{report}</div>",
150
  unsafe_allow_html=True
151
  )
 
152
  if st.button("⬅️ Upload Another"):
153
  st.session_state.stage = "upload"
154
  del st.session_state.uploaded
155
  st.experimental_rerun()
156
 
 
157
  st.markdown("""
158
  <hr style='margin:2em 0;'>
159
  <p style='font-size:0.8em;color:gray;text-align:center;'>
160
- Powered by your fine-tuned ViTβž”T5, both coming from a single pytorch_model.bin in Chest-Radiology.
161
  </p>
162
- """, unsafe_allow_html=True)
 
1
+ # streamlit_app.py
2
  import os
3
+ # ─── force all HF/Streamlit caches into /tmp —──────────────────────────────────
 
 
 
 
 
 
 
 
 
 
 
4
  for ENV, VAL in [
5
+ ("HOME", "/tmp"),
6
+ ("XDG_CONFIG_HOME", "/tmp"),
7
+ ("STREAMLIT_HOME", "/tmp"),
8
+ ("XDG_CACHE_HOME", "/tmp"),
9
+ ("HF_HOME", "/tmp/hf"),
10
+ ("TRANSFORMERS_CACHE","/tmp/hf/transformers"),
11
  ]:
12
  os.environ[ENV] = VAL
 
 
13
 
14
+ for d in ("/tmp/streamlit", "/tmp/hf/transformers"):
15
+ os.makedirs(d, exist_ok=True)
16
 
 
 
17
 
18
+ import streamlit as st
19
+ from PIL import Image
20
+ import torch
21
+ import torchvision.transforms as T
22
+ from transformers import ViTModel, T5ForConditionalGeneration, T5Tokenizer
23
+
24
+ # ─── point at your 1.2 GB model repo, NOT this Space —──────────────────────────
25
+ HF_MODEL_ID = "RakeshNJ12345/Chest-Radiology"
26
 
27
  @st.cache_resource(show_spinner=False)
28
  def load_models():
29
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
30
 
31
+ # 1) Vision trunk (fine‐tuned ViT weights under `vit/` in your model repo)
32
+ vit = ViTModel.from_pretrained(f"{HF_MODEL_ID}/vit").to(device)
 
33
 
34
+ # 2) T5 + tokenizer (your fine‐tuned report generator)
35
+ t5 = T5ForConditionalGeneration.from_pretrained(HF_MODEL_ID).to(device)
36
  tok = T5Tokenizer.from_pretrained(HF_MODEL_ID)
37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  return device, vit, t5, tok
39
 
 
40
  device, vit, t5, tokenizer = load_models()
41
 
42
+ # ─── preprocessing for ViT —────────────────────────────────────────────────────
 
43
  transform = T.Compose([
44
  T.Resize((224, 224)),
45
  T.ToTensor(),
46
  T.Normalize(mean=0.5, std=0.5),
47
  ])
48
 
49
+ # ─── Streamlit layout —─────────────────────────────────────────────────────────
50
+ st.set_page_config(page_title="AI Chest X-Ray Report", layout="wide")
51
+ st.markdown("<h1 style='text-align:center;'>AI Chest X-Ray Report</h1>", unsafe_allow_html=True)
52
+ st.markdown("<p style='text-align:center;'>Upload a chest X-ray (PNG/JPG) to generate a report.</p>",
53
  unsafe_allow_html=True)
 
 
 
 
54
 
55
  if "stage" not in st.session_state:
56
  st.session_state.stage = "upload"
57
 
58
+ # ─── UPLOAD SCREEN ─────────────────────────────────────────────────────────────
 
59
  if st.session_state.stage == "upload":
60
+ uploaded = st.file_uploader(
61
+ "πŸ“€ Upload your chest X-ray",
62
+ type=["png","jpg","jpeg"],
63
+ label_visibility="collapsed"
64
+ )
65
+ if uploaded:
66
+ st.image(uploaded, width=350,
67
+ caption=f"{uploaded.name} β€” {uploaded.size/1e6:.2f} MB")
68
  if st.button("▢️ Generate Report"):
69
+ st.session_state.uploaded = uploaded
70
  st.session_state.stage = "report"
71
  st.experimental_rerun()
72
 
73
+ # ─── REPORT SCREEN ─────────────────────────────────────────────────────────────
 
74
  elif st.session_state.stage == "report":
75
  img = Image.open(st.session_state.uploaded).convert("RGB")
76
 
77
  with st.spinner("πŸ”Ž Analyzing…"):
78
  # 1) ViT features
79
+ x = transform(img).unsqueeze(0).to(device)
80
+ vit_out = vit(pixel_values=x).pooler_output # [1,768]
81
 
82
+ # 2) project to T5 hidden size
83
+ proj = torch.nn.Linear(vit_out.size(-1), t5.config.d_model).to(device)
84
+ vision_pf = proj(vit_out).unsqueeze(1) # [1,1,d_model]
85
 
86
+ # 3) fixed β€œreport:” prefix
87
  enc = tokenizer("report:", return_tensors="pt").to(device)
88
+ txt_emb = t5.encoder.embed_tokens(enc.input_ids) # [1,L,d_model]
89
+
90
+ # 4) build encoder inputs/mask
91
+ enc_emb = torch.cat([vision_pf, txt_emb], dim=1) # [1,1+L,d]
92
+ enc_mask = torch.cat([
93
+ torch.ones(1,1,device=device,dtype=torch.long),
94
+ enc.attention_mask
95
+ ], dim=1) # [1,1+L]
96
+
97
+ # 5) run encoder
98
+ enc_out = t5.encoder(inputs_embeds=enc_emb,
99
+ attention_mask=enc_mask)
100
+
101
+ # 6) generate (greedy β†’ no reorder errors)
102
+ out_ids = t5.generate(
103
+ encoder_outputs = enc_out,
104
+ encoder_attention_mask = enc_mask,
105
+ max_length = 64,
106
+ num_beams = 1,
107
+ do_sample = False,
108
+ eos_token_id = tokenizer.eos_token_id,
109
+ )
110
+ diagnosis = tokenizer.decode(out_ids[0], skip_special_tokens=True)
111
+ confidence = "–" # you can compute or leave blank
112
+
113
+ # ── display side-by-side ─────────────────────────────────────────────────────
114
  c1, c2 = st.columns(2)
115
  with c1:
116
+ st.subheader("Your X-Ray")
117
  st.image(img, use_column_width=True)
118
+ st.markdown(f"**File:** {st.session_state.uploaded.name} \n"
119
+ f"**Size:** {st.session_state.uploaded.size/1e6:.2f} MB")
 
 
120
  with c2:
121
+ st.subheader("AI Report")
122
  st.markdown(
123
  f"<div style='background:#e0f7fa;padding:12px;border-radius:6px;'>"
124
+ f"<strong>Primary Impression</strong><br>{diagnosis}</div>",
125
  unsafe_allow_html=True
126
  )
127
+ st.markdown(f"**Confidence:** {confidence}")
128
  if st.button("⬅️ Upload Another"):
129
  st.session_state.stage = "upload"
130
  del st.session_state.uploaded
131
  st.experimental_rerun()
132
 
133
+ # ─── footer —───────────────────────────────────────────────────────────────────
134
  st.markdown("""
135
  <hr style='margin:2em 0;'>
136
  <p style='font-size:0.8em;color:gray;text-align:center;'>
137
+ Powered by a fine-tuned ViT + T5 loaded from your model repo.
138
  </p>
139
+ """, unsafe_allow_html=True)