Singularity666 commited on
Commit
edd8d6d
·
1 Parent(s): 83eab98

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +118 -43
app.py CHANGED
@@ -1,29 +1,115 @@
1
  import streamlit as st
 
 
 
2
  from PIL import Image
3
  import numpy as np
4
- import main
5
- import pandas as pd
6
- import cv2
7
-
8
- def get_image_np(uploaded_file):
9
- image = Image.open(uploaded_file)
10
- return np.array(image)
11
-
12
- def show_predicted_caption(image_np, top_k=1):
13
- image = cv2.cvtColor(image_np, cv2.COLOR_RGB2BGR)
14
- captions = predict_caption(image, model, text_embeddings, valid_df['caption'].values, n=top_k)
15
- return captions
16
-
17
- # Load the model and text embeddings
18
- valid_df = pd.read_csv('testing_df.csv')
19
- model, text_embeddings = main.get_text_embeddings(valid_df)
20
-
21
- # App code
22
- st.title("Medical Radiology Report Generator")
23
-
24
- st.header("Personal Information")
25
- first_name = st.text_input("First Name", "John")
26
- last_name = st.text_input("Last Name", "Doe")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  age = st.number_input("Age", min_value=0, max_value=120, value=25, step=1)
28
  gender = st.selectbox("Gender", ["Male", "Female", "Other"])
29
 
@@ -37,7 +123,7 @@ if uploaded_file is not None:
37
  if st.button("Generate Caption"):
38
  with st.spinner("Generating caption..."):
39
  image_np = np.array(image)
40
- caption = show_predicted_caption(image_np)[0]
41
 
42
  st.success(f"Caption: {caption}")
43
 
@@ -55,22 +141,11 @@ if uploaded_file is not None:
55
 
56
  # Advanced Feedback System
57
  st.header("Advanced Feedback System")
58
- feedback_options = ["Better", "Satisfied", "Worse"]
59
- feedback = st.radio("Rate the generated report:", feedback_options)
60
-
61
- top_k = 1
62
- while feedback == "Worse":
63
- top_k += 1
64
- with st.spinner("Regenerating report..."):
65
- new_caption = show_predicted_caption(image_np, top_k=top_k)[-1]
66
- radiology_report = generate_radiology_report(f"Write Complete Radiology Report for this: {new_caption}")
67
-
68
- radiology_report_with_personal_info = f"Patient Name: {first_name} {last_name}\nAge: {age}\nGender: {gender}\n\n{radiology_report}"
69
-
70
- with container:
71
- container.empty()
72
- st.header("Radiology Report")
73
- st.write(radiology_report_with_personal_info)
74
- st.markdown(download_link(save_as_docx(radiology_report_with_personal_info, "radiology_report.docx"), "radiology_report.docx", "Download Report as DOCX"), unsafe_allow_html=True)
75
-
76
- feedback = st.radio("Rate the generated report:", feedback_options)
 
1
  import streamlit as st
2
+ import pickle
3
+ import pandas as pd
4
+ import torch
5
  from PIL import Image
6
  import numpy as np
