File size: 5,809 Bytes
f9f1b17
 
 
 
 
 
b5ebf36
 
 
ec9f2f1
36b2997
 
473583b
5db06e5
 
 
7107aca
f9f1b17
 
 
20f6840
295c6f3
 
 
b5ebf36
 
 
 
295c6f3
b5ebf36
 
 
c65c39d
 
 
 
 
20f6840
c65c39d
 
 
 
 
21fd28f
 
 
 
 
5a78ee4
20f6840
 
 
8908b27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9f1b17
 
 
 
 
7107aca
4eadb6d
f9f1b17
 
 
 
 
 
 
295c6f3
f9f1b17
 
 
 
 
 
295c6f3
b5ebf36
 
 
 
 
 
 
ec9f2f1
b5ebf36
 
 
295c6f3
b5ebf36
 
 
 
 
 
 
 
 
 
 
295c6f3
ad61148
 
 
 
 
 
 
b5ebf36
295c6f3
ad61148
 
 
 
b5ebf36
295c6f3
 
b5ebf36
f9f1b17
 
 
 
 
 
 
36b2997
 
f9f1b17
 
295c6f3
f9f1b17
 
295c6f3
ad61148
 
36b2997
 
 
 
 
 
 
 
473583b
36b2997
295c6f3
 
 
 
 
 
 
bb947d6
295c6f3
 
 
 
 
 
bb947d6
295c6f3
 
 
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
import streamlit as st
import pickle
import pandas as pd
import torch
from PIL import Image
import numpy as np
from main import predict_caption, CLIPModel, get_text_embeddings
import openai
import base64
from docx import Document
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from io import BytesIO

# Set up OpenAI API
openai.api_key = "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"

# Custom CSS for the page
st.markdown(
    """
<style>
    @import url('https://fonts.googleapis.com/css2?family=Roboto+Mono&display=swap');
    body {
        background-color: transparent;
    }
    .container {
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: rgba(255, 255, 255, 0.7);
        border-radius: 15px;
        padding: 20px;
    }
    .stApp {
        background-color: transparent;
    }
    .stText, .stMarkdown, .stTextInput>label, .stButton>button>span {
        color: #1c1c1c !important; /* Set the dark text color for text elements */
        font-family: 'Roboto Mono', monospace;
    }
    .stButton>button>span {
        color: initial !important; /* Reset the text color for the 'Generate Caption' button */
    }
    .stMarkdown h1, .stMarkdown h2 {
        color: #ff6b81 !important; /* Set the text color of h1 and h2 elements to soft red-pink */
        font-weight: bold; /* Set the font weight to bold */
        border: 2px solid #ff6b81; /* Add a bold border around the headers */
        padding: 10px; /* Add padding to the headers */
        border-radius: 5px; /* Add border-radius to the headers */
    }
    .stMarkdown p {
        font-family: 'Roboto Mono', monospace;
    }

    /* Animations */
    @keyframes fadeIn {
        from {opacity: 0;}
        to {opacity: 1;}
    }

    .stMarkdown h1 {
        animation: fadeIn 1s linear 0s 1 normal forwards;
    }

    .stMarkdown h2 {
        animation: fadeIn 1s linear 1s 1 normal forwards;
    }

    .stMarkdown p {
        animation: fadeIn 1s linear 2s 1 normal forwards;
    }
</style>
""",
    unsafe_allow_html=True,
)



device = torch.device("cpu")

testing_df = pd.read_csv("testing_df.csv")
model = CLIPModel().to(device)
model.load_state_dict(torch.load("weights.pt", map_location=torch.device('cpu')))
text_embeddings = torch.load('saved_text_embeddings.pt', map_location=device)


def show_predicted_caption(image):
    matches = predict_caption(
        image, model, text_embeddings, testing_df["caption"]
    )[0]
    return matches


def generate_radiology_report(prompt):
    response = openai.Completion.create(
        engine="text-davinci-003",
        prompt=prompt,
        max_tokens=800,
        n=1,
        stop=None,
        temperature=1,
    )
    return response.choices[0].text.strip()


def chatbot_response(prompt):
    response = openai.Completion.create(
        engine="text-davinci-003",
        prompt=prompt,
        max_tokens=500,
        n=1,
        stop=None,
        temperature=0.8,
    )
    return response.choices[0].text.strip()

# Add this function to your code
def save_as_docx(text, filename):
    document = Document()
    document.add_paragraph(text)
    with BytesIO() as output:
        document.save(output)
        output.seek(0)
        return output.getvalue()

# Add this function to your code
def download_link(content, filename, link_text):
    b64 = base64.b64encode(content).decode()
    href = f'<a href="data:application/octet-stream;base64,{b64}" download="{filename}">{link_text}</a>'
    return href


st.title("RadiXGPT: An Evolution of machine doctors towards Radiology")
st.write("Upload Scan to get Radiological Report:")

uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "png", "jpeg"])
if uploaded_file is not None:
    image = Image.open(uploaded_file)
    st.image(image, caption="Uploaded Image", use_column_width=True)
    st.write("")

    if st.button("Generate Caption"):
        with st.spinner("Generating caption..."):
            image_np = np.array(image)
            caption = show_predicted_caption(image_np)
           
            st.success(f"Caption: {caption}")

            # Add the OpenAI API call here and generate the radiology report
            radiology_report = generate_radiology_report(f"Write Complete Radiology Report for this: {caption}")
            container = st.container()
            with container:
                st.header("Radiology Report")
                st.write(radiology_report)
                st.markdown(download_link(save_as_docx(radiology_report, "radiology_report.docx"), "radiology_report.docx", "Download Report as DOCX"), unsafe_allow_html=True)
            
            # Add the chatbot functionality
            st.header("1-to-1 Consultation")
            st.write("Ask any questions you have about the radiology report:")

            user_input = st.text_input("Enter your question:")
            chat_history = []

            if user_input:
                chat_history.append({"user": user_input})

                if user_input.lower() == "thank you":
                    st.write("Bot: You're welcome! If you have any more questions, feel free to ask.")
                else:
                    # Add the OpenAI API call here and generate the answer to the user's question
                    prompt = f"Answer to the user's question based on the generated radiology report: {user_input}"
                    for history_item in chat_history:
                        prompt += f"\nUser: {history_item['user']}"
                        if 'bot' in history_item:
                            prompt += f"\nBot: {history_item['bot']}"

                    answer = chatbot_response(prompt)
                    chat_history[-1]["bot"] = answer
                    st.write(f"Bot: {answer}")