tousin23 commited on
Commit
7569ad7
·
verified ·
1 Parent(s): fe26267

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +133 -51
app.py CHANGED
@@ -1,54 +1,136 @@
1
- import streamlit as st
 
 
 
 
2
  import torch
3
- import torchvision.transforms as transforms
4
- from torchvision.models import resnet50
5
  from PIL import Image
6
- import requests
7
- from io import BytesIO
8
-
9
- # Load the pre-trained ResNet-50 model
10
- model = resnet50(pretrained=True)
11
- model.eval()
12
-
13
- # Define the image transforms
14
- transform = transforms.Compose([
15
- transforms.Resize(256),
16
- transforms.CenterCrop(224),
17
- transforms.ToTensor(),
18
- transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
19
- ])
20
-
21
- # Define the label map for ImageNet classes
22
- LABELS_URL = "https://raw.githubusercontent.com/anishathalye/imagenet-simple-labels/master/imagenet-simple-labels.json"
23
- response = requests.get(LABELS_URL)
24
- labels = response.json()
25
-
26
- # Streamlit UI
27
- st.title("Image Classification with Pre-trained ResNet-50")
28
- st.write("Upload an image and the model will predict the class of the object in the image.")
29
-
30
- # File uploader
31
- uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
32
-
33
- if uploaded_file is not None:
34
- # Open the image file
35
- image = Image.open(uploaded_file)
36
-
37
- # Display the image
38
- st.image(image, caption='Uploaded Image', use_column_width=True)
39
- st.write("")
40
- st.write("Classifying...")
41
-
42
- # Preprocess the image
43
- image = transform(image).unsqueeze(0)
44
-
45
- # Predict the class
46
- with torch.no_grad():
47
- outputs = model(image)
48
-
49
- # Get the predicted class
50
- _, predicted = torch.max(outputs, 1)
51
- predicted_class = labels[predicted.item()]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
53
- # Display the result
54
- st.write(f"Predicted Class: {predicted_class}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from pprint import pprint
3
+ from configs.config import parser
4
+ from dataset.data_module import DataModule
5
+ from models.R2GenGPT import R2GenGPT
6
  import torch
7
+ from transformers import BertTokenizer, AutoImageProcessor
 
8
  from PIL import Image
9
+ import numpy as np
10
+ import streamlit as st
11
+ from lightning.pytorch import seed_everything
12
+
13
+ # Initialize the app
14
+ # st.title("Chest X-ray Report Generator")
15
+
16
+ # Function to load the model
17
+ def load_model(args):
18
+ model = R2GenGPT(args)
19
+ model.eval()
20
+ model.freeze()
21
+ return model
22
+
23
+ # Function to parse image
24
+ def _parse_image(vit_feature_extractor, img):
25
+ pixel_values = vit_feature_extractor(img, return_tensors="pt").pixel_values
26
+ return pixel_values[0]
27
+
28
+ # Function to generate predictions
29
+ def generate_predictions(image_path, vit_feature_extractor, model):
30
+ model.llama_tokenizer.padding_side = "right"
31
+
32
+ with Image.open(image_path) as pil:
33
+ array = np.array(pil, dtype=np.uint8)
34
+ if array.shape[-1] != 3 or len(array.shape) != 3:
35
+ array = np.array(pil.convert("RGB"), dtype=np.uint8)
36
+ image = _parse_image(vit_feature_extractor, array)
37
+ image = image.unsqueeze(0)
38
+ # image = image[None, :]
39
+ image = image.to(device='cuda:0')
40
+
41
+ print("Model Encoding for Image: ", model.encode_img(image))
42
+ try:
43
+ img_embeds, atts_img = model.encode_img(image)
44
+ print("Image embeddings in try blk", img_embeds)
45
+
46
+ print("Try block for Image Embeddings \n")
47
+
48
+ except Exception as e:
49
+ st.error(e)
50
+ print(st.error(e))
51
+ print("Except block for Image embeddings \n")
52
+ # return []
53
+
54
+ img_embeds = model.layer_norm(img_embeds)
55
+ img_embeds, atts_img = model.prompt_wrap(img_embeds, atts_img)
56
+ print("Image embeddings: ", img_embeds)
57
+
58
+
59
+ batch_size = img_embeds.shape[0]
60
+ print("Batch size printed: ", batch_size)
61
+ bos = torch.ones([batch_size, 1],
62
+ dtype=atts_img.dtype,
63
+ device=atts_img.device) * model.llama_tokenizer.bos_token_id
64
+ bos_embeds = model.embed_tokens(bos)
65
+ atts_bos = atts_img[:, :1]
66
+ print("Attention: ", atts_bos)
67
+
68
+ inputs_embeds = torch.cat([bos_embeds, img_embeds], dim=1)
69
+ print("Shape of Input emb", inputs_embeds)
70
+ inputs_embeds = inputs_embeds.type(torch.float16)
71
+ attention_mask = torch.cat([atts_bos, atts_img], dim=1)
72
+ print("Shape of Attention mask: ", attention_mask)
73
+
74
+ try:
75
+ with torch.no_grad():
76
+ outputs = model.llama_model.generate(inputs_embeds=inputs_embeds)
77
+ print("output", outputs)
78
+ except Exception as e:
79
+ st.error(e)
80
+ return []
81
+
82
+ hypo = [model.decode(i) for i in outputs]
83
+ print("Generated Report :", hypo)
84
+ return hypo
85
+
86
+ # Function to perform inference
87
+ def inference(args, uploaded_file):
88
+ model = load_model(args)
89
+ vit_feature_extractor = AutoImageProcessor.from_pretrained(args.vision_model)
90
 
91
+ with open("/workspace/p10_p10046166_s50051329_427446c1-881f5cce-85191ce1-91a58ba9-0a57d3f5.jpg", "wb") as f:
92
+ f.write(uploaded_file.getbuffer())
93
+
94
+ predictions = generate_predictions("/workspace/p10_p10046166_s50051329_427446c1-881f5cce-85191ce1-91a58ba9-0a57d3f5.jpg", vit_feature_extractor, model)
95
+ print("Predictions: ", predictions)
96
+ os.remove("/workspace/p10_p10046166_s50051329_427446c1-881f5cce-85191ce1-91a58ba9-0a57d3f5.jpg")
97
+
98
+ return predictions
99
+
100
+ # Main function
101
+ def main():
102
+ #parser = argparse.ArgumentParser()
103
+ # other arguments
104
+ #parser.add_argument('--file', type=open, action=LoadFromFile)
105
+
106
+ args = parser.parse_args()
107
+ pprint(vars(args))
108
+ seed_everything(42, workers=True)
109
+
110
+ # File uploader for image
111
+ model = load_model(args)
112
+ vit_feature_extractor = AutoImageProcessor.from_pretrained(args.vision_model)
113
+ predictions = generate_predictions("/workspace/p10_p10046166_s57379357_6e511483-c7e1601c-76890b2f-b0c6b55d-e53bcbf6.jpg", vit_feature_extractor, model)
114
+ print("Predictions: ", predictions)
115
+
116
+ print("Inference: ", inference(args, "/workspace/p10_p10046166_s57379357_6e511483-c7e1601c-76890b2f-b0c6b55d-e53bcbf6.jpg"))
117
+ #uploaded_file = st.file_uploader("Choose a chest X-ray image...", type="jpg")
118
+
119
+ #if uploaded_file is not None:
120
+ # st.image(uploaded_file, caption='Uploaded Image.', use_column_width=True)
121
+ # st.write("")
122
+ # st.write("Generating report...")
123
+
124
+ #predictions = inference(args, uploaded_file)
125
+
126
+ # if predictions:
127
+ # st.write("Generated Report:")
128
+
129
+ # for pred in predictions:
130
+ # print("Generated Report", pred)
131
+ # st.write(pred)
132
+ # else:
133
+ # st.write("Failed to generate report.")
134
+
135
+ if __name__ == '__main__':
136
+ main()