7
+ from main import predict_caption, CLIPModel, get_text_embeddings
8
+ import openai
9
+ import base64
10
+ from docx import Document
11
+ from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
12
+ from io import BytesIO
13
+
14
+ # Set up OpenAI API
15
+ openai.api_key = "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"
16
+
17
+ # Custom CSS for the page
18
+ st.markdown(
19
+ """
20
+ <style>
21
+ body {
22
+ background-color: transparent;
23
+ }
24
+ .container {
25
+ display: flex;
26
+ justify-content: center;
27
+ align-items: center;
28
+ background-color: rgba(255, 255, 255, 0.7);
29
+ border-radius: 15px;
30
+ padding: 20px;
31
+ }
32
+ .stApp {
33
+ background-color: transparent;
34
+ }
35
+ .stText, .stMarkdown, .stTextInput>label, .stButton>button>span {
36
+ color: #1c1c1c !important; /* Set the dark text color for text elements */
37
+ }
38
+ .stButton>button>span {
39
+ color: initial !important; /* Reset the text color for the 'Generate Caption' button */
40
+ }
41
+ .stMarkdown h1, .stMarkdown h2 {
42
+ color: #ff6b81 !important; /* Set the text color of h1 and h2 elements to soft red-pink */
43
+ font-weight: bold; /* Set the font weight to bold */
44
+ border: 2px solid #ff6b81; /* Add a bold border around the headers */
45
+ padding: 10px; /* Add padding to the headers */
46
+ border-radius: 5px; /* Add border-radius to the headers */
47
+ }
48
+ </style>
49
+ """,
50
+ unsafe_allow_html=True,
51
+ )
52
+
53
+ device = torch.device("cpu")
54
+
55
+ testing_df = pd.read_csv("testing_df.csv")
56
+ model = CLIPModel().to(device)
57
+ model.load_state_dict(torch.load("weights.pt", map_location=torch.device('cpu')))
58
+ text_embeddings = torch.load('saved_text_embeddings.pt', map_location=device)
59
+
60
+ # Initialize the session state
61
+ if 'user_input' not in st.session_state:
62
+ st.session_state.user_input = ''
63
+ if 'chat_history' not in st.session_state:
64
+ st.session_state.chat_history = []
65
+
66
+ def show_predicted_caption(image):
67
+ matches = predict_caption(
68
+ image, model, text_embeddings, testing_df["caption"]
69
+ )[0]
70
+ return matches
71
+
72
+ def generate_radiology_report(prompt):
73
+ response = openai.Completion.create(
74
+ engine="text-davinci-003",
75
+ prompt=prompt,
76
+ max_tokens=800,
77
+ n=1,
78
+ stop=None,
79
+ temperature=1,
80
+ )
81
+ return response.choices[0].text.strip()
82
+
83
+ def chatbot_response(prompt):
84
+ response = openai.Completion.create(
85
+ engine="text-davinci-003",
86
+ prompt=prompt,
87
+ max_tokens=500,
88
+ n=1,
89
+ stop=None,
90
+ temperature=0.8,
91
+ )
92
+ return response.choices[0].text.strip()
93
+
94
+ def save_as_docx(text, filename):
95
+ document = Document()
96
+ document.add_paragraph(text)
97
+ with BytesIO() as output:
98
+ document.save(output)
99
+ output.seek(0)
100
+ return output.getvalue()
101
+
102
+ def download_link(content, filename, link_text):
103
+ b64 = base64.b64encode(content).decode()
104
+ href = f'<a href="data:application/octet-stream;base64,{b64}" download="{filename}">{link_text}</a>'
105
+ return href
106
+
107
+ st.title("RadiXGPT: An Evolution of machine doctors towards Radiology")
108
+
109
+ # Collect user's personal information
110
+ st.subheader("Personal Information")
111
+ first_name = st.text_input("First Name")
112
+ last_name = st.text_input("Last Name")
113
  age = st.number_input("Age", min_value=0, max_value=120, value=25, step=1)
114
  gender = st.selectbox("Gender", ["Male", "Female", "Other"])
115
 
 
123
  if st.button("Generate Caption"):
124
  with st.spinner("Generating caption..."):
125
  image_np = np.array(image)
126
+ caption = show_predicted_caption(image_np)
127
 
128
  st.success(f"Caption: {caption}")
129
 
 
141
 
142
  # Advanced Feedback System
143
  st.header("Advanced Feedback System")
144
+ st.write("Provide feedback on the RadiXGPT system to help it learn and adapt to technical terms:")
145
+ feedback = st.text_area("Enter your feedback here...")
146
+
147
+ if st.button("Submit Feedback"):
148
+ st.success("Thank you for your feedback! Your input helps us improve the RadiXGPT system.")
149
+ # Add your feedback processing logic here
150
+ # This could include updating the model with the new information,
151
+ # logging the feedback, or triggering an alert for manual